@kaynooo/cli-view 0.7.6 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/view.js +89 -1838
- package/package.json +9 -8
- package/src/code.ts +251 -0
- package/src/diff.ts +224 -0
- package/src/index.ts +6 -0
- package/src/markdown.ts +210 -0
- package/src/theme.ts +54 -0
- package/src/view.ts +202 -0
package/dist/view.js
CHANGED
|
@@ -1,929 +1,14 @@
|
|
|
1
1
|
#!/bin/sh
|
|
2
2
|
// @bun 2>/dev/null; exec bun --no-env-file --config=/dev/null "$0" "$@"
|
|
3
|
-
var __esm = (fn, res, err) => () => {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
err = [e];
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
return res;
|
|
13
|
-
};
|
|
14
|
-
|
|
15
|
-
// ../kit/src/mode.ts
|
|
16
|
-
import process2 from "process";
|
|
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
|
-
var MODES, AGENT_VARIABLES;
|
|
31
|
-
var init_mode = __esm(() => {
|
|
32
|
-
MODES = new Set(["terminal", "ci", "agent", "pipe"]);
|
|
33
|
-
AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
|
|
34
|
-
});
|
|
35
|
-
|
|
36
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
|
|
37
|
-
function b(r) {
|
|
38
|
-
let e = r.startsWith("#") ? r.slice(1) : r;
|
|
39
|
-
if (!G.test(e))
|
|
40
|
-
return [0, 0, 0];
|
|
41
|
-
if (e.length === 3 || e.length === 4)
|
|
42
|
-
return [Number.parseInt(e[0] + e[0], 16), Number.parseInt(e[1] + e[1], 16), Number.parseInt(e[2] + e[2], 16)];
|
|
43
|
-
if (e.length !== 6 && e.length !== 8)
|
|
44
|
-
throw Error(`Invalid hex color length: ${e.length}`);
|
|
45
|
-
return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
|
|
46
|
-
}
|
|
47
|
-
function C(r, e = globalThis.process?.env ?? {}) {
|
|
48
|
-
if (e.FORCE_COLOR !== undefined)
|
|
49
|
-
return h.has(e.FORCE_COLOR);
|
|
50
|
-
if (e.NO_COLOR !== undefined || e.NODE_DISABLE_COLORS !== undefined || e.TERM === "dumb")
|
|
51
|
-
return false;
|
|
52
|
-
return r?.isTTY === true;
|
|
53
|
-
}
|
|
54
|
-
function f(r, e = []) {
|
|
55
|
-
let l = "", n = "";
|
|
56
|
-
for (let t = 0, i = e.length;t < i; t++)
|
|
57
|
-
l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
|
|
58
|
-
let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
|
|
59
|
-
return new Proxy(c, { get(t, i) {
|
|
60
|
-
let a = B[i];
|
|
61
|
-
if (Array.isArray(a)) {
|
|
62
|
-
let s = g.get(i);
|
|
63
|
-
if (s === undefined)
|
|
64
|
-
s = f(r, [...e, a]), g.set(i, s);
|
|
65
|
-
return s;
|
|
66
|
-
}
|
|
67
|
-
if (typeof a === "function")
|
|
68
|
-
return (...s) => {
|
|
69
|
-
let y = `${i}:${s.join(",")}`, u = g.get(y);
|
|
70
|
-
if (u === undefined) {
|
|
71
|
-
if (g.size >= 64)
|
|
72
|
-
g.clear();
|
|
73
|
-
u = f(r, [...e, a(...s)]), g.set(y, u);
|
|
74
|
-
}
|
|
75
|
-
return u;
|
|
76
|
-
};
|
|
77
|
-
throw Error(`Unknown style: ${String(i)}`);
|
|
78
|
-
} });
|
|
79
|
-
}
|
|
80
|
-
function Fe(r = {}) {
|
|
81
|
-
return f(r);
|
|
82
|
-
}
|
|
83
|
-
var G, B, h, o;
|
|
84
|
-
var init_chunk_x450vn3m = __esm(() => {
|
|
85
|
-
G = /^[a-f0-9]+$/i;
|
|
86
|
-
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") => {
|
|
87
|
-
let [l, n, c] = b(r);
|
|
88
|
-
return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
|
|
89
|
-
}, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
|
|
90
|
-
h = new Set(["", "1", "2", "3", "true"]);
|
|
91
|
-
o = Fe();
|
|
92
|
-
});
|
|
93
|
-
|
|
94
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/tools/colors.js
|
|
95
|
-
var init_colors = __esm(() => {
|
|
96
|
-
init_chunk_x450vn3m();
|
|
97
|
-
});
|
|
98
|
-
|
|
99
|
-
// ../kit/src/config.ts
|
|
100
|
-
import { existsSync } from "fs";
|
|
101
|
-
import { dirname, join, resolve } from "path";
|
|
102
|
-
import process3 from "process";
|
|
103
|
-
function findUp(names, from = process3.cwd(), stop = () => false) {
|
|
104
|
-
const wanted = typeof names === "string" ? [names] : names;
|
|
105
|
-
for (let dir = resolve(from);; dir = dirname(dir)) {
|
|
106
|
-
const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
|
|
107
|
-
if (found !== undefined)
|
|
108
|
-
return found;
|
|
109
|
-
if (stop(dir) || dirname(dir) === dir)
|
|
110
|
-
return;
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
var init_config = __esm(() => {
|
|
114
|
-
init_args();
|
|
115
|
-
});
|
|
116
|
-
|
|
117
|
-
// ../kit/src/user-config.ts
|
|
118
|
-
import { homedir } from "os";
|
|
119
|
-
import { isAbsolute, join as join2 } from "path";
|
|
120
|
-
import process4 from "process";
|
|
121
|
-
function xdgFolder(value, fallback) {
|
|
122
|
-
return value !== undefined && isAbsolute(value) ? value : fallback;
|
|
123
|
-
}
|
|
124
|
-
function configBase(where = {}) {
|
|
125
|
-
const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
|
|
126
|
-
return xdgFolder(xdg, join2(where.home ?? homedir(), ".config"));
|
|
127
|
-
}
|
|
128
|
-
function userConfigPath(bin, where = {}) {
|
|
129
|
-
return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
|
|
130
|
-
}
|
|
131
|
-
var init_user_config = () => {};
|
|
132
|
-
|
|
133
|
-
// ../kit/src/theme.ts
|
|
134
|
-
import { existsSync as existsSync2, readFileSync, statSync } from "fs";
|
|
135
|
-
import { homedir as homedir2 } from "os";
|
|
136
|
-
import { join as join3, resolve as resolve2 } from "path";
|
|
137
|
-
import process5 from "process";
|
|
138
|
-
function toLinear(channel) {
|
|
139
|
-
const value = channel / 255;
|
|
140
|
-
return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
|
|
141
|
-
}
|
|
142
|
-
function toOklab(hex) {
|
|
143
|
-
const [r, g, b] = [1, 3, 5].map((at) => toLinear(Number.parseInt(hex.slice(at, at + 2), 16)));
|
|
144
|
-
const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
|
|
145
|
-
const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
|
|
146
|
-
const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
|
|
147
|
-
return [0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s, 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s, 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s];
|
|
148
|
-
}
|
|
149
|
-
function fromOklab([lightness, a, b]) {
|
|
150
|
-
const l = (lightness + 0.3963377774 * a + 0.2158037573 * b) ** 3;
|
|
151
|
-
const m = (lightness - 0.1055613458 * a - 0.0638541728 * b) ** 3;
|
|
152
|
-
const s = (lightness - 0.0894841775 * a - 1.291485548 * b) ** 3;
|
|
153
|
-
const channels = [4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s, -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s, -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s];
|
|
154
|
-
return `#${channels.map((channel) => fromLinear(channel).toString(16).padStart(2, "0")).join("")}`;
|
|
155
|
-
}
|
|
156
|
-
function gradientAt(theme, ratio) {
|
|
157
|
-
if (theme.gradient === undefined)
|
|
158
|
-
return;
|
|
159
|
-
const key = theme.gradient.join();
|
|
160
|
-
let ends = ENDS.get(key);
|
|
161
|
-
if (ends === undefined) {
|
|
162
|
-
ends = [toOklab(theme.gradient[0]), toOklab(theme.gradient[1])];
|
|
163
|
-
ENDS.set(key, ends);
|
|
164
|
-
}
|
|
165
|
-
const at = Math.min(1, Math.max(0, ratio));
|
|
166
|
-
const [from, to] = ends;
|
|
167
|
-
return fromOklab(from.map((start, index) => start + (to[index] - start) * at));
|
|
168
|
-
}
|
|
169
|
-
function isColorSpec(spec) {
|
|
170
|
-
if (typeof spec === "number")
|
|
171
|
-
return Number.isInteger(spec) && spec >= 0 && spec <= 255;
|
|
172
|
-
return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
|
|
173
|
-
}
|
|
174
|
-
function cubeLevel(channel) {
|
|
175
|
-
return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
|
|
176
|
-
}
|
|
177
|
-
function nearest256(hex) {
|
|
178
|
-
const rgb = [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
|
|
179
|
-
const levels = rgb.map(cubeLevel);
|
|
180
|
-
const cube = levels.map((level) => CUBE[level]);
|
|
181
|
-
const grey = Math.min(23, Math.max(0, Math.round((rgb.reduce((sum, channel) => sum + channel, 0) / 3 - 8) / 10)));
|
|
182
|
-
const greyValue = 8 + grey * 10;
|
|
183
|
-
const distance = (colour) => colour.reduce((sum, channel, at) => sum + (channel - rgb[at]) ** 2, 0);
|
|
184
|
-
return distance([greyValue, greyValue, greyValue]) < distance(cube) ? 232 + grey : 16 + 36 * levels[0] + 6 * levels[1] + levels[2];
|
|
185
|
-
}
|
|
186
|
-
function hasTrueColor(env) {
|
|
187
|
-
return env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
|
|
188
|
-
}
|
|
189
|
-
function tinted(colors, spec, env = process5.env) {
|
|
190
|
-
if (typeof spec === "number")
|
|
191
|
-
return colors.ansi256(spec);
|
|
192
|
-
return spec.trim().split(SPACES).reduce((chain, token) => {
|
|
193
|
-
if (HEX.test(token))
|
|
194
|
-
return hasTrueColor(env) ? chain.hex(token) : chain.ansi256(nearest256(token));
|
|
195
|
-
return chain[token] ?? chain;
|
|
196
|
-
}, colors);
|
|
197
|
-
}
|
|
198
|
-
function isRecord(value) {
|
|
199
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
200
|
-
}
|
|
201
|
-
function readThemeFile(path, warn) {
|
|
202
|
-
try {
|
|
203
|
-
const stat = statSync(path, { throwIfNoEntry: false });
|
|
204
|
-
if (stat === undefined)
|
|
205
|
-
return;
|
|
206
|
-
if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
|
|
207
|
-
warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
|
|
208
|
-
return;
|
|
209
|
-
}
|
|
210
|
-
const parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
211
|
-
if (isRecord(parsed))
|
|
212
|
-
return parsed;
|
|
213
|
-
warn(`${path} is not a JSON object, theme ignored`);
|
|
214
|
-
} catch (error) {
|
|
215
|
-
warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
|
|
216
|
-
}
|
|
217
|
-
return;
|
|
218
|
-
}
|
|
219
|
-
function applyPreset(theme, name, warn, where) {
|
|
220
|
-
if (name === undefined)
|
|
221
|
-
return;
|
|
222
|
-
if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
|
|
223
|
-
warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
|
|
224
|
-
return;
|
|
225
|
-
}
|
|
226
|
-
const preset = PRESETS[name];
|
|
227
|
-
Object.assign(theme.colors, preset.colors);
|
|
228
|
-
Object.assign(theme.glyphs, preset.glyphs);
|
|
229
|
-
if (preset.accents !== undefined)
|
|
230
|
-
theme.accents = [...preset.accents];
|
|
231
|
-
if (Object.hasOwn(preset, "gradient"))
|
|
232
|
-
theme.gradient = preset.gradient;
|
|
233
|
-
return name;
|
|
234
|
-
}
|
|
235
|
-
function applyFile(theme, file, where, warn) {
|
|
236
|
-
if (isRecord(file.colors)) {
|
|
237
|
-
for (const [key, value] of Object.entries(file.colors)) {
|
|
238
|
-
if (!Object.hasOwn(DEFAULT.colors, key))
|
|
239
|
-
warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
|
|
240
|
-
else if (!isColorSpec(value))
|
|
241
|
-
warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
|
|
242
|
-
else
|
|
243
|
-
theme.colors[key] = value;
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
if (isRecord(file.glyphs)) {
|
|
247
|
-
for (const [key, value] of Object.entries(file.glyphs)) {
|
|
248
|
-
if (!Object.hasOwn(DEFAULT.glyphs, key))
|
|
249
|
-
warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
|
|
250
|
-
else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
|
|
251
|
-
warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
|
|
252
|
-
else
|
|
253
|
-
theme.glyphs[key] = value;
|
|
254
|
-
}
|
|
255
|
-
}
|
|
256
|
-
if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
|
|
257
|
-
theme.accents = [...file.accents];
|
|
258
|
-
else if (file.accents !== undefined)
|
|
259
|
-
warn(`${where}: accents must be a non-empty list of colours`);
|
|
260
|
-
if (file.gradient === null)
|
|
261
|
-
theme.gradient = undefined;
|
|
262
|
-
else if (Array.isArray(file.gradient) && file.gradient.length === 2 && file.gradient.every((end) => typeof end === "string" && HEX.test(end)))
|
|
263
|
-
theme.gradient = [file.gradient[0], file.gradient[1]];
|
|
264
|
-
else if (file.gradient !== undefined)
|
|
265
|
-
warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);
|
|
266
|
-
if (isRecord(file.bins)) {
|
|
267
|
-
for (const [bin, value] of Object.entries(file.bins)) {
|
|
268
|
-
if (isColorSpec(value))
|
|
269
|
-
theme.bins[bin] = value;
|
|
270
|
-
else
|
|
271
|
-
warn(`${where}: bin ${bin} has no valid colour`);
|
|
272
|
-
}
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
function endsWalk(home) {
|
|
276
|
-
return (dir) => dir === resolve2(home) || existsSync2(join3(dir, ".git"));
|
|
277
|
-
}
|
|
278
|
-
function warnOnce(message) {
|
|
279
|
-
if (warned.has(message))
|
|
280
|
-
return;
|
|
281
|
-
warned.add(message);
|
|
282
|
-
console.error(`warning: theme ${message}`);
|
|
283
|
-
}
|
|
284
|
-
function isPath(chosen) {
|
|
285
|
-
return chosen.includes("/") || chosen.endsWith(".json");
|
|
286
|
-
}
|
|
287
|
-
function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(), warn = warnOnce } = {}) {
|
|
288
|
-
const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null), gradient: DEFAULT.gradient };
|
|
289
|
-
const sources = [];
|
|
290
|
-
const chosen = env.KIT_THEME ?? "";
|
|
291
|
-
const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
|
|
292
|
-
if (isPath(chosen))
|
|
293
|
-
wanted.push(resolve2(from, chosen));
|
|
294
|
-
const files = [];
|
|
295
|
-
for (const path of wanted) {
|
|
296
|
-
const file = path === undefined ? undefined : readThemeFile(path, warn);
|
|
297
|
-
if (path !== undefined && file !== undefined)
|
|
298
|
-
files.push({ path, file });
|
|
299
|
-
}
|
|
300
|
-
let preset = "default";
|
|
301
|
-
if (chosen !== "" && !isPath(chosen)) {
|
|
302
|
-
preset = applyPreset(theme, chosen, warn, "KIT_THEME") ?? preset;
|
|
303
|
-
} else {
|
|
304
|
-
const named = files.findLast(({ file }) => file.preset !== undefined);
|
|
305
|
-
if (named !== undefined)
|
|
306
|
-
preset = applyPreset(theme, named.file.preset, warn, named.path) ?? preset;
|
|
307
|
-
}
|
|
308
|
-
for (const { path, file } of files) {
|
|
309
|
-
applyFile(theme, file, path, warn);
|
|
310
|
-
sources.push(path);
|
|
311
|
-
}
|
|
312
|
-
return { theme, sources, preset };
|
|
313
|
-
}
|
|
314
|
-
function activeTheme() {
|
|
315
|
-
const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
|
|
316
|
-
if (current === undefined || key !== currentKey) {
|
|
317
|
-
current = loadTheme();
|
|
318
|
-
currentKey = key;
|
|
319
|
-
}
|
|
320
|
-
return current;
|
|
321
|
-
}
|
|
322
|
-
var fromLinear = (value) => Math.round(255 * Math.min(1, Math.max(0, value <= 0.0031308 ? value * 12.92 : 1.055 * value ** (1 / 2.4) - 0.055))), ENDS, DEFAULT, BRIGHT, MONO, ASCII, PRESETS, STYLES, HEX, CONTROL, MAX_FILE_BYTES, SPACES, CUBE, warned, current, currentKey = "";
|
|
323
|
-
var init_theme = __esm(() => {
|
|
324
|
-
init_config();
|
|
325
|
-
init_user_config();
|
|
326
|
-
ENDS = new Map;
|
|
327
|
-
DEFAULT = {
|
|
328
|
-
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" },
|
|
329
|
-
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" },
|
|
330
|
-
accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
|
|
331
|
-
bins: {},
|
|
332
|
-
gradient: ["#c084fc", "#67e8f9"]
|
|
333
|
-
};
|
|
334
|
-
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" };
|
|
335
|
-
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" };
|
|
336
|
-
ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
|
|
337
|
-
PRESETS = {
|
|
338
|
-
default: {},
|
|
339
|
-
"high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
|
|
340
|
-
mono: { colors: MONO, accents: ["bold"], gradient: undefined },
|
|
341
|
-
ascii: { glyphs: ASCII }
|
|
342
|
-
};
|
|
343
|
-
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"]);
|
|
344
|
-
HEX = /^#[0-9a-f]{6}$/i;
|
|
345
|
-
CONTROL = /\p{Cc}/u;
|
|
346
|
-
MAX_FILE_BYTES = 64 * 1024;
|
|
347
|
-
SPACES = /\s+/;
|
|
348
|
-
CUBE = [0, 95, 135, 175, 215, 255];
|
|
349
|
-
warned = new Set;
|
|
350
|
-
});
|
|
351
|
-
|
|
352
|
-
// ../kit/src/style.ts
|
|
353
|
-
import process6 from "process";
|
|
354
|
-
function takesControlCodes(stream, env = process6.env) {
|
|
355
|
-
return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
|
|
356
|
-
}
|
|
357
|
-
function paint(stream, env = process6.env) {
|
|
358
|
-
return Fe({ stream: { isTTY: takesControlCodes(stream, env) }, env });
|
|
359
|
-
}
|
|
360
|
-
function role(name, stream, env = process6.env) {
|
|
361
|
-
const colors = paint(stream, env);
|
|
362
|
-
return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
|
|
363
|
-
}
|
|
364
|
-
function link(text, url, stream, env = process6.env) {
|
|
365
|
-
if (takesControlCodes(stream, env))
|
|
366
|
-
return `\x1B]8;;${url}\x1B\\${text}\x1B]8;;\x1B\\`;
|
|
367
|
-
return text === url ? text : `${text} (${url})`;
|
|
368
|
-
}
|
|
369
|
-
var STATUS_WORDS, STATUS_OF;
|
|
370
|
-
var init_style = __esm(() => {
|
|
371
|
-
init_colors();
|
|
372
|
-
init_mode();
|
|
373
|
-
init_theme();
|
|
374
|
-
STATUS_WORDS = {
|
|
375
|
-
passed: ["passed", "success", "succeeded", "ok"],
|
|
376
|
-
failed: ["failed", "failure", "error", "errored"],
|
|
377
|
-
running: ["running", "in_progress", "started", "holding"],
|
|
378
|
-
queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
|
|
379
|
-
skipped: ["skipped", "cancelled", "canceled", "manual"]
|
|
380
|
-
};
|
|
381
|
-
STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
|
|
382
|
-
});
|
|
383
|
-
|
|
384
|
-
// ../kit/src/format.ts
|
|
385
|
-
import process7 from "process";
|
|
386
|
-
function formatSeconds(total) {
|
|
387
|
-
let rest = Math.max(0, Math.round(total));
|
|
388
|
-
const amounts = UNITS.map(([unit, size]) => {
|
|
389
|
-
const amount = Math.floor(rest / size);
|
|
390
|
-
rest -= amount * size;
|
|
391
|
-
return `${amount}${unit}`;
|
|
392
|
-
});
|
|
393
|
-
const first = amounts.findIndex((amount) => !amount.startsWith("0"));
|
|
394
|
-
if (first === -1)
|
|
395
|
-
return "0s";
|
|
396
|
-
const next = amounts[first + 1];
|
|
397
|
-
return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
|
|
398
|
-
}
|
|
399
|
-
function formatDuration(ms) {
|
|
400
|
-
return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
|
|
401
|
-
}
|
|
402
|
-
function upTo(text, separator) {
|
|
403
|
-
const end = text.indexOf(separator);
|
|
404
|
-
return end === -1 ? text : text.slice(0, end);
|
|
405
|
-
}
|
|
406
|
-
function textWidth(text) {
|
|
407
|
-
return Bun.stringWidth(text);
|
|
408
|
-
}
|
|
409
|
-
function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
|
|
410
|
-
return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
|
|
411
|
-
}
|
|
412
|
-
function printJson(value) {
|
|
413
|
-
console.log(jsonText(value));
|
|
414
|
-
}
|
|
415
|
-
var UNITS, ESCAPE;
|
|
416
|
-
var init_format = __esm(() => {
|
|
417
|
-
init_mode();
|
|
418
|
-
init_style();
|
|
419
|
-
UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
|
|
420
|
-
ESCAPE = String.fromCharCode(27);
|
|
421
|
-
});
|
|
422
|
-
|
|
423
|
-
// ../kit/src/help.ts
|
|
424
|
-
import process8 from "process";
|
|
425
|
-
function usageLine(usage, colors = paint(process8.stdout), { summary: withSummary = true } = {}) {
|
|
426
|
-
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
427
|
-
`);
|
|
428
|
-
const blank = lines.indexOf("");
|
|
429
|
-
const synopses = blank === -1 ? lines : lines.slice(0, blank);
|
|
430
|
-
const details = blank === -1 ? [] : lines.slice(blank + 1);
|
|
431
|
-
const colon = synopses[0].indexOf(": ");
|
|
432
|
-
const inline = synopses[0].slice(colon + 2);
|
|
433
|
-
const summary = colon === -1 ? details.shift() : `${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;
|
|
434
|
-
if (colon !== -1)
|
|
435
|
-
synopses[0] = synopses[0].slice(0, colon);
|
|
436
|
-
const head = `${colors.bold("Usage:")} ${synopses.map((line) => line.replaceAll(OPTIONAL, (part) => colors.dim(part))).join(`
|
|
437
|
-
`)}`;
|
|
438
|
-
const lead = summary === undefined || !withSummary ? [] : ["", colors.bold(prose(summary, colors))];
|
|
439
|
-
const rest = details.length === 0 ? [] : ["", ...details.map((line) => prose(line, colors))];
|
|
440
|
-
return [head, ...lead, ...rest].join(`
|
|
441
|
-
`);
|
|
442
|
-
}
|
|
443
|
-
function prose(line, colors) {
|
|
444
|
-
if (colors.cyan("x") === "x")
|
|
445
|
-
return line;
|
|
446
|
-
return line.replaceAll(PROSE_MARKS, (match, code, flag) => code === undefined ? colors.cyan(flag ?? match) : colors.bold(code));
|
|
447
|
-
}
|
|
448
|
-
function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [], bin } = {}) {
|
|
449
|
-
const { summary } = description(usage);
|
|
450
|
-
const head = bin === undefined ? [usageLine(usage, colors)] : [`${colors.bold(bin.name)} ${colors.dim(bin.version())}${summary === "" ? "" : ` ${summary}`}`, "", usageLine(usage, colors, { summary: false })];
|
|
451
|
-
return [...head, "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
|
|
452
|
-
`);
|
|
453
|
-
}
|
|
454
|
-
function exitRows(exits, colors = paint(process8.stdout)) {
|
|
455
|
-
if (exits.length === 0)
|
|
456
|
-
return [];
|
|
457
|
-
return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
|
|
458
|
-
}
|
|
459
|
-
function wantsHelpJson(env = process8.env) {
|
|
460
|
-
return env.KIT_HELP === "json";
|
|
461
|
-
}
|
|
462
|
-
function description(usage, { examples = [], replaces, exits } = {}, options) {
|
|
463
|
-
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
464
|
-
`);
|
|
465
|
-
const first = lines[0];
|
|
466
|
-
const colon = first.indexOf(": ");
|
|
467
|
-
const prose = lines[lines.indexOf("") + 1] ?? "";
|
|
468
|
-
const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
|
|
469
|
-
return {
|
|
470
|
-
synopsis: colon === -1 ? first : first.slice(0, colon),
|
|
471
|
-
summary: colon === -1 ? fallback : first.slice(colon + 2),
|
|
472
|
-
...replaces === undefined ? {} : { replaces },
|
|
473
|
-
examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
|
|
474
|
-
...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
|
|
475
|
-
...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
|
|
476
|
-
};
|
|
477
|
-
}
|
|
478
|
-
function exampleRows(examples, colors = paint(process8.stdout)) {
|
|
479
|
-
if (examples.length === 0 || outputMode() === "agent")
|
|
480
|
-
return [];
|
|
481
|
-
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
482
|
-
}
|
|
483
|
-
function optionRows(options, colors = paint(process8.stdout)) {
|
|
484
|
-
const rows = Object.entries(options).map(([name, option]) => {
|
|
485
|
-
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
486
|
-
const choices = option.choices?.join("|");
|
|
487
|
-
const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
|
|
488
|
-
const named = inline ? `<${choices}>` : "<value>";
|
|
489
|
-
const placeholder = option.optional === undefined ? named : `[${named}]`;
|
|
490
|
-
const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
|
|
491
|
-
const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
|
|
492
|
-
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
|
|
493
|
-
});
|
|
494
|
-
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
495
|
-
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
496
|
-
}
|
|
497
|
-
var OPTIONAL, USAGE_PREFIX, FULL_STOP, PROSE_MARKS, MAX_INLINE_CHOICES = 24;
|
|
498
|
-
var init_help = __esm(() => {
|
|
499
|
-
init_mode();
|
|
500
|
-
init_style();
|
|
501
|
-
OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
|
|
502
|
-
USAGE_PREFIX = /^usage:\s*/i;
|
|
503
|
-
FULL_STOP = /\.$/;
|
|
504
|
-
PROSE_MARKS = /`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;
|
|
505
|
-
});
|
|
506
|
-
|
|
507
|
-
// ../kit/src/text.ts
|
|
508
|
-
function stripAnsi(text) {
|
|
509
|
-
return text.replace(ANSI, "");
|
|
510
|
-
}
|
|
511
|
-
function stripControls(text) {
|
|
512
|
-
return text.replace(CONTROLS, "");
|
|
513
|
-
}
|
|
514
|
-
function escapeControls(text) {
|
|
515
|
-
return text.replace(CONTROLS, (char) => {
|
|
516
|
-
const code = char.charCodeAt(0);
|
|
517
|
-
if (code === 127)
|
|
518
|
-
return "^?";
|
|
519
|
-
return code < 128 ? `^${String.fromCharCode(code + 64)}` : `M-^${String.fromCharCode(code - 64)}`;
|
|
520
|
-
});
|
|
521
|
-
}
|
|
522
|
-
function distance(a, b) {
|
|
523
|
-
const left = [...a];
|
|
524
|
-
const right = [...b];
|
|
525
|
-
let before = [];
|
|
526
|
-
let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
|
|
527
|
-
for (const [i, x] of left.entries()) {
|
|
528
|
-
const current = [i + 1];
|
|
529
|
-
for (const [j, y] of right.entries()) {
|
|
530
|
-
let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
|
|
531
|
-
if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
|
|
532
|
-
cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
|
|
533
|
-
current.push(cost);
|
|
534
|
-
}
|
|
535
|
-
before = previous;
|
|
536
|
-
previous = current;
|
|
537
|
-
}
|
|
538
|
-
return previous[right.length] ?? 0;
|
|
539
|
-
}
|
|
540
|
-
function closest(name, names) {
|
|
541
|
-
const started = names.find((known) => known.startsWith(name));
|
|
542
|
-
if (started !== undefined)
|
|
543
|
-
return started;
|
|
544
|
-
const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
|
|
545
|
-
return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
|
|
546
|
-
}
|
|
547
|
-
var ANSI, CONTROLS;
|
|
548
|
-
var init_text = __esm(() => {
|
|
549
|
-
ANSI = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
|
|
550
|
-
CONTROLS = /[\x00-\x08\x0B-\x1F\x7F-\x9F]/g;
|
|
551
|
-
});
|
|
552
|
-
|
|
553
|
-
// ../kit/src/input.ts
|
|
554
|
-
import process9 from "process";
|
|
555
|
-
function wholeNumber(value, name, fallback, min = 1) {
|
|
556
|
-
if (value === undefined)
|
|
557
|
-
return fallback;
|
|
558
|
-
const number = Number(value);
|
|
559
|
-
if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
|
|
560
|
-
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
|
|
561
|
-
return number;
|
|
562
|
-
}
|
|
563
|
-
async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
|
|
564
|
-
if (path === "-") {
|
|
565
|
-
if (process9.stdin.isTTY)
|
|
566
|
-
fail(noStdin);
|
|
567
|
-
return Bun.stdin.text();
|
|
568
|
-
}
|
|
569
|
-
const file = Bun.file(path);
|
|
570
|
-
if (!await file.exists())
|
|
571
|
-
fail(`no file ${path}`);
|
|
572
|
-
return file.text();
|
|
573
|
-
}
|
|
574
|
-
var WHOLE;
|
|
575
|
-
var init_input = __esm(() => {
|
|
576
|
-
init_args();
|
|
577
|
-
WHOLE = /^\d+$/;
|
|
578
|
-
});
|
|
579
|
-
|
|
580
|
-
// ../kit/src/args.ts
|
|
581
|
-
import process10 from "process";
|
|
582
|
-
import { parseArgs } from "util";
|
|
583
|
-
function jsonOption(holds) {
|
|
584
|
-
return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
|
|
585
|
-
}
|
|
586
|
-
function fail(message, code = 2, hint) {
|
|
587
|
-
throw new Exit(message, code, hint);
|
|
588
|
-
}
|
|
589
|
-
function badUsage(message) {
|
|
590
|
-
throw new UsageError(message);
|
|
591
|
-
}
|
|
592
|
-
|
|
593
|
-
class Completing {
|
|
594
|
-
options;
|
|
595
|
-
positionals;
|
|
596
|
-
candidates;
|
|
597
|
-
constructor(options, positionals = [], candidates = {}) {
|
|
598
|
-
this.options = options;
|
|
599
|
-
this.positionals = positionals;
|
|
600
|
-
this.candidates = candidates;
|
|
601
|
-
}
|
|
602
|
-
}
|
|
603
|
-
function applyOutput(color, plain, env = process10.env) {
|
|
604
|
-
const when = plain === true ? "never" : color ?? "auto";
|
|
605
|
-
if (when === "auto")
|
|
606
|
-
return;
|
|
607
|
-
if (when !== "always" && when !== "never")
|
|
608
|
-
badUsage(`--color takes auto, always or never, not ${when}`);
|
|
609
|
-
if (when === "always") {
|
|
610
|
-
env.FORCE_COLOR = "1";
|
|
611
|
-
delete env.NO_COLOR;
|
|
612
|
-
} else {
|
|
613
|
-
env.NO_COLOR = "1";
|
|
614
|
-
delete env.FORCE_COLOR;
|
|
615
|
-
}
|
|
616
|
-
}
|
|
617
|
-
function parse(args, usage, options, settings = {}) {
|
|
618
|
-
const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
|
|
619
|
-
const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
|
|
620
|
-
const listing = listed(all, settings.allowNegative === true);
|
|
621
|
-
if (completion.active)
|
|
622
|
-
throw new Completing(listing, settings.positionals, settings.candidates);
|
|
623
|
-
const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
|
|
624
|
-
let parsed;
|
|
625
|
-
try {
|
|
626
|
-
parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
|
|
627
|
-
} catch (error) {
|
|
628
|
-
const message = parseError(error);
|
|
629
|
-
throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
|
|
630
|
-
}
|
|
631
|
-
const values = parsed.values;
|
|
632
|
-
applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
|
|
633
|
-
if (values.help === true) {
|
|
634
|
-
console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, { ...settings, bin: heading.bin }));
|
|
635
|
-
throw new HelpShown;
|
|
636
|
-
}
|
|
637
|
-
checkChoices(parsed.values, all);
|
|
638
|
-
checkConflicts(parsed.values, all);
|
|
639
|
-
if (settings.positionals !== undefined)
|
|
640
|
-
checkPositionals(parsed.positionals, settings.positionals);
|
|
641
|
-
return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
|
|
642
|
-
}
|
|
643
|
-
function splitRest(args, passes) {
|
|
644
|
-
const separator = passes ? args.indexOf("--") : -1;
|
|
645
|
-
return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
|
|
646
|
-
}
|
|
647
|
-
function splitTrailing(args, options, count) {
|
|
648
|
-
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
649
|
-
let seen = 0;
|
|
650
|
-
if (count === 0)
|
|
651
|
-
return { own: args, rest: undefined };
|
|
652
|
-
for (let at = 0;at < args.length; at++) {
|
|
653
|
-
const word = args[at];
|
|
654
|
-
if (word === "--")
|
|
655
|
-
break;
|
|
656
|
-
if (word.startsWith("-")) {
|
|
657
|
-
if (takesValue(word))
|
|
658
|
-
at++;
|
|
659
|
-
continue;
|
|
660
|
-
}
|
|
661
|
-
seen++;
|
|
662
|
-
if (seen === count)
|
|
663
|
-
return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
|
|
664
|
-
}
|
|
665
|
-
return { own: args, rest: undefined };
|
|
666
|
-
}
|
|
667
|
-
function listed(options, allowNegative) {
|
|
668
|
-
if (!allowNegative)
|
|
669
|
-
return options;
|
|
670
|
-
return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
|
|
671
|
-
if (option.type !== "boolean" || option.negative === undefined)
|
|
672
|
-
return [[name, option]];
|
|
673
|
-
return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
|
|
674
|
-
}));
|
|
675
|
-
}
|
|
676
|
-
function withAliases(args, options) {
|
|
677
|
-
const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
|
|
678
|
-
if (named.size === 0)
|
|
679
|
-
return args;
|
|
680
|
-
const separator = args.indexOf("--");
|
|
681
|
-
const own = separator === -1 ? args : args.slice(0, separator);
|
|
682
|
-
return [...own.map((arg) => {
|
|
683
|
-
const at = arg.indexOf("=");
|
|
684
|
-
const current = named.get(at === -1 ? arg : arg.slice(0, at));
|
|
685
|
-
return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
|
|
686
|
-
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
687
|
-
}
|
|
688
|
-
function withBare(args, options) {
|
|
689
|
-
const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
|
|
690
|
-
if (bare.size === 0)
|
|
691
|
-
return args;
|
|
692
|
-
const separator = args.indexOf("--");
|
|
693
|
-
const own = separator === -1 ? args : args.slice(0, separator);
|
|
694
|
-
return [...own.flatMap((arg, index) => {
|
|
695
|
-
const optional = bare.get(arg);
|
|
696
|
-
const next = own[index + 1];
|
|
697
|
-
const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
|
|
698
|
-
return optional === undefined || value ? [arg] : [arg, optional.bare];
|
|
699
|
-
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
700
|
-
}
|
|
701
|
-
function checkConflicts(values, options) {
|
|
702
|
-
const given = (name) => values[name] !== undefined && values[name] !== false;
|
|
703
|
-
for (const [name, { conflicts = [] }] of Object.entries(options)) {
|
|
704
|
-
const other = given(name) ? conflicts.find(given) : undefined;
|
|
705
|
-
if (other !== undefined)
|
|
706
|
-
badUsage(`--${name} cannot be used with --${other}`);
|
|
707
|
-
}
|
|
708
|
-
}
|
|
709
|
-
function checkChoices(values, options) {
|
|
710
|
-
for (const [name, option] of Object.entries(options)) {
|
|
711
|
-
if (option.choices === undefined)
|
|
712
|
-
continue;
|
|
713
|
-
const given = values[name];
|
|
714
|
-
for (const value of Array.isArray(given) ? given : [given]) {
|
|
715
|
-
if (typeof value === "string")
|
|
716
|
-
oneOf(value, name, option.choices);
|
|
717
|
-
}
|
|
718
|
-
}
|
|
719
|
-
}
|
|
720
|
-
function oneOf(value, name, choices) {
|
|
721
|
-
if (!choices.includes(value))
|
|
722
|
-
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
|
|
723
|
-
return value;
|
|
724
|
-
}
|
|
725
|
-
function checkPositionals(given, names) {
|
|
726
|
-
const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
|
|
727
|
-
const required = names.filter((name) => !name.startsWith("[")).length;
|
|
728
|
-
if (given.length < required)
|
|
729
|
-
badUsage(`missing ${names[given.length]}`);
|
|
730
|
-
if (!variadic && given.length > names.length)
|
|
731
|
-
badUsage(`unexpected argument ${given[names.length]}`);
|
|
732
|
-
}
|
|
733
|
-
function joinDashValues(args, options) {
|
|
734
|
-
const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
|
|
735
|
-
const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
|
|
736
|
-
const joined = [];
|
|
737
|
-
for (let i = 0;i < args.length; i++) {
|
|
738
|
-
const arg = args[i] ?? "";
|
|
739
|
-
if (arg === "--")
|
|
740
|
-
return [...joined, ...args.slice(i)];
|
|
741
|
-
const name = longOf.get(arg);
|
|
742
|
-
const next = args[i + 1];
|
|
743
|
-
if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
|
|
744
|
-
joined.push(`--${name}=${next}`);
|
|
745
|
-
i++;
|
|
746
|
-
} else {
|
|
747
|
-
joined.push(arg);
|
|
748
|
-
}
|
|
749
|
-
}
|
|
750
|
-
return joined;
|
|
751
|
-
}
|
|
752
|
-
function parseError(error) {
|
|
753
|
-
const message = upTo(error instanceof Error ? error.message : String(error), ". ");
|
|
754
|
-
return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
|
|
755
|
-
}
|
|
756
|
-
function nearestOption(message, options, allowNegative) {
|
|
757
|
-
const typed = UNKNOWN_OPTION.exec(message)?.[1];
|
|
758
|
-
if (typed === undefined)
|
|
759
|
-
return;
|
|
760
|
-
const word = typed.replace(DASHES, "");
|
|
761
|
-
if (word.length < 2 && !typed.startsWith("--"))
|
|
762
|
-
return;
|
|
763
|
-
const known = Object.entries(options).flatMap(([name, option]) => [
|
|
764
|
-
...option.short === undefined ? [] : [`-${option.short}`],
|
|
765
|
-
`--${name}`,
|
|
766
|
-
...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
|
|
767
|
-
]);
|
|
768
|
-
const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
|
|
769
|
-
return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
|
|
770
|
-
}
|
|
771
|
-
var DASHES, EXIT, Exit, UsageError, HelpShown, completion, heading, OUTPUT_OPTIONS, UNKNOWN_OPTION;
|
|
772
|
-
var init_args = __esm(() => {
|
|
773
|
-
init_format();
|
|
774
|
-
init_help();
|
|
775
|
-
init_text();
|
|
776
|
-
init_help();
|
|
777
|
-
init_input();
|
|
778
|
-
DASHES = /^-+/;
|
|
779
|
-
EXIT = Symbol.for("@kaynooo/cli-kit/Exit");
|
|
780
|
-
Exit = class Exit extends Error {
|
|
781
|
-
code;
|
|
782
|
-
hint;
|
|
783
|
-
[EXIT] = true;
|
|
784
|
-
constructor(message, code, hint) {
|
|
785
|
-
super(message);
|
|
786
|
-
this.code = code;
|
|
787
|
-
this.hint = hint;
|
|
788
|
-
}
|
|
789
|
-
static [Symbol.hasInstance](value) {
|
|
790
|
-
if (this !== Exit)
|
|
791
|
-
return Function.prototype[Symbol.hasInstance].call(this, value);
|
|
792
|
-
return typeof value === "object" && value !== null && value[EXIT] === true;
|
|
793
|
-
}
|
|
794
|
-
};
|
|
795
|
-
UsageError = class UsageError extends Exit {
|
|
796
|
-
constructor(message, hint) {
|
|
797
|
-
super(message, 2, hint);
|
|
798
|
-
}
|
|
799
|
-
};
|
|
800
|
-
HelpShown = class HelpShown extends Exit {
|
|
801
|
-
constructor() {
|
|
802
|
-
super("help shown", 0);
|
|
803
|
-
}
|
|
804
|
-
};
|
|
805
|
-
completion = { active: false };
|
|
806
|
-
heading = { bin: undefined };
|
|
807
|
-
OUTPUT_OPTIONS = {
|
|
808
|
-
color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
|
|
809
|
-
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
810
|
-
};
|
|
811
|
-
UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
|
|
812
|
-
});
|
|
813
|
-
|
|
814
|
-
// ../kit/src/folders.ts
|
|
815
|
-
var SKIPPED_FOLDERS;
|
|
816
|
-
var init_folders = __esm(() => {
|
|
817
|
-
init_user_config();
|
|
818
|
-
SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
|
|
819
|
-
});
|
|
820
|
-
|
|
821
|
-
// src/view.ts
|
|
822
|
-
import process18 from "process";
|
|
823
|
-
|
|
824
|
-
// ../kit/src/index.ts
|
|
825
|
-
init_args();
|
|
826
|
-
|
|
827
|
-
// ../kit/src/argv.ts
|
|
828
|
-
import { readFileSync as readFileSync2, realpathSync } from "fs";
|
|
829
|
-
import { resolve as resolve3 } from "path";
|
|
830
|
-
import process11 from "process";
|
|
831
|
-
function commandLine() {
|
|
832
|
-
try {
|
|
833
|
-
return readFileSync2("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
|
|
834
|
-
} catch {
|
|
835
|
-
return;
|
|
836
|
-
}
|
|
837
|
-
}
|
|
838
|
-
function realPath(word) {
|
|
839
|
-
try {
|
|
840
|
-
return realpathSync(resolve3(word));
|
|
841
|
-
} catch {
|
|
842
|
-
return;
|
|
843
|
-
}
|
|
844
|
-
}
|
|
845
|
-
function scriptArgs(argv = process11.argv.slice(2), cmdline = commandLine(), script = process11.argv[1]) {
|
|
846
|
-
const target = script === undefined ? undefined : realPath(script) ?? script;
|
|
847
|
-
const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
|
|
848
|
-
const after = at === -1 ? [] : cmdline.slice(at + 1);
|
|
849
|
-
return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
|
|
850
|
-
}
|
|
851
|
-
// ../kit/src/chart.ts
|
|
852
|
-
init_format();
|
|
853
|
-
init_mode();
|
|
854
|
-
init_style();
|
|
855
|
-
init_theme();
|
|
856
|
-
// ../kit/src/ci.ts
|
|
857
|
-
init_args();
|
|
858
|
-
init_format();
|
|
859
|
-
|
|
860
|
-
// ../kit/src/progress.ts
|
|
861
|
-
init_format();
|
|
862
|
-
|
|
863
|
-
// ../kit/src/process.ts
|
|
864
|
-
var GROUP_SIGNALS = new Set(["SIGINT", "SIGHUP"]);
|
|
865
|
-
|
|
866
|
-
// ../kit/src/progress.ts
|
|
867
|
-
init_style();
|
|
868
|
-
init_theme();
|
|
869
|
-
var ESC = String.fromCharCode(27);
|
|
870
|
-
var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
|
|
871
|
-
var RESET_STYLE = `${ESC}[0m`;
|
|
872
|
-
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
873
|
-
|
|
874
|
-
// ../kit/src/ci.ts
|
|
875
|
-
init_style();
|
|
876
|
-
|
|
877
|
-
// ../kit/src/tool.ts
|
|
878
|
-
init_format();
|
|
879
|
-
// ../kit/src/cli.ts
|
|
880
|
-
init_args();
|
|
881
|
-
import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
|
|
882
|
-
import { dirname as dirname3, join as join5 } from "path";
|
|
883
|
-
import process15 from "process";
|
|
884
|
-
|
|
885
|
-
// ../kit/src/askpass.ts
|
|
886
|
-
import process12 from "process";
|
|
887
|
-
var SOCKET_VARIABLE = "KAYNOOO_ASKPASS_SOCKET";
|
|
888
|
-
async function askpassClient(argv) {
|
|
889
|
-
const socketPath = process12.env[SOCKET_VARIABLE];
|
|
890
|
-
if (socketPath === undefined)
|
|
891
|
-
return;
|
|
892
|
-
const request = { prompt: argv[0] ?? "", ...process12.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
|
|
893
|
-
const { promise, resolve } = Promise.withResolvers();
|
|
894
|
-
let received = "";
|
|
895
|
-
try {
|
|
896
|
-
await Bun.connect({
|
|
897
|
-
unix: socketPath,
|
|
898
|
-
socket: {
|
|
899
|
-
open: (socket) => void socket.write(`${JSON.stringify(request)}
|
|
900
|
-
`),
|
|
901
|
-
data: (_, chunk) => {
|
|
902
|
-
received += chunk.toString();
|
|
903
|
-
},
|
|
904
|
-
close: () => resolve(received),
|
|
905
|
-
error: () => resolve("")
|
|
906
|
-
}
|
|
907
|
-
});
|
|
908
|
-
} catch {
|
|
909
|
-
return 1;
|
|
910
|
-
}
|
|
911
|
-
const reply = await promise;
|
|
912
|
-
if (reply === "")
|
|
913
|
-
return 1;
|
|
914
|
-
const { answer } = JSON.parse(reply);
|
|
915
|
-
if (request.notice === true)
|
|
916
|
-
return 0;
|
|
917
|
-
if (answer === undefined)
|
|
918
|
-
return 1;
|
|
919
|
-
process12.stdout.write(`${answer}
|
|
920
|
-
`);
|
|
921
|
-
return 0;
|
|
922
|
-
}
|
|
923
|
-
|
|
924
|
-
// ../kit/src/completions.ts
|
|
925
|
-
var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
|
|
926
|
-
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'
|
|
3
|
+
var __esm=(fn,res,err)=>()=>{if(fn)try{res=fn(fn=0)}catch(e){err=[e]}if(err)throw err[0];return res};import process from"process";function isSet(value){return value!==void 0&&value!==""&&value!=="0"&&value.toLowerCase()!=="false"}function outputMode(stream=process.stdout,env=process.env){let chosen=env.KIT_MODE;if(chosen!==void 0&&MODES.has(chosen))return chosen;if(AGENT_VARIABLES.some((name)=>isSet(env[name])))return"agent";if(stream.isTTY===!0)return"terminal";return isSet(env.CI)?"ci":"pipe"}function isHumanTerminal(stream=process.stdout,env=process.env){return outputMode(stream,env)==="terminal"}function canPage(stream=process.stdout,env=process.env){return isHumanTerminal(stream,env)}var MODES,AGENT_VARIABLES;var init_mode=__esm(()=>{MODES=new Set(["terminal","ci","agent","pipe"]),AGENT_VARIABLES=["CLAUDECODE","AI_AGENT","CODEX_SANDBOX","CODEX_CI","CURSOR_AGENT","OPENCODE","GEMINI_CLI","ANTIGRAVITY_AGENT"]});function b(r){let e=r.startsWith("#")?r.slice(1):r;if(!G.test(e))return[0,0,0];if(e.length===3||e.length===4)return[Number.parseInt(e[0]+e[0],16),Number.parseInt(e[1]+e[1],16),Number.parseInt(e[2]+e[2],16)];if(e.length!==6&&e.length!==8)throw Error(`Invalid hex color length: ${e.length}`);return[Number.parseInt(e.slice(0,2),16),Number.parseInt(e.slice(2,4),16),Number.parseInt(e.slice(4,6),16)]}function C(r,e=globalThis.process?.env??{}){if(e.FORCE_COLOR!==void 0)return h.has(e.FORCE_COLOR);if(e.NO_COLOR!==void 0||e.NODE_DISABLE_COLORS!==void 0||e.TERM==="dumb")return!1;return r?.isTTY===!0}function f(r,e=[]){let l="",n="";for(let t=0,i=e.length;t<i;t++)l+=`\x1B[${e[t][0]}m`,n=`\x1B[${e[t][1]}m${n}`;let c=(t)=>C(r.stream??globalThis.process?.stdout,r.env)?l+t+n:t,g=new Map;return new Proxy(c,{get(t,i){let a=B[i];if(Array.isArray(a)){let s=g.get(i);if(s===void 0)s=f(r,[...e,a]),g.set(i,s);return s}if(typeof a==="function")return(...s)=>{let y=`${i}:${s.join(",")}`,u=g.get(y);if(u===void 0){if(g.size>=64)g.clear();u=f(r,[...e,a(...s)]),g.set(y,u)}return u};throw Error(`Unknown style: ${String(i)}`)}})}function Fe(r={}){return f(r)}var G,B,h,o;var init_chunk_x450vn3m=__esm(()=>{G=/^[a-f0-9]+$/i;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")=>{let[l,n,c]=b(r);return[`${e==="fg"?38:48};2;${l};${n};${c}`,e==="fg"?39:49]},ansi256:(r,e="fg")=>[`${e==="fg"?38:48};5;${r}`,e==="fg"?39:49]},h=new Set(["","1","2","3","true"]);o=Fe()});var init_colors=__esm(()=>{init_chunk_x450vn3m()});import{existsSync}from"fs";import{dirname,join,resolve}from"path";import process2 from"process";function findUp(names,from=process2.cwd(),stop=()=>!1){let wanted=typeof names==="string"?[names]:names;for(let dir=resolve(from);;dir=dirname(dir)){let found=wanted.map((name)=>join(dir,name)).find((path)=>existsSync(path));if(found!==void 0)return found;if(stop(dir)||dirname(dir)===dir)return}}var init_config=__esm(()=>{init_args()});import{existsSync as existsSync2,mkdirSync,readFileSync,statSync,writeFileSync}from"fs";import{homedir}from"os";import{dirname as dirname2,isAbsolute,join as join2}from"path";import process3 from"process";function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function xdgFolder(value,fallback){return value!==void 0&&isAbsolute(value)?value:fallback}function configBase(where={}){let xdg=where.xdg??(where.home===void 0?process3.env.XDG_CONFIG_HOME:void 0);return xdgFolder(xdg,join2(where.home??homedir(),".config"))}function userConfigPath(bin,where={}){return join2(configBase(where),"kaynooo-cli",`${bin}.json`)}function mainConfigPath(where={}){let jsonc=join2(configBase(where),"kaynooo-cli","config.jsonc");return existsSync2(jsonc)?jsonc:userConfigPath("config",where)}function readCachedObject(path){let stat=statSync(path,{throwIfNoEntry:!1});if(stat===void 0||!stat.isFile())return FILE_CACHE.delete(path),{};let cached=FILE_CACHE.get(path);if(cached!==void 0&&cached.mtimeMs===stat.mtimeMs&&cached.size===stat.size)return cached.data;try{let parsed=Bun.JSONC.parse(readFileSync(path,"utf8")),data=isRecord(parsed)?parsed:{};return FILE_CACHE.set(path,{mtimeMs:stat.mtimeMs,size:stat.size,data}),data}catch{return{}}}function readMainConfig(where={}){return readCachedObject(mainConfigPath(where))}var FILE_CACHE;var init_user_config=__esm(()=>{FILE_CACHE=new Map});import{existsSync as existsSync3,readFileSync as readFileSync2,statSync as statSync2}from"fs";import{homedir as homedir2}from"os";import{join as join3,resolve as resolve2}from"path";import process4 from"process";function toLinear(channel){let value=channel/255;return value<=0.04045?value/12.92:((value+0.055)/1.055)**2.4}function toOklab(hex){let[r,g,b]=[1,3,5].map((at)=>toLinear(Number.parseInt(hex.slice(at,at+2),16))),l=Math.cbrt(0.4122214708*r+0.5363325363*g+0.0514459929*b),m=Math.cbrt(0.2119034982*r+0.6806995451*g+0.1073969566*b),s=Math.cbrt(0.0883024619*r+0.2817188376*g+0.6299787005*b);return[0.2104542553*l+0.793617785*m-0.0040720468*s,1.9779984951*l-2.428592205*m+0.4505937099*s,0.0259040371*l+0.7827717662*m-0.808675766*s]}function fromOklab([lightness,a,b]){let l=(lightness+0.3963377774*a+0.2158037573*b)**3,m=(lightness-0.1055613458*a-0.0638541728*b)**3,s=(lightness-0.0894841775*a-1.291485548*b)**3;return`#${[4.0767416621*l-3.3077115913*m+0.2309699292*s,-1.2684380046*l+2.6097574011*m-0.3413193965*s,-0.0041960863*l-0.7034186147*m+1.707614701*s].map((channel)=>fromLinear(channel).toString(16).padStart(2,"0")).join("")}`}function gradientAt(theme,ratio){if(theme.gradient===void 0)return;let key=theme.gradient.join(),ends=ENDS.get(key);if(ends===void 0)ends=[toOklab(theme.gradient[0]),toOklab(theme.gradient[1])],ENDS.set(key,ends);let at=Math.min(1,Math.max(0,ratio)),[from,to]=ends;return fromOklab(from.map((start,index)=>start+(to[index]-start)*at))}function isColorSpec(spec){if(typeof spec==="number")return Number.isInteger(spec)&&spec>=0&&spec<=255;return typeof spec==="string"&&spec.trim()!==""&&spec.trim().split(SPACES).every((token)=>STYLES.has(token)||HEX.test(token))}function cubeLevel(channel){return CUBE.reduce((best,value,level)=>Math.abs(value-channel)<Math.abs(CUBE[best]-channel)?level:best,0)}function nearest256(hex){let rgb=[1,3,5].map((at)=>Number.parseInt(hex.slice(at,at+2),16)),levels=rgb.map(cubeLevel),cube=levels.map((level)=>CUBE[level]),grey=Math.min(23,Math.max(0,Math.round((rgb.reduce((sum,channel)=>sum+channel,0)/3-8)/10))),greyValue=8+grey*10,distance=(colour)=>colour.reduce((sum,channel,at)=>sum+(channel-rgb[at])**2,0);return distance([greyValue,greyValue,greyValue])<distance(cube)?232+grey:16+36*levels[0]+6*levels[1]+levels[2]}function hasTrueColor(env){return env.COLORTERM==="truecolor"||env.COLORTERM==="24bit"}function tinted(colors,spec,env=process4.env){if(typeof spec==="number")return colors.ansi256(spec);return spec.trim().split(SPACES).reduce((chain,token)=>{if(HEX.test(token))return hasTrueColor(env)?chain.hex(token):chain.ansi256(nearest256(token));return chain[token]??chain},colors)}function isRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function readThemeFile(path,warn){try{let stat=statSync2(path,{throwIfNoEntry:!1});if(stat===void 0)return;if(!stat.isFile()||stat.size>MAX_FILE_BYTES){warn(`${path} is not a regular file under ${MAX_FILE_BYTES/1024} KiB, theme ignored`);return}let parsed=Bun.JSONC.parse(readFileSync2(path,"utf8"));if(isRecord2(parsed))return parsed;warn(`${path} is not a JSON object, theme ignored`)}catch(error){warn(`${path} does not parse (${error instanceof Error?error.message:String(error)}), theme ignored`)}return}function applyPreset(theme,name,warn,where){if(name===void 0)return;if(typeof name!=="string"||!Object.hasOwn(PRESETS,name)){warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);return}let preset=PRESETS[name];if(Object.assign(theme.colors,preset.colors),Object.assign(theme.glyphs,preset.glyphs),preset.accents!==void 0)theme.accents=[...preset.accents];if(Object.hasOwn(preset,"gradient"))theme.gradient=preset.gradient;return name}function applyFile(theme,file,where,warn){if(isRecord2(file.colors))for(let[key,value]of Object.entries(file.colors))if(!Object.hasOwn(DEFAULT.colors,key))warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);else if(!isColorSpec(value))warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);else theme.colors[key]=value;if(isRecord2(file.glyphs))for(let[key,value]of Object.entries(file.glyphs))if(!Object.hasOwn(DEFAULT.glyphs,key))warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);else if(typeof value!=="string"||CONTROL.test(value)||Bun.stringWidth(value)!==1)warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);else theme.glyphs[key]=value;if(Array.isArray(file.accents)&&file.accents.length>0&&file.accents.every(isColorSpec))theme.accents=[...file.accents];else if(file.accents!==void 0)warn(`${where}: accents must be a non-empty list of colours`);if(file.gradient===null)theme.gradient=void 0;else if(Array.isArray(file.gradient)&&file.gradient.length===2&&file.gradient.every((end)=>typeof end==="string"&&HEX.test(end)))theme.gradient=[file.gradient[0],file.gradient[1]];else if(file.gradient!==void 0)warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);if(isRecord2(file.bins))for(let[bin,value]of Object.entries(file.bins))if(isColorSpec(value))theme.bins[bin]=value;else warn(`${where}: bin ${bin} has no valid colour`)}function endsWalk(home){return(dir)=>dir===resolve2(home)||existsSync3(join3(dir,".git"))}function warnOnce(message){if(warned.has(message))return;warned.add(message),console.error(`warning: theme ${message}`)}function isPath(chosen){return chosen.includes("/")||chosen.endsWith(".json")}function loadTheme({env=process4.env,from=process4.cwd(),home=homedir2(),warn=warnOnce}={}){let theme={colors:{...DEFAULT.colors},glyphs:{...DEFAULT.glyphs},accents:[...DEFAULT.accents],bins:Object.create(null),gradient:DEFAULT.gradient},sources=[],chosen=env.KIT_THEME??"",wanted=chosen===""?[userConfigPath("theme",{home,xdg:env.XDG_CONFIG_HOME}),findUp(join3(".kaynooo","theme.json"),from,endsWalk(home))]:[];if(isPath(chosen))wanted.push(resolve2(from,chosen));let files=[];if(chosen===""){let mainTheme=readMainConfig({home,xdg:env.XDG_CONFIG_HOME}).theme;if(isRecord2(mainTheme))files.push({path:`${mainConfigPath({home,xdg:env.XDG_CONFIG_HOME})}#theme`,file:mainTheme})}for(let path of wanted){let file=path===void 0?void 0:readThemeFile(path,warn);if(path!==void 0&&file!==void 0)files.push({path,file})}let preset="default";if(chosen!==""&&!isPath(chosen))preset=applyPreset(theme,chosen,warn,"KIT_THEME")??preset;else{let named=files.findLast(({file})=>file.preset!==void 0);if(named!==void 0)preset=applyPreset(theme,named.file.preset,warn,named.path)??preset}for(let{path,file}of files)applyFile(theme,file,path,warn),sources.push(path);return{theme,sources,preset}}function activeTheme(){let key=`${process4.cwd()}\x00${process4.env.KIT_THEME??""}\x00${process4.env.XDG_CONFIG_HOME??""}`;if(current===void 0||key!==currentKey)current=loadTheme(),currentKey=key;return current}var fromLinear=(value)=>Math.round(255*Math.min(1,Math.max(0,value<=0.0031308?value*12.92:1.055*value**0.4166666666666667-0.055))),ENDS,DEFAULT,BRIGHT,LIGHT,MONO,ASCII,PRESETS,STYLES,HEX,CONTROL,MAX_FILE_BYTES=65536,SPACES,CUBE,warned,current,currentKey="";var init_theme=__esm(()=>{init_config();init_user_config();ENDS=new Map;DEFAULT={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"},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"},accents:["cyan","magenta","green","blue","yellow","redBright"],bins:{},gradient:["#c084fc","#67e8f9"]},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"},LIGHT={accent:"#0369a1",id:"#b45309",path:"#1d4ed8",label:"#52525b",value:"bold",ok:"#15803d",warn:"#b45309",problem:"#b91c1c",note:"#52525b",plan:"#7e22ce",passed:"#15803d",failed:"#b91c1c",running:"#0369a1",queued:"#b45309",skipped:"#52525b"},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"},ASCII={ok:"+",warn:"!",problem:"x",note:">",plan:"?",passed:"+",failed:"x",running:"*",queued:"o",skipped:"-",bar:"#",rule:"-",corner:"+",open:"*",leaf:"-",guide:"|"},PRESETS={default:{},"high-contrast":{colors:BRIGHT,accents:["cyanBright","magentaBright","greenBright","blueBright","yellowBright","redBright"],gradient:["#d8b4fe","#a5f3fc"]},light:{colors:LIGHT,accents:["#0369a1","#7e22ce","#15803d","#1d4ed8","#b45309","#b91c1c"],gradient:["#7c3aed","#0284c7"]},mono:{colors:MONO,accents:["bold"],gradient:void 0},ascii:{glyphs:ASCII}},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"]),HEX=/^#[0-9a-f]{6}$/i,CONTROL=/\p{Cc}/u,SPACES=/\s+/;CUBE=[0,95,135,175,215,255];warned=new Set});import process5 from"process";function takesControlCodes(stream,env=process5.env){return stream.isTTY===!0&&(env.NO_COLOR===void 0||env.NO_COLOR==="")&&env.NODE_DISABLE_COLORS===void 0&&env.TERM!=="dumb"&&outputMode(stream,env)==="terminal"}function paint(stream,env=process5.env){let effective=env.NO_COLOR===""?{...env,NO_COLOR:void 0}:env;return Fe({stream:{isTTY:takesControlCodes(stream,env)},env:effective})}function role(name,stream,env=process5.env){let colors=paint(stream,env);return takesControlCodes(stream,env)?tinted(colors,activeTheme().theme.colors[name],env):colors}function link(text,url,stream,env=process5.env){if(takesControlCodes(stream,env))return`\x1B]8;;${url}\x1B\\${text}\x1B]8;;\x1B\\`;return text===url?text:`${text} (${url})`}var STATUS_WORDS,STATUS_OF;var init_style=__esm(()=>{init_colors();init_mode();init_theme();STATUS_WORDS={passed:["passed","success","succeeded","ok"],failed:["failed","failure","error","errored"],running:["running","in_progress","started","holding"],queued:["queued","waiting","pending","created","blocked","scheduled"],skipped:["skipped","cancelled","canceled","manual"]},STATUS_OF=new Map(Object.entries(STATUS_WORDS).flatMap(([status,words])=>words.map((word)=>[word,status])))});function stripAnsi(text){return text.replace(ANSI,"")}function stripControls(text){return text.replace(CONTROLS,"")}function escapeControls(text){return text.replace(CONTROLS,(char)=>{let code=char.charCodeAt(0);if(code===127)return"^?";return code<128?`^${String.fromCharCode(code+64)}`:`M-^${String.fromCharCode(code-64)}`})}function distance(a,b){let left=[...a],right=[...b],before=[],previous=Array.from({length:right.length+1},(_,index)=>index);for(let[i,x]of left.entries()){let current=[i+1];for(let[j,y]of right.entries()){let cost=Math.min((previous[j+1]??0)+1,(current[j]??0)+1,(previous[j]??0)+(x===y?0:1));if(i>0&&j>0&&x===right[j-1]&&left[i-1]===y)cost=Math.min(cost,(before[j-1]??0)+1);current.push(cost)}before=previous,previous=current}return previous[right.length]??0}function closest(name,names){let started=names.find((known)=>known.startsWith(name));if(started!==void 0)return started;let[best]=names.map((known)=>({known,far:distance(name,known)})).sort((a,b)=>a.far-b.far);return best!==void 0&&best.far<=(name.length<4?1:2)?best.known:void 0}var ANSI,CONTROLS,ESC,ESCAPE_CODE,RESET_STYLE,CLOSE_LINK;var init_text=__esm(()=>{ANSI=/\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;CONTROLS=/[\x00-\x08\x0B-\x1F\x7F-\x9F]/g;ESC=String.fromCharCode(27),ESCAPE_CODE=new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`,"y"),RESET_STYLE=`${ESC}[0m`,CLOSE_LINK=`${ESC}]8;;${ESC}\\`});import process6 from"process";function formatSeconds(total){let rest=Math.max(0,Math.round(total)),amounts=UNITS.map(([unit,size])=>{let amount=Math.floor(rest/size);return rest-=amount*size,`${amount}${unit}`}),first=amounts.findIndex((amount)=>!amount.startsWith("0"));if(first===-1)return"0s";let next=amounts[first+1];return next===void 0||next.startsWith("0")?amounts[first]??"0s":`${amounts[first]} ${next}`}function formatDuration(ms){return ms<60000?`${(Math.max(0,ms)/1000).toFixed(1)}s`:formatSeconds(ms/1000)}function upTo(text,separator){let end=text.indexOf(separator);return end===-1?text:text.slice(0,end)}function textWidth(text){return Bun.stringWidth(text)}function jsonText(value,replacer,{stream=process6.stdout,env=process6.env}={}){return JSON.stringify(value,replacer,outputMode(stream,env)==="agent"?void 0:2)}function printJson(value){console.log(jsonText(value))}var UNITS;var init_format=__esm(()=>{init_mode();init_style();init_text();init_theme();UNITS=[["d",86400],["h",3600],["m",60],["s",1]]});import process7 from"process";function usageLine(usage,colors=paint(process7.stdout),{summary:withSummary=!0}={}){let lines=usage.replace(USAGE_PREFIX,"").split(`
|
|
4
|
+
`),blank=lines.indexOf(""),synopses=blank===-1?lines:lines.slice(0,blank),details=blank===-1?[]:lines.slice(blank+1),colon=synopses[0].indexOf(": "),inline=synopses[0].slice(colon+2),summary=colon===-1?details.shift():`${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;if(colon!==-1)synopses[0]=synopses[0].slice(0,colon);let head=`${colors.bold("Usage:")} ${synopses.map((line)=>line.replaceAll(OPTIONAL,(part)=>colors.dim(part))).join(`
|
|
5
|
+
`)}`,lead=summary===void 0||!withSummary?[]:["",colors.bold(prose(summary,colors))],rest=details.length===0?[]:["",...details.map((line)=>prose(line,colors))];return[head,...lead,...rest].join(`
|
|
6
|
+
`)}function prose(line,colors){if(colors.cyan("x")==="x")return line;return line.replaceAll(PROSE_MARKS,(match,code,flag)=>code===void 0?colors.cyan(flag??match):colors.bold(code))}function helpText(usage,options,colors=paint(process7.stdout),{examples=[],exits=[],bin,columns}={}){let{summary}=description(usage);return[...bin===void 0?[usageLine(usage,colors)]:[`${colors.bold(bin.name)} ${colors.dim(bin.version())}${summary===""?"":` ${summary}`}`,"",usageLine(usage,colors,{summary:!1})],"",colors.bold("Options:"),...optionRows(options,colors,columns),...exitRows(exits,colors),...exampleRows(examples,colors)].join(`
|
|
7
|
+
`)}function exitRows(exits,colors=paint(process7.stdout)){if(exits.length===0)return[];return["",`${colors.bold("Exit codes:")} ${exits.map(([code,meaning])=>`${colors.cyan(String(code))} ${meaning}`).join(", ")}`]}function wantsHelpJson(env=process7.env,argv){if(env.KIT_HELP==="json")return!0;if(argv===void 0)return!1;let end=argv.indexOf("--"),own=end===-1?argv:argv.slice(0,end);if(own.includes("--help=json"))return!0;return(own.includes("--help")||own.includes("-h")||own[0]==="help")&&own.includes("--json")}function description(usage,{examples=[],replaces,exits}={},options){let lines=usage.replace(USAGE_PREFIX,"").split(`
|
|
8
|
+
`),first=lines[0],colon=first.indexOf(": "),prose=lines[lines.indexOf("")+1]??"",fallback=lines.includes("")?`${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP,""):"";return{synopsis:colon===-1?first:first.slice(0,colon),summary:colon===-1?fallback:first.slice(colon+2),...replaces===void 0?{}:{replaces},examples:examples.map((example)=>typeof example==="string"?{line:example}:{line:example[0],note:example[1]}),...exits===void 0?{}:{exits:exits.map(([code,meaning])=>({code,meaning}))},...options===void 0?{}:{options:Object.entries(options).map(([name,{short,description}])=>({name,...short===void 0?{}:{short},...description===void 0?{}:{description}}))}}}function exampleRows(examples,colors=paint(process7.stdout)){if(examples.length===0)return[];let shown=outputMode()==="agent"?examples.slice(0,MAX_AGENT_EXAMPLES):examples;return["",colors.bold("Examples:"),...shown.map((example)=>typeof example==="string"?` ${example}`:` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)]}function wrapText(text,limit){if(text.length<=limit)return[text];let lines=[],current="";for(let word of text.split(" "))if(current==="")current=word;else if(current.length+1+word.length<=limit)current=`${current} ${word}`;else lines.push(current),current=word;if(current!=="")lines.push(current);return lines}function optionRows(options,colors=paint(process7.stdout),columns){let rows=Object.entries(options).map(([name,option])=>{let short=option.short===void 0?" ":`${colors.cyan(`-${option.short}`)}, `,choices=option.choices?.join("|"),inline=choices!==void 0&&choices.length<=MAX_INLINE_CHOICES,named=inline?`<${choices}>`:"<value>",placeholder=option.optional===void 0?named:`[${named}]`,value=option.type==="string"?` ${colors.dim(placeholder)}`:"",described=choices===void 0||inline?option.description??"":[option.description,`one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");return{flag:`${short}${colors.cyan(`--${name}`)}${value}`,width:`-x, --${name}`.length+(option.type==="string"?placeholder.length+1:0),description:described}}),width=Math.max(0,...rows.map((row)=>row.width)),indent=2+width+2,room=columns!==void 0&&columns-indent>=20?columns-indent:void 0;return rows.flatMap((row)=>{if(row.description==="")return[` ${row.flag}`];let wrapped=room===void 0?[row.description]:wrapText(row.description,room),[first="",...rest]=wrapped;return[` ${row.flag}${" ".repeat(width-row.width)} ${colors.dim(first)}`,...rest.map((line)=>`${" ".repeat(indent)}${colors.dim(line)}`)]})}var OPTIONAL,USAGE_PREFIX,FULL_STOP,PROSE_MARKS,MAX_AGENT_EXAMPLES=2,MAX_INLINE_CHOICES=24;var init_help=__esm(()=>{init_mode();init_style();OPTIONAL=/(?<!\x1B)\[[^\]]+\]/g,USAGE_PREFIX=/^usage:\s*/i,FULL_STOP=/\.$/,PROSE_MARKS=/`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi});import process8 from"process";function wholeNumber(value,name,fallback,min=1){if(value===void 0)return fallback;let number=Number(value);if(!WHOLE.test(value)||!Number.isSafeInteger(number)||number<min)badUsage(`${name.startsWith("<")?name:`--${name}`} takes a whole number from ${min}, not ${value}`);return number}async function readInput(path,{noStdin="nothing is piped on stdin"}={}){if(path==="-"){if(process8.stdin.isTTY)fail(noStdin);return Bun.stdin.text()}let file=Bun.file(path);if(!await file.exists())fail(`no file ${path}`);return file.text()}var WHOLE;var init_input=__esm(()=>{init_args();WHOLE=/^\d+$/});import process9 from"process";import{parseArgs}from"util";function jsonOption(holds){return{type:"boolean",description:holds===void 0?"print JSON":`print JSON: ${holds}`}}function fail(message,code=2,hint){throw new Exit(message,code,hint)}function badUsage(message){throw new UsageError(message)}class Completing{options;positionals;candidates;constructor(options,positionals=[],candidates={}){this.options=options;this.positionals=positionals;this.candidates=candidates}}function applyOutput(color,plain,env=process9.env){let when=plain===!0?"never":color??"auto";if(when==="auto")return;if(when!=="always"&&when!=="never")badUsage(`--color takes auto, always or never, not ${when}`);if(when==="always")env.FORCE_COLOR="1",delete env.NO_COLOR;else env.NO_COLOR="1",delete env.FORCE_COLOR}function parse(args,usage,options,settings={}){let output=Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name])=>!(name in options))),all={...options,...output,help:{type:"boolean",short:"h",description:"show this help"}},listing=listed(all,settings.allowNegative===!0);if(completion.active)throw new Completing(listing,settings.positionals,settings.candidates);let{own,rest}=settings.trailing===!0?splitTrailing(args,all,settings.positionals?.length??0):splitRest(args,settings.rest===!0),helpJson=wantsHelpJson(process9.env,own),stripHelpJson=(arg)=>{if(arg==="--help=json")return["--help"];return arg==="--json"&&!("json"in options)?[]:[arg]},normalized=helpJson?own.flatMap(stripHelpJson):own,parsed;try{parsed=parseArgs({args:joinDashValues(withBare(withAliases(normalized,all),all),all),options:all,allowPositionals:!0,allowNegative:settings.allowNegative===!0,strict:!0})}catch(error){let message=parseError(error);throw new UsageError(message,nearestOption(message,all,settings.allowNegative===!0))}let values=parsed.values;if(applyOutput("color"in output?values.color:void 0,"plain"in output?values.plain:void 0),values.help===!0){let columns=takesControlCodes(process9.stdout)?process9.stdout.columns:void 0;throw console.log(helpJson?JSON.stringify(description(usage,settings,listing)):helpText(usage,listing,void 0,{...settings,bin:heading.bin,columns})),new HelpShown}if(checkChoices(parsed.values,all),checkConflicts(parsed.values,all),settings.positionals!==void 0)checkPositionals(parsed.positionals,settings.positionals);return{...parsed,values:parsed.values,positionals:parsed.positionals,rest}}function splitRest(args,passes){let separator=passes?args.indexOf("--"):-1;return{own:separator===-1?args:args.slice(0,separator),rest:separator===-1?void 0:args.slice(separator+1)}}function splitTrailing(args,options,count){let takesValue=(word)=>!word.includes("=")&&Object.entries(options).some(([name,{short,type}])=>type==="string"&&(word===`--${name}`||word===`-${short}`)),seen=0;if(count===0)return{own:args,rest:void 0};for(let at=0;at<args.length;at++){let word=args[at];if(word==="--")break;if(word.startsWith("-")){if(takesValue(word))at++;continue}if(seen++,seen===count)return{own:args.slice(0,at+1),rest:args.slice(at+1)}}return{own:args,rest:void 0}}function listed(options,allowNegative){if(!allowNegative)return options;return Object.fromEntries(Object.entries(options).flatMap(([name,option])=>{if(option.type!=="boolean"||option.negative===void 0)return[[name,option]];return[...option.description===void 0?[]:[[name,option]],[`no-${name}`,{type:"boolean",description:option.negative}]]}))}function withAliases(args,options){let named=new Map(Object.entries(options).flatMap(([name,{aliases=[]}])=>aliases.map((alias)=>[`--${alias}`,`--${name}`])));if(named.size===0)return args;let separator=args.indexOf("--");return[...(separator===-1?args:args.slice(0,separator)).map((arg)=>{let at=arg.indexOf("="),current=named.get(at===-1?arg:arg.slice(0,at));return current===void 0?arg:`${current}${at===-1?"":arg.slice(at)}`}),...separator===-1?[]:args.slice(separator)]}function withBare(args,options){let bare=new Map(Object.entries(options).flatMap(([name,{short,optional}])=>optional===void 0?[]:[[`--${name}`,optional],...short===void 0?[]:[[`-${short}`,optional]]]));if(bare.size===0)return args;let separator=args.indexOf("--"),own=separator===-1?args:args.slice(0,separator);return[...own.flatMap((arg,index)=>{let optional=bare.get(arg),next=own[index+1],value=next!==void 0&&(optional?.accepts===void 0?!next.startsWith("-"):optional.accepts.test(next));return optional===void 0||value?[arg]:[arg,optional.bare]}),...separator===-1?[]:args.slice(separator)]}function checkConflicts(values,options){let given=(name)=>values[name]!==void 0&&values[name]!==!1;for(let[name,{conflicts=[]}]of Object.entries(options)){let other=given(name)?conflicts.find(given):void 0;if(other!==void 0)badUsage(`--${name} cannot be used with --${other}`)}}function checkChoices(values,options){for(let[name,option]of Object.entries(options)){if(option.choices===void 0)continue;let given=values[name];for(let value of Array.isArray(given)?given:[given])if(typeof value==="string")oneOf(value,name,option.choices)}}function oneOf(value,name,choices){if(!choices.includes(value))badUsage(`${name.startsWith("<")?name:`--${name}`} takes one of ${choices.join(", ")}, not ${value}`);return value}function checkPositionals(given,names){let variadic=names.at(-1)?.replace("]","").endsWith("...")===!0,required=names.filter((name)=>!name.startsWith("[")).length;if(given.length<required)badUsage(`missing ${names[given.length]}`);if(!variadic&&given.length>names.length)badUsage(`unexpected argument ${given[names.length]}`)}function joinDashValues(args,options){let longOf=new Map(Object.entries(options).flatMap(([name,option])=>option.short===void 0?[[`--${name}`,name]]:[[`--${name}`,name],[`-${option.short}`,name]])),isOption=(arg)=>arg==="--"||longOf.has(arg.includes("=")?arg.slice(0,arg.indexOf("=")):arg),joined=[];for(let i=0;i<args.length;i++){let arg=args[i]??"";if(arg==="--")return[...joined,...args.slice(i)];let name=longOf.get(arg),next=args[i+1];if(name!==void 0&&options[name]?.type==="string"&&next!==void 0&&next.startsWith("-")&&next!=="-"&&!isOption(next))joined.push(`--${name}=${next}`),i++;else joined.push(arg)}return joined}function parseError(error){let message=upTo(error instanceof Error?error.message:String(error),". ");return`${message.charAt(0).toLowerCase()}${message.slice(1)}`}function nearestOption(message,options,allowNegative){let typed=UNKNOWN_OPTION.exec(message)?.[1];if(typed===void 0)return;let word=typed.replace(DASHES,"");if(word.length<2&&!typed.startsWith("--"))return;let known=Object.entries(options).flatMap(([name,option])=>[...option.short===void 0?[]:[`-${option.short}`],`--${name}`,...allowNegative&&option.type==="boolean"?[`--no-${name}`]:[]]),meant=closest(word,known.map((flag)=>flag.replace(DASHES,"")));return meant===void 0?void 0:`did you mean ${known.find((flag)=>flag.replace(DASHES,"")===meant)}?`}var DASHES,EXIT,Exit,UsageError,HelpShown,completion,heading,OUTPUT_OPTIONS,UNKNOWN_OPTION;var init_args=__esm(()=>{init_format();init_help();init_style();init_text();init_help();init_input();DASHES=/^-+/;EXIT=Symbol.for("@kaynooo/cli-kit/Exit");Exit=class Exit extends Error{code;hint;[EXIT]=!0;constructor(message,code,hint){super(message);this.code=code;this.hint=hint}static[Symbol.hasInstance](value){if(this!==Exit)return Function.prototype[Symbol.hasInstance].call(this,value);return typeof value==="object"&&value!==null&&value[EXIT]===!0}};UsageError=class UsageError extends Exit{constructor(message,hint){super(message,2,hint)}};HelpShown=class HelpShown extends Exit{constructor(){super("help shown",0)}};completion={active:!1},heading={bin:void 0},OUTPUT_OPTIONS={color:{type:"string",choices:["auto","always","never"],description:"auto (the default) colours on a terminal alone"},plain:{type:"boolean",description:"plain text, no colour or spinner: --color never"}};UNKNOWN_OPTION=/^unknown option '(-[^']+)'/});var init_folders=__esm(()=>{init_user_config()});import{existsSync as existsSync4}from"fs";import process17 from"process";init_args();import{readFileSync as readFileSync3,realpathSync}from"fs";import{resolve as resolve3}from"path";import process10 from"process";function commandLine(){try{return readFileSync3("/proc/self/cmdline","utf8").split("\x00").slice(0,-1)}catch{return}}function realPath(word){try{return realpathSync(resolve3(word))}catch{return}}function scriptArgs(argv=process10.argv.slice(2),cmdline=commandLine(),script=process10.argv[1]){let target=script===void 0?void 0:realPath(script)??script,at=cmdline===void 0||target===void 0?-1:cmdline.findIndex((word,index)=>index>0&&(resolve3(word)===script||realPath(word)===target)),after=at===-1?[]:cmdline.slice(at+1);return after[0]==="--"&&after.length===argv.length+1&&argv.every((word,index)=>word===after[index+1])?after:argv}init_format();init_mode();init_style();init_theme();init_args();init_format();init_format();init_style();init_text();init_theme();init_style();init_format();init_args();import{readFileSync as readFileSync5,realpathSync as realpathSync2}from"fs";import{dirname as dirname4,join as join5}from"path";import process14 from"process";import process11 from"process";var SOCKET_VARIABLE="KAYNOOO_ASKPASS_SOCKET";async function askpassClient(argv){let socketPath=process11.env[SOCKET_VARIABLE];if(socketPath===void 0)return;let request={prompt:argv[0]??"",...process11.env.SSH_ASKPASS_PROMPT==="none"?{notice:!0}:{}},{promise,resolve}=Promise.withResolvers(),received="";try{await Bun.connect({unix:socketPath,socket:{open:(socket)=>void socket.write(`${JSON.stringify(request)}
|
|
9
|
+
`),data:(_,chunk)=>{received+=chunk.toString()},close:()=>resolve(received),error:()=>resolve("")}})}catch{return 1}let reply=await promise;if(reply==="")return 1;let{answer}=JSON.parse(reply);if(request.notice===!0)return 0;if(answer===void 0)return 1;return process11.stdout.write(`${answer}
|
|
10
|
+
`),0}init_args();var COMPLETION_SHELLS=["fish","bash","zsh"];function completionScript(shell,bins,header=`# Generated by \`${bins[0]} --completions ${shell}\``){if(shell==="fish")return`${header}
|
|
11
|
+
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'
|
|
927
12
|
set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
|
|
928
13
|
set -l current (commandline -ct)
|
|
929
14
|
for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
|
|
@@ -933,8 +18,10 @@ var FISH_FUNCTION = `functions -q __kaynooo_cli_complete; or function __kaynooo_
|
|
|
933
18
|
echo $line
|
|
934
19
|
end
|
|
935
20
|
end
|
|
936
|
-
end
|
|
937
|
-
|
|
21
|
+
end
|
|
22
|
+
${bins.map((bin)=>`complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
|
|
23
|
+
`).join("")}`;if(shell==="bash")return`${header}
|
|
24
|
+
__kaynooo_cli_complete() {
|
|
938
25
|
local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
|
|
939
26
|
local -a lines
|
|
940
27
|
COMPREPLY=()
|
|
@@ -947,8 +34,10 @@ var BASH_FUNCTION = `__kaynooo_cli_complete() {
|
|
|
947
34
|
fi
|
|
948
35
|
done
|
|
949
36
|
COMPREPLY+=($(compgen -W "$words" -- "$cur"))
|
|
950
|
-
}
|
|
951
|
-
|
|
37
|
+
}
|
|
38
|
+
complete -F __kaynooo_cli_complete ${bins.join(" ")}
|
|
39
|
+
`;return`${header}
|
|
40
|
+
__kaynooo_cli_complete() {
|
|
952
41
|
local line
|
|
953
42
|
local -a described plain
|
|
954
43
|
for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
|
|
@@ -963,925 +52,87 @@ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
|
|
|
963
52
|
(( \${#described} )) && _describe -V value described
|
|
964
53
|
(( \${#plain} )) && compadd -- "\${plain[@]}"
|
|
965
54
|
return 0
|
|
966
|
-
}`;
|
|
967
|
-
function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
|
|
968
|
-
if (shell === "fish")
|
|
969
|
-
return `${header}
|
|
970
|
-
${FISH_FUNCTION}
|
|
971
|
-
${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
|
|
972
|
-
`).join("")}`;
|
|
973
|
-
if (shell === "bash")
|
|
974
|
-
return `${header}
|
|
975
|
-
${BASH_FUNCTION}
|
|
976
|
-
complete -F __kaynooo_cli_complete ${bins.join(" ")}
|
|
977
|
-
`;
|
|
978
|
-
return `${header}
|
|
979
|
-
${ZSH_FUNCTION}
|
|
980
|
-
compdef __kaynooo_cli_complete ${bins.join(" ")}
|
|
981
|
-
`;
|
|
982
|
-
}
|
|
983
|
-
|
|
984
|
-
// ../kit/src/notify.ts
|
|
985
|
-
init_format();
|
|
986
|
-
init_mode();
|
|
987
|
-
import process13 from "process";
|
|
988
|
-
var NOTIFY_AFTER_MS = 1e4;
|
|
989
|
-
var CANCELLED = 130;
|
|
990
|
-
function base64(text) {
|
|
991
|
-
return Buffer.from(text).toString("base64");
|
|
992
|
-
}
|
|
993
|
-
function notification(title, body, env = process13.env) {
|
|
994
|
-
const id = `kit${process13.pid}`;
|
|
995
|
-
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\\`];
|
|
996
|
-
return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
|
|
997
|
-
}
|
|
998
|
-
function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
|
|
999
|
-
if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
|
|
1000
|
-
return;
|
|
1001
|
-
stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
|
|
1002
|
-
}
|
|
1003
|
-
|
|
1004
|
-
// ../kit/src/cli.ts
|
|
1005
|
-
init_style();
|
|
1006
|
-
init_text();
|
|
1007
|
-
|
|
1008
|
-
// ../kit/src/usage.ts
|
|
1009
|
-
import { appendFileSync, mkdirSync } from "fs";
|
|
1010
|
-
import { homedir as homedir3 } from "os";
|
|
1011
|
-
import { dirname as dirname2, join as join4 } from "path";
|
|
1012
|
-
import process14 from "process";
|
|
1013
|
-
|
|
1014
|
-
// ../kit/src/logs.ts
|
|
1015
|
-
init_user_config();
|
|
1016
|
-
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
1017
|
-
var CLI_FOLDER = "kaynooo-cli";
|
|
1018
|
-
|
|
1019
|
-
// ../kit/src/usage.ts
|
|
1020
|
-
init_user_config();
|
|
1021
|
-
var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
|
|
1022
|
-
var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
|
|
1023
|
-
var LONGEST_NAME = 40;
|
|
1024
|
-
var usageError;
|
|
1025
|
-
function noteUsageError(message) {
|
|
1026
|
-
usageError = message;
|
|
1027
|
-
}
|
|
1028
|
-
function stateHome(env = process14.env) {
|
|
1029
|
-
return xdgFolder(env.XDG_STATE_HOME, join4(homedir3(), ".local", "state"));
|
|
1030
|
-
}
|
|
1031
|
-
function usagePath(env = process14.env) {
|
|
1032
|
-
return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
1033
|
-
}
|
|
1034
|
-
function usageRecorded(env = process14.env) {
|
|
1035
|
-
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
1036
|
-
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
1037
|
-
}
|
|
1038
|
-
function flagNames(argv) {
|
|
1039
|
-
const end = argv.indexOf("--");
|
|
1040
|
-
const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
|
|
1041
|
-
return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
|
|
1042
|
-
}
|
|
1043
|
-
function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
|
|
1044
|
-
const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
|
|
1045
|
-
usageError = undefined;
|
|
1046
|
-
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
|
|
1047
|
-
}
|
|
1048
|
-
function recordUsage(entry, env = process14.env) {
|
|
1049
|
-
if (!usageRecorded(env))
|
|
1050
|
-
return;
|
|
1051
|
-
try {
|
|
1052
|
-
const path = usagePath(env);
|
|
1053
|
-
mkdirSync(dirname2(path), { recursive: true, mode: 448 });
|
|
1054
|
-
appendFileSync(path, `${JSON.stringify(entry)}
|
|
1055
|
-
`, { mode: 384 });
|
|
1056
|
-
} catch {}
|
|
1057
|
-
}
|
|
1058
|
-
|
|
1059
|
-
// ../kit/src/cli.ts
|
|
1060
|
-
var LEVEL_OPTIONS = {
|
|
1061
|
-
...OUTPUT_OPTIONS,
|
|
1062
|
-
help: { type: "boolean", short: "h", description: "show this help" }
|
|
1063
|
-
};
|
|
1064
|
-
var TOP_OPTIONS = {
|
|
1065
|
-
...LEVEL_OPTIONS,
|
|
1066
|
-
version: { type: "boolean", short: "v", description: "print the version" },
|
|
1067
|
-
completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
|
|
1068
|
-
};
|
|
1069
|
-
function printError(prefix, message, hint, cause) {
|
|
1070
|
-
const colors = paint(process15.stderr);
|
|
1071
|
-
const styled = takesControlCodes(process15.stderr);
|
|
1072
|
-
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
1073
|
-
const under = (label, text, tint) => text === undefined ? "" : `
|
|
1074
|
-
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
1075
|
-
console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
|
|
1076
|
-
}
|
|
1077
|
-
function printJsonError(message, hint, cause) {
|
|
1078
|
-
console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
|
|
1079
|
-
}
|
|
1080
|
-
function wantsJson(argv) {
|
|
1081
|
-
const end = argv.indexOf("--");
|
|
1082
|
-
return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
|
|
1083
|
-
}
|
|
1084
|
-
function reportThrown(prefix, error, redact = (text) => text, json = false) {
|
|
1085
|
-
if (error instanceof HelpShown)
|
|
1086
|
-
return 0;
|
|
1087
|
-
const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
|
|
1088
|
-
const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
|
|
1089
|
-
const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
|
|
1090
|
-
if (error instanceof Exit && error.code === 2)
|
|
1091
|
-
noteUsageError(error.message);
|
|
1092
|
-
const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
|
|
1093
|
-
report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
|
|
1094
|
-
return error instanceof Exit ? error.code : 1;
|
|
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
|
-
function candidateLine(candidate) {
|
|
1111
|
-
return typeof candidate === "string" ? candidate : candidate.join("\t");
|
|
1112
|
-
}
|
|
1113
|
-
function positionalBeingTyped(before, { options, positionals }) {
|
|
1114
|
-
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
1115
|
-
const typed = [];
|
|
1116
|
-
let at = 0;
|
|
1117
|
-
while (at < before.length) {
|
|
1118
|
-
const word = before[at];
|
|
1119
|
-
if (word === "--") {
|
|
1120
|
-
typed.push(...before.slice(at + 1));
|
|
1121
|
-
break;
|
|
1122
|
-
}
|
|
1123
|
-
if (!word.startsWith("-"))
|
|
1124
|
-
typed.push(word);
|
|
1125
|
-
else if (takesValue(word))
|
|
1126
|
-
at++;
|
|
1127
|
-
at++;
|
|
1128
|
-
}
|
|
1129
|
-
const last = positionals.at(-1);
|
|
1130
|
-
if (typed.length < positionals.length)
|
|
1131
|
-
return { name: positionals[typed.length], typed };
|
|
1132
|
-
return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
|
|
1133
|
-
}
|
|
1134
|
-
async function leafCandidates(run, words) {
|
|
1135
|
-
const completing = await completingOf(run);
|
|
1136
|
-
if ((words.at(-1) ?? "").startsWith("-"))
|
|
1137
|
-
return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
|
|
1138
|
-
const flag = words.at(-2);
|
|
1139
|
-
const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
|
|
1140
|
-
const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
|
|
1141
|
-
if (option?.type === "string") {
|
|
1142
|
-
const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
|
|
1143
|
-
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1144
|
-
}
|
|
1145
|
-
const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
|
|
1146
|
-
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1147
|
-
}
|
|
1148
|
-
var COMPLETIONS = "--completions";
|
|
1149
|
-
function flagValue([flag = "", ...rest]) {
|
|
1150
|
-
return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
|
|
1151
|
-
}
|
|
1152
|
-
function printCompletionScript(name, args) {
|
|
1153
|
-
const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
|
|
1154
|
-
if (shell === undefined || args.length !== 1) {
|
|
1155
|
-
printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
|
|
1156
|
-
return 2;
|
|
1157
|
-
}
|
|
1158
|
-
console.log(completionScript(shell, [name]).trimEnd());
|
|
1159
|
-
return 0;
|
|
1160
|
-
}
|
|
1161
|
-
async function printCandidates(found) {
|
|
1162
|
-
for (const line of await found)
|
|
1163
|
-
console.log(line);
|
|
1164
|
-
return 0;
|
|
1165
|
-
}
|
|
1166
|
-
function packageVersion(entry = Bun.main) {
|
|
1167
|
-
let resolved = entry;
|
|
1168
|
-
try {
|
|
1169
|
-
resolved = realpathSync2(entry);
|
|
1170
|
-
} catch {}
|
|
1171
|
-
for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
|
|
1172
|
-
try {
|
|
1173
|
-
const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
|
|
1174
|
-
if (typeof version === "string")
|
|
1175
|
-
return version;
|
|
1176
|
-
} catch {}
|
|
1177
|
-
if (dirname3(dir) === dir)
|
|
1178
|
-
return "0.0.0";
|
|
1179
|
-
}
|
|
1180
|
-
}
|
|
1181
|
-
async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
|
|
1182
|
-
const answered = await askpassClient(argv);
|
|
1183
|
-
if (answered !== undefined)
|
|
1184
|
-
return answered;
|
|
1185
|
-
if (argv[0] === COMPLETE)
|
|
1186
|
-
return printCandidates(leafCandidates(run, argv.slice(1)));
|
|
1187
|
-
if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
|
|
1188
|
-
return printCompletionScript(name, flagValue(argv));
|
|
1189
|
-
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
|
|
1190
|
-
console.log(version ?? packageVersion());
|
|
1191
|
-
return 0;
|
|
1192
|
-
}
|
|
1193
|
-
let code;
|
|
1194
|
-
const started = performance.now();
|
|
1195
|
-
heading.bin = { name, version: () => version ?? packageVersion() };
|
|
1196
|
-
try {
|
|
1197
|
-
code = await run(argv);
|
|
1198
|
-
} catch (error) {
|
|
1199
|
-
code = reportThrown(name, error, redact, wantsJson(argv));
|
|
1200
|
-
} finally {
|
|
1201
|
-
heading.bin = undefined;
|
|
1202
|
-
}
|
|
1203
|
-
notifyEnd(name, code, performance.now() - started);
|
|
1204
|
-
if (usage !== false) {
|
|
1205
|
-
try {
|
|
1206
|
-
recordUsage(usageEntry(name, undefined, argv, code, { ms: performance.now() - started }));
|
|
1207
|
-
} catch {}
|
|
1208
|
-
}
|
|
1209
|
-
return code;
|
|
1210
55
|
}
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
init_format();
|
|
1221
|
-
|
|
1222
|
-
// ../kit/src/git.ts
|
|
1223
|
-
init_args();
|
|
1224
|
-
// ../kit/src/limit.ts
|
|
1225
|
-
init_args();
|
|
1226
|
-
|
|
1227
|
-
// ../kit/src/index.ts
|
|
1228
|
-
init_mode();
|
|
1229
|
-
|
|
1230
|
-
// ../kit/src/report.ts
|
|
1231
|
-
init_style();
|
|
1232
|
-
init_text();
|
|
1233
|
-
// ../kit/src/secrets.ts
|
|
1234
|
-
var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
|
|
1235
|
-
var NOT_PASSWORDS = new Set(["compass", "encompass", "bypass", "overpass", "underpass", "surpass", "trespass"]);
|
|
1236
|
-
// ../kit/src/sessions.ts
|
|
1237
|
-
var {Glob } = globalThis.Bun;
|
|
1238
|
-
var SESSION_FILES = new Glob("*.json");
|
|
1239
|
-
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
1240
|
-
|
|
1241
|
-
// ../kit/src/index.ts
|
|
1242
|
-
init_style();
|
|
1243
|
-
init_text();
|
|
1244
|
-
init_theme();
|
|
1245
|
-
init_user_config();
|
|
1246
|
-
|
|
1247
|
-
// ../kit/src/watch.ts
|
|
1248
|
-
init_args();
|
|
1249
|
-
init_input();
|
|
1250
|
-
init_style();
|
|
1251
|
-
// ../kit/src/workspace-root.ts
|
|
1252
|
-
init_user_config();
|
|
1253
|
-
// src/code.ts
|
|
1254
|
-
var WORD_START = /[a-z_$]/i;
|
|
1255
|
-
var WORD = /^[\w$-]+/;
|
|
1256
|
-
var NUMBER = /^(?:0x[\da-f_]+|\d[\d_]*(?:\.\d[\d_]*)?(?:e[+-]?\d+)?)/i;
|
|
1257
|
-
var PREVIOUS_WORD = /[\w$]$/;
|
|
1258
|
-
var AFTER_KEY = /^\s*:/;
|
|
1259
|
-
var YAML_KEY = /^(\s*(?:- )?)([\w.\-/]+)(?=:(?:\s|$))/;
|
|
1260
|
-
var SETTING_KEY = /^(\s*)([\w.-]+)(?=\s*[=:])/;
|
|
1261
|
-
var SECTION = /^\s*\[.*\]\s*$/;
|
|
1262
|
-
var WHITESPACE = /\s/;
|
|
1263
|
-
var FLAG = /^--?[a-z][\w-]*/i;
|
|
1264
|
-
var COMMAND_END = /[|&;(]\s*$/;
|
|
1265
|
-
var PROMPT = /^\s*(?:[$>]\s*)?$/;
|
|
1266
|
-
var DIGIT = /\d/;
|
|
1267
|
-
var TRAILING_NEWLINE = /\n$/;
|
|
1268
|
-
var LEADING_DOT = /^\./;
|
|
1269
|
-
var TRIPLE_QUOTES = ['"""', "'''"];
|
|
1270
|
-
function words(list) {
|
|
1271
|
-
return new Set(list.split(" "));
|
|
1272
|
-
}
|
|
1273
|
-
var SLASHES = { line: ["//"], block: ["/*", "*/"] };
|
|
1274
|
-
var HASH = { line: ["#"] };
|
|
1275
|
-
var CONSTANTS = "true false null undefined NaN Infinity";
|
|
1276
|
-
var C_LIKE = "if else for while do switch case default break continue return throw try catch finally new delete typeof instanceof in of void yield await async static public private protected readonly abstract extends implements super this";
|
|
1277
|
-
var SCRIPT = `${C_LIKE} const let var function class import export from as type interface enum namespace declare satisfies keyof is get set ${CONSTANTS}`;
|
|
1278
|
-
var LANGUAGES = {
|
|
1279
|
-
script: { ...SLASHES, quotes: "\"'`", keywords: words(SCRIPT) },
|
|
1280
|
-
json: { line: [], quotes: '"', keywords: words("true false null"), quotedKeys: true },
|
|
1281
|
-
jsonc: { ...SLASHES, quotes: '"', keywords: words("true false null"), quotedKeys: true },
|
|
1282
|
-
python: { ...HASH, quotes: `"'`, keywords: words("def class return if elif else for while in not and or is import from as with try except finally raise pass break continue lambda yield async await global nonlocal del assert None True False self") },
|
|
1283
|
-
shell: { ...HASH, commands: true, quotes: "\"'`", keywords: words("if then else elif fi for while until do done case esac in function return exit local export set unset source alias echo cd end switch begin and or not") },
|
|
1284
|
-
yaml: { ...HASH, quotes: `"'`, keywords: words("true false null yes no"), key: YAML_KEY, quotedKeys: true },
|
|
1285
|
-
toml: { ...HASH, quotes: `"'`, keywords: words("true false"), key: SETTING_KEY, section: SECTION },
|
|
1286
|
-
ini: { line: ["#", ";"], quotes: `"'`, keywords: words("true false yes no on off"), key: SETTING_KEY, section: SECTION },
|
|
1287
|
-
css: { line: [], block: ["/*", "*/"], quotes: `"'`, keywords: words("important inherit initial unset auto none") },
|
|
1288
|
-
html: { line: [], block: ["<!--", "-->"], quotes: `"'`, keywords: words("") },
|
|
1289
|
-
sql: { line: ["--"], block: ["/*", "*/"], quotes: "\"'`", keywords: words("select from where and or not insert into values update set delete create alter drop table index view join left right inner outer full on group by order having limit offset as distinct union all null is in like between case when then else end primary key foreign references default unique with returning true false") },
|
|
1290
|
-
rust: { ...SLASHES, quotes: '"', keywords: words("fn let mut const static struct enum impl trait pub use mod crate self super if else match for while loop break continue return as in ref move async await dyn where type unsafe true false None Some Ok Err") },
|
|
1291
|
-
go: { ...SLASHES, quotes: "\"'`", keywords: words("func var const type struct interface map chan package import if else for range switch case default break continue return go defer select fallthrough goto nil true false") },
|
|
1292
|
-
php: { ...SLASHES, line: ["//", "#"], quotes: `"'`, keywords: words(`${C_LIKE} function class interface trait namespace use public private protected static final echo array fn match list isset empty require include require_once include_once true false null`) },
|
|
1293
|
-
java: { ...SLASHES, quotes: `"'`, keywords: words(`${C_LIKE} class interface enum package import final void int long double float boolean char byte short true false null var record`) },
|
|
1294
|
-
c: { ...SLASHES, quotes: `"'`, keywords: words(`${C_LIKE} struct union typedef enum const volatile extern sizeof void int long double float char short unsigned signed auto register inline static include define ifdef ifndef endif pragma true false NULL nullptr class template typename namespace using bool`) },
|
|
1295
|
-
ruby: { ...HASH, quotes: `"'`, keywords: words("def end class module if elsif else unless while until for in do begin rescue ensure return yield self nil true false and or not require require_relative include extend attr_accessor attr_reader puts then case when") },
|
|
1296
|
-
lua: { line: ["--"], quotes: `"'`, keywords: words("function end if then else elseif for while do repeat until return local break in and or not nil true false") },
|
|
1297
|
-
dockerfile: { ...HASH, quotes: `"'`, keywords: words("FROM RUN CMD LABEL EXPOSE ENV ADD COPY ENTRYPOINT VOLUME USER WORKDIR ARG ONBUILD STOPSIGNAL HEALTHCHECK SHELL AS") },
|
|
1298
|
-
makefile: { ...HASH, quotes: `"'`, keywords: words("ifeq ifneq ifdef ifndef else endif include define endef export") }
|
|
1299
|
-
};
|
|
1300
|
-
var ALIASES = {
|
|
1301
|
-
script: ["ts", "tsx", "mts", "cts", "js", "jsx", "mjs", "cjs", "typescript", "javascript", "vue", "svelte"],
|
|
1302
|
-
json: ["json", "jsonl", "ndjson"],
|
|
1303
|
-
jsonc: ["jsonc", "json5"],
|
|
1304
|
-
python: ["py", "python"],
|
|
1305
|
-
shell: ["sh", "bash", "zsh", "fish", "shell", "console"],
|
|
1306
|
-
yaml: ["yml", "yaml"],
|
|
1307
|
-
toml: ["toml"],
|
|
1308
|
-
ini: ["ini", "conf", "cfg", "properties", "editorconfig"],
|
|
1309
|
-
css: ["css", "scss", "less"],
|
|
1310
|
-
html: ["html", "htm", "xml", "svg"],
|
|
1311
|
-
sql: ["sql"],
|
|
1312
|
-
rust: ["rs", "rust"],
|
|
1313
|
-
go: ["go", "golang"],
|
|
1314
|
-
php: ["php"],
|
|
1315
|
-
java: ["java", "kt", "kts", "cs", "swift", "dart", "scala"],
|
|
1316
|
-
c: ["c", "h", "cpp", "cc", "hpp", "cxx"],
|
|
1317
|
-
ruby: ["rb", "ruby"],
|
|
1318
|
-
lua: ["lua"],
|
|
1319
|
-
dockerfile: ["dockerfile", "containerfile"],
|
|
1320
|
-
makefile: ["makefile", "mk", "just", "justfile"]
|
|
1321
|
-
};
|
|
1322
|
-
var BY_NAME = new Map(Object.entries(ALIASES).flatMap(([name, aliases]) => aliases.map((alias) => [alias, name])));
|
|
1323
|
-
var EXTENSION = /\.([^./]+)$/;
|
|
1324
|
-
var BASENAME = /[^/]*$/;
|
|
1325
|
-
function languageOf(nameOrPath) {
|
|
1326
|
-
const base = (BASENAME.exec(nameOrPath)?.[0] ?? "").toLowerCase();
|
|
1327
|
-
const extension = EXTENSION.exec(base)?.[1];
|
|
1328
|
-
return BY_NAME.get(extension ?? base) ?? BY_NAME.get(base.replace(LEADING_DOT, ""));
|
|
1329
|
-
}
|
|
1330
|
-
function paintLines(text, paint) {
|
|
1331
|
-
return text.split(`
|
|
1332
|
-
`).map((line) => line === "" ? line : paint(line)).join(`
|
|
1333
|
-
`);
|
|
1334
|
-
}
|
|
1335
|
-
function stringEnd(source, start, quote) {
|
|
1336
|
-
const triple = TRIPLE_QUOTES.find((each) => source.startsWith(each, start));
|
|
1337
|
-
const multiline = quote === "`" || triple !== undefined;
|
|
1338
|
-
const closer = triple ?? quote;
|
|
1339
|
-
let at = start + closer.length;
|
|
1340
|
-
while (at < source.length) {
|
|
1341
|
-
const char = source.charAt(at);
|
|
1342
|
-
if (char === "\\") {
|
|
1343
|
-
at += 2;
|
|
1344
|
-
} else if (source.startsWith(closer, at)) {
|
|
1345
|
-
return at + closer.length;
|
|
1346
|
-
} else if (char === `
|
|
1347
|
-
` && !multiline) {
|
|
1348
|
-
return at;
|
|
1349
|
-
} else {
|
|
1350
|
-
at++;
|
|
1351
|
-
}
|
|
1352
|
-
}
|
|
1353
|
-
return source.length;
|
|
1354
|
-
}
|
|
1355
|
-
function lineLead(line, language, theme) {
|
|
1356
|
-
if (language.section?.test(line) === true)
|
|
1357
|
-
return { done: theme.heading(line), rest: "" };
|
|
1358
|
-
const match = language.key?.exec(line);
|
|
1359
|
-
if (match === null || match === undefined)
|
|
1360
|
-
return { done: "", rest: line };
|
|
1361
|
-
return { done: `${match[1] ?? ""}${theme.accent(match[2] ?? "")}`, rest: line.slice(match[0].length) };
|
|
1362
|
-
}
|
|
1363
|
-
function highlight(source, name, theme) {
|
|
1364
|
-
const language = LANGUAGES[name];
|
|
1365
|
-
const text = source.replaceAll(`\r
|
|
1366
|
-
`, `
|
|
1367
|
-
`);
|
|
1368
|
-
let out = "";
|
|
1369
|
-
let at = 0;
|
|
1370
|
-
while (at < text.length) {
|
|
1371
|
-
const lineStart = at === 0 || text.charAt(at - 1) === `
|
|
1372
|
-
`;
|
|
1373
|
-
if (lineStart && (language.key !== undefined || language.section !== undefined)) {
|
|
1374
|
-
const lineEnd = text.indexOf(`
|
|
1375
|
-
`, at);
|
|
1376
|
-
const line = text.slice(at, lineEnd === -1 ? text.length : lineEnd);
|
|
1377
|
-
const { done, rest } = lineLead(line, language, theme);
|
|
1378
|
-
if (done !== "") {
|
|
1379
|
-
out += done;
|
|
1380
|
-
at += line.length - rest.length;
|
|
1381
|
-
continue;
|
|
1382
|
-
}
|
|
1383
|
-
}
|
|
1384
|
-
const char = text.charAt(at);
|
|
1385
|
-
const comment = language.line.find((each) => text.startsWith(each, at));
|
|
1386
|
-
if (comment !== undefined) {
|
|
1387
|
-
const end = text.indexOf(`
|
|
1388
|
-
`, at);
|
|
1389
|
-
const stop = end === -1 ? text.length : end;
|
|
1390
|
-
out += paintLines(text.slice(at, stop), theme.dim);
|
|
1391
|
-
at = stop;
|
|
1392
|
-
} else if (language.block !== undefined && text.startsWith(language.block[0], at)) {
|
|
1393
|
-
const end = text.indexOf(language.block[1], at + language.block[0].length);
|
|
1394
|
-
const stop = end === -1 ? text.length : end + language.block[1].length;
|
|
1395
|
-
out += paintLines(text.slice(at, stop), theme.dim);
|
|
1396
|
-
at = stop;
|
|
1397
|
-
} else if (language.quotes.includes(char)) {
|
|
1398
|
-
const stop = stringEnd(text, at, char);
|
|
1399
|
-
const isKey = language.quotedKeys === true && AFTER_KEY.test(text.slice(stop, !text.includes(`
|
|
1400
|
-
`, stop) ? undefined : text.indexOf(`
|
|
1401
|
-
`, stop)));
|
|
1402
|
-
out += paintLines(text.slice(at, stop), isKey ? theme.accent : theme.string);
|
|
1403
|
-
at = stop;
|
|
1404
|
-
} else if (DIGIT.test(char) && !PREVIOUS_WORD.test(text.slice(Math.max(0, at - 1), at))) {
|
|
1405
|
-
const number = NUMBER.exec(text.slice(at))?.[0] ?? char;
|
|
1406
|
-
out += theme.number(number);
|
|
1407
|
-
at += number.length;
|
|
1408
|
-
} else if (language.commands === true && char === "-" && (at === 0 || WHITESPACE.test(text.charAt(at - 1))) && FLAG.test(text.slice(at))) {
|
|
1409
|
-
const flag = FLAG.exec(text.slice(at))?.[0] ?? char;
|
|
1410
|
-
out += theme.number(flag);
|
|
1411
|
-
at += flag.length;
|
|
1412
|
-
} else if (WORD_START.test(char)) {
|
|
1413
|
-
const word = WORD.exec(text.slice(at))?.[0] ?? char;
|
|
1414
|
-
const before = text.slice(text.lastIndexOf(`
|
|
1415
|
-
`, at - 1) + 1, at);
|
|
1416
|
-
const command = language.commands === true && (PROMPT.test(before) || COMMAND_END.test(before));
|
|
1417
|
-
if (language.keywords.has(word))
|
|
1418
|
-
out += theme.keyword(word);
|
|
1419
|
-
else
|
|
1420
|
-
out += command && !word.startsWith("$") ? theme.accent(word) : word;
|
|
1421
|
-
at += word.length;
|
|
1422
|
-
} else {
|
|
1423
|
-
out += char;
|
|
1424
|
-
at++;
|
|
1425
|
-
}
|
|
1426
|
-
}
|
|
1427
|
-
return out;
|
|
1428
|
-
}
|
|
1429
|
-
function renderCode(source, name, theme, lineNumbers) {
|
|
1430
|
-
const text = escapeControls(source.replaceAll(`\r
|
|
1431
|
-
`, `
|
|
1432
|
-
`)).replace(TRAILING_NEWLINE, "");
|
|
1433
|
-
const shown = name === undefined ? text : highlight(text, name, theme);
|
|
1434
|
-
if (!lineNumbers)
|
|
1435
|
-
return `${shown}
|
|
1436
|
-
`;
|
|
1437
|
-
const lines = shown.split(`
|
|
1438
|
-
`);
|
|
1439
|
-
const digits = String(lines.length).length;
|
|
1440
|
-
return `${lines.map((line, index) => `${theme.dim(`${String(index + 1).padStart(digits)} \u2502`)} ${line}`.trimEnd()).join(`
|
|
56
|
+
__kaynooo_cli_register() {
|
|
57
|
+
add-zsh-hook -d precmd __kaynooo_cli_register
|
|
58
|
+
(( $+functions[compdef] )) || { autoload -Uz compinit && compinit }
|
|
59
|
+
compdef __kaynooo_cli_complete $__kaynooo_cli_bins
|
|
60
|
+
}
|
|
61
|
+
autoload -Uz add-zsh-hook
|
|
62
|
+
add-zsh-hook precmd __kaynooo_cli_register
|
|
63
|
+
typeset -gaU __kaynooo_cli_bins
|
|
64
|
+
__kaynooo_cli_bins+=(${bins.join(" ")})
|
|
65
|
+
`}var COMPLETE="__complete",FILES="__files__",COMPLETIONS="--completions";async function completingOf(run){completion.active=!0;try{await run([])}catch(error){if(error instanceof Completing)return error}finally{completion.active=!1}return new Completing({})}function candidateLine(candidate){return typeof candidate==="string"?candidate:candidate.join("\t")}function positionalBeingTyped(before,{options,positionals}){let takesValue=(word)=>!word.includes("=")&&Object.entries(options).some(([name,{short,type}])=>type==="string"&&(word===`--${name}`||word===`-${short}`)),typed=[],at=0;while(at<before.length){let word=before[at];if(word==="--"){typed.push(...before.slice(at+1));break}if(!word.startsWith("-"))typed.push(word);else if(takesValue(word))at++;at++}let last=positionals.at(-1);if(typed.length<positionals.length)return{name:positionals[typed.length],typed};return{name:last?.replace("]","").endsWith("...")===!0?last:void 0,typed}}async function leafCandidates(run,words){let completing=await completingOf(run);if((words.at(-1)??"").startsWith("-"))return Object.entries(completing.options).map(([name,option])=>option.description===void 0?`--${name}`:`--${name} ${option.description}`);let flag=words.at(-2),option=flag?.startsWith("-")===!0?Object.entries(completing.options).find(([name,{short}])=>flag===`--${name}`||flag===`-${short}`)?.[1]:void 0,{name,typed}=positionalBeingTyped(words.slice(0,-1),completing);if(option?.type==="string"){let values=option.choices===void 0?await option.candidates?.(typed):option.choices;return values===void 0?[FILES]:values.map(candidateLine)}let values=name===void 0?void 0:await completing.candidates[name]?.(typed);return values===void 0?[FILES]:values.map(candidateLine)}function flagValue([flag="",...rest]){return flag.includes("=")?[flag.slice(flag.indexOf("=")+1),...rest]:rest}function printCompletionScript(name,args,reportError){let shell=COMPLETION_SHELLS.find((each)=>each===args[0]);if(shell===void 0||args.length!==1)return reportError(name,`${COMPLETIONS} takes one of ${COMPLETIONS_SHELLS_LIST()}`,`${name} ${COMPLETIONS} fish`),2;return console.log(completionScript(shell,[name]).trimEnd()),0}function COMPLETIONS_SHELLS_LIST(){return COMPLETION_SHELLS.join(", ")}async function printCandidates(found){for(let line of await found)console.log(line);return 0}init_mode();init_format();init_mode();import process12 from"process";var NOTIFY_AFTER_MS=1e4,CANCELLED=130;function base64(text){return Buffer.from(text).toString("base64")}function sanitizeOsc(text){return text.replaceAll(/[\x00-\x1F\x7F;]/g," ")}function wrapTmux(codes,env){return codes.map((code)=>env.TMUX===void 0||env.TMUX===""?code:`\x1BPtmux;${code.replaceAll("\x1B","\x1B\x1B")}\x1B\\`).join("")}function notification(title,body,env=process12.env){let program=env.TERM_PROGRAM??"",term=env.TERM??"";if(program==="WezTerm"||term.startsWith("foot")||term.startsWith("rxvt"))return wrapTmux([`\x1B]777;notify;${sanitizeOsc(title)};${sanitizeOsc(body)}\x1B\\`],env);if(program==="iTerm.app"||env.WT_SESSION!==void 0&&env.WT_SESSION!=="")return wrapTmux([`\x1B]9;${sanitizeOsc(title)}: ${sanitizeOsc(body)}\x1B\\`],env);let id=`kit${process12.pid}`,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\\`];return wrapTmux(codes,env)}function notifyEnd(command,code,ms,{stream=process12.stderr,env=process12.env}={}){if(ms<NOTIFY_AFTER_MS||code===CANCELLED||outputMode(stream,env)!=="terminal")return;stream.write(notification(command,code===0?`done in ${formatDuration(ms)}`:`failed with exit ${code} after ${formatDuration(ms)}`,env))}init_style();init_text();import{appendFileSync,mkdirSync as mkdirSync2,readFileSync as readFileSync4,renameSync,statSync as statSync3,writeFileSync as writeFileSync2}from"fs";import{homedir as homedir3}from"os";import{dirname as dirname3,join as join4}from"path";import process13 from"process";init_user_config();var CLI_FOLDER="kaynooo-cli";init_user_config();var MAX_USAGE_BYTES=2097152,UNKNOWN_OPTION2=/unknown option '(--[a-z][a-z0-9-]*)[=']/,FLAG_NAME=/^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/,LONGEST_NAME=40,usageError;function noteUsageError(message){usageError=message}function stateHome(env=process13.env){return xdgFolder(env.XDG_STATE_HOME,join4(homedir3(),".local","state"))}function usagePath(env=process13.env){return join4(stateHome(env),CLI_FOLDER,"usage.jsonl")}function usageRecorded(env=process13.env){let off=env.KAYNOOO_CLI_NO_USAGE;return env.NODE_ENV!=="test"&&(off===void 0||off===""||off==="0")}function flagNames(argv){let end=argv.indexOf("--"),names=(end===-1?argv:argv.slice(0,end)).filter((word)=>word.startsWith("-")&&word!=="-").map((word)=>word.includes("=")?word.slice(0,word.indexOf("=")):word);return[...new Set(names)].filter((name)=>name.length<=LONGEST_NAME&&FLAG_NAME.test(name))}function usageEntry(bin,command,argv,code,{ms,mode,now=new Date}={}){let unknown=code===2&&usageError!==void 0?UNKNOWN_OPTION2.exec(usageError)?.[1]:void 0;return usageError=void 0,{at:now.toISOString(),bin,...command===void 0?{}:{command},flags:flagNames(argv),code,...unknown===void 0?{}:{unknown},...ms===void 0?{}:{ms:Math.round(ms)},...mode===void 0?{}:{mode}}}function trimUsage(path,maxBytes){let info=statSync3(path,{throwIfNoEntry:!1});if(info===void 0||info.size<=maxBytes)return;let lines=readFileSync4(path,"utf8").split(`
|
|
66
|
+
`).filter(Boolean),kept=`${lines.slice(Math.floor(lines.length/2)).join(`
|
|
1441
67
|
`)}
|
|
1442
|
-
`;
|
|
1443
|
-
}
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
var MAX_TOKENS = 300;
|
|
1461
|
-
function looksLikeDiff(text) {
|
|
1462
|
-
const first = stripAnsi(text).split(`
|
|
1463
|
-
`).find((line) => line.trim() !== "") ?? "";
|
|
1464
|
-
return first.startsWith("diff --git ") || first.startsWith("--- ") || first.startsWith("@@ ") || first.startsWith("Index: ") || COMMIT.test(first);
|
|
1465
|
-
}
|
|
1466
|
-
function changedChars(a, b) {
|
|
1467
|
-
const left = a.match(TOKEN) ?? [];
|
|
1468
|
-
const right = b.match(TOKEN) ?? [];
|
|
1469
|
-
if (left.length > MAX_TOKENS || right.length > MAX_TOKENS)
|
|
1470
|
-
return;
|
|
1471
|
-
const common = Array.from({ length: left.length + 1 }, () => Array.from({ length: right.length + 1 }).fill(0));
|
|
1472
|
-
for (let i = left.length - 1;i >= 0; i--) {
|
|
1473
|
-
for (let j = right.length - 1;j >= 0; j--)
|
|
1474
|
-
common[i][j] = left[i] === right[j] ? common[i + 1][j + 1] + 1 : Math.max(common[i + 1][j], common[i][j + 1]);
|
|
1475
|
-
}
|
|
1476
|
-
const flags = (tokens) => tokens.flatMap((token) => Array.from({ length: token.length }).fill(true));
|
|
1477
|
-
const changedLeft = flags(left);
|
|
1478
|
-
const changedRight = flags(right);
|
|
1479
|
-
let shared = false;
|
|
1480
|
-
let i = 0;
|
|
1481
|
-
let j = 0;
|
|
1482
|
-
let at = 0;
|
|
1483
|
-
let to = 0;
|
|
1484
|
-
while (i < left.length && j < right.length) {
|
|
1485
|
-
if (left[i] === right[j]) {
|
|
1486
|
-
shared ||= WORD_CHAR.test(left[i]);
|
|
1487
|
-
changedLeft.fill(false, at, at + left[i].length);
|
|
1488
|
-
changedRight.fill(false, to, to + right[j].length);
|
|
1489
|
-
at += left[i].length;
|
|
1490
|
-
to += right[j].length;
|
|
1491
|
-
i++;
|
|
1492
|
-
j++;
|
|
1493
|
-
} else if (common[i + 1][j] >= common[i][j + 1]) {
|
|
1494
|
-
at += left[i++].length;
|
|
1495
|
-
} else {
|
|
1496
|
-
to += right[j++].length;
|
|
1497
|
-
}
|
|
1498
|
-
}
|
|
1499
|
-
return shared ? [changedLeft, changedRight] : undefined;
|
|
1500
|
-
}
|
|
1501
|
-
function paintContent({ mark, text, language }, theme, changed) {
|
|
1502
|
-
const tone = mark === "+" ? theme.added : theme.removed;
|
|
1503
|
-
const code = text.slice(1);
|
|
1504
|
-
const source = language === undefined ? code : highlight(code, language, theme);
|
|
1505
|
-
const cells = [{ char: mark, style: "", changed: false }];
|
|
1506
|
-
let style = "";
|
|
1507
|
-
let from = 0;
|
|
1508
|
-
for (const escape of source.matchAll(ESCAPE2)) {
|
|
1509
|
-
for (const char of source.slice(from, escape.index).split(""))
|
|
1510
|
-
cells.push({ char, style, changed: changed?.[cells.length - 1] ?? false });
|
|
1511
|
-
style = CLOSING.has(escape[1]) ? "" : style + escape[0];
|
|
1512
|
-
from = escape.index + escape[0].length;
|
|
1513
|
-
}
|
|
1514
|
-
for (const char of source.slice(from).split(""))
|
|
1515
|
-
cells.push({ char, style, changed: changed?.[cells.length - 1] ?? false });
|
|
1516
|
-
let out = "";
|
|
1517
|
-
for (let at = 0;at < cells.length; ) {
|
|
1518
|
-
let end = at + 1;
|
|
1519
|
-
while (end < cells.length && cells[end].style === cells[at].style && cells[end].changed === cells[at].changed)
|
|
1520
|
-
end++;
|
|
1521
|
-
const run = cells.slice(at, end).map((cell) => cell.char).join("");
|
|
1522
|
-
const shown = cells[at].style === "" ? tone(run) : `${cells[at].style}${run}\x1B[0m`;
|
|
1523
|
-
out += cells[at].changed ? theme.changed(shown) : shown;
|
|
1524
|
-
at = end;
|
|
1525
|
-
}
|
|
1526
|
-
return out;
|
|
1527
|
-
}
|
|
1528
|
-
function renderDiff(text, theme) {
|
|
1529
|
-
let oldLeft = 0;
|
|
1530
|
-
let newLeft = 0;
|
|
1531
|
-
let language;
|
|
1532
|
-
const lines = escapeControls(text.replace(GIT_COLOR, "").replaceAll(`\r
|
|
1533
|
-
`, `
|
|
1534
|
-
`)).replace(TRAILING_NEWLINE2, "").split(`
|
|
1535
|
-
`).map((line) => {
|
|
1536
|
-
if ((oldLeft > 0 || newLeft > 0) && line !== "" && !HUNK_LINE.has(line[0] ?? ""))
|
|
1537
|
-
oldLeft = newLeft = 0;
|
|
1538
|
-
if (oldLeft > 0 || newLeft > 0) {
|
|
1539
|
-
const mark = line[0];
|
|
1540
|
-
if (mark === "+") {
|
|
1541
|
-
newLeft--;
|
|
1542
|
-
return { mark, text: line, language };
|
|
1543
|
-
}
|
|
1544
|
-
if (mark === "-") {
|
|
1545
|
-
oldLeft--;
|
|
1546
|
-
return { mark, text: line, language };
|
|
1547
|
-
}
|
|
1548
|
-
if (mark === "\\")
|
|
1549
|
-
return theme.dim(line);
|
|
1550
|
-
oldLeft--;
|
|
1551
|
-
newLeft--;
|
|
1552
|
-
return line;
|
|
1553
|
-
}
|
|
1554
|
-
const hunk = HUNK.exec(line);
|
|
1555
|
-
if (hunk !== null) {
|
|
1556
|
-
oldLeft = Number(hunk[1] ?? 1);
|
|
1557
|
-
newLeft = Number(hunk[2] ?? 1);
|
|
1558
|
-
return `${theme.accent(line.slice(0, line.length - (hunk[3] ?? "").length))}${theme.dim(hunk[3] ?? "")}`;
|
|
1559
|
-
}
|
|
1560
|
-
const file = FILE_HEADER.exec(line);
|
|
1561
|
-
if (file !== null) {
|
|
1562
|
-
language = languageOf(file[2] ?? "");
|
|
1563
|
-
return `${theme.dim("diff")} ${theme.bold(theme.path(file[2] ?? ""))}`;
|
|
1564
|
-
}
|
|
1565
|
-
const commit = COMMIT.exec(line);
|
|
1566
|
-
if (commit !== null)
|
|
1567
|
-
return `${theme.dim(commit[1] ?? "")}${theme.id(commit[2] ?? "")}${theme.dim(commit[3] ?? "")}`;
|
|
1568
|
-
const target = NEW_FILE.exec(line)?.[1];
|
|
1569
|
-
if (target !== undefined && target !== "/dev/null")
|
|
1570
|
-
language = languageOf(target);
|
|
1571
|
-
return MARKERS.test(line) || META.test(line) || COMMIT_META.test(line) ? theme.dim(line) : line;
|
|
1572
|
-
});
|
|
1573
|
-
const changes = new Map;
|
|
1574
|
-
for (let at = 0;at < lines.length; ) {
|
|
1575
|
-
const first = lines[at];
|
|
1576
|
-
const isRemoved = typeof first === "object" && first.mark === "-";
|
|
1577
|
-
if (!isRemoved) {
|
|
1578
|
-
at++;
|
|
1579
|
-
continue;
|
|
1580
|
-
}
|
|
1581
|
-
let split = at;
|
|
1582
|
-
while (typeof lines[split] === "object" && lines[split].mark === "-")
|
|
1583
|
-
split++;
|
|
1584
|
-
let end = split;
|
|
1585
|
-
while (typeof lines[end] === "object" && lines[end].mark === "+")
|
|
1586
|
-
end++;
|
|
1587
|
-
for (let pair = 0;pair < Math.min(split - at, end - split); pair++) {
|
|
1588
|
-
const flags = changedChars(lines[at + pair].text.slice(1), lines[split + pair].text.slice(1));
|
|
1589
|
-
if (flags !== undefined) {
|
|
1590
|
-
changes.set(at + pair, flags[0]);
|
|
1591
|
-
changes.set(split + pair, flags[1]);
|
|
1592
|
-
}
|
|
1593
|
-
}
|
|
1594
|
-
at = Math.max(end, at + 1);
|
|
1595
|
-
}
|
|
1596
|
-
return `${lines.map((line, index) => typeof line === "string" ? line : paintContent(line, theme, changes.get(index))).join(`
|
|
68
|
+
`,temp=`${path}.${process13.pid}.tmp`;writeFileSync2(temp,kept,{mode:384}),renameSync(temp,path)}function recordUsage(entry,env=process13.env,maxBytes=MAX_USAGE_BYTES){if(!usageRecorded(env))return;try{let path=usagePath(env);mkdirSync2(dirname3(path),{recursive:!0,mode:448}),appendFileSync(path,`${JSON.stringify(entry)}
|
|
69
|
+
`,{mode:384}),trimUsage(path,maxBytes)}catch{}}var LEVEL_OPTIONS={...OUTPUT_OPTIONS,help:{type:"boolean",short:"h",description:"show this help"}},TOP_OPTIONS={...LEVEL_OPTIONS,version:{type:"boolean",short:"v",description:"print the version"},completions:{type:"string",choices:COMPLETION_SHELLS,description:"print the shell completion script"}};function printError(prefix,message,hint,cause){let colors=paint(process14.stderr),styled=takesControlCodes(process14.stderr),head=styled?`${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}`:`error: ${prefix}:`,under=(label,text,tint)=>text===void 0?"":`
|
|
70
|
+
${styled?tint(label):`${label}:`} ${text}`;console.error(`${head} ${message}${under("cause",cause,colors.dim)}${under("hint",hint,colors.yellow)}`)}function printJsonError(message,hint,cause,extra){console.error(JSON.stringify({error:message,...extra?.code===void 0?{}:{code:extra.code},...extra?.command===void 0?{}:{command:extra.command},...hint===void 0?{}:{hint},...cause===void 0?{}:{cause}}))}function wantsJson(argv){let end=argv.indexOf("--");return(end===-1?argv:argv.slice(0,end)).includes("--json")}function reportThrown(prefix,error,redact=(text)=>text,json=!1){if(error instanceof HelpShown)return 0;let code=error instanceof Exit?error.code:1,helpHint=error instanceof UsageError?`run ${prefix} --help for its options`:void 0,named=error instanceof Error&&!(error instanceof Exit)&&error.name!=="Error"?`${error.name}: ${error.message}`:void 0,cause=error instanceof Error&&error.cause instanceof Error?redact(error.cause.message):void 0;if(error instanceof Exit&&error.code===2)noteUsageError(error.message);return(json?(message,hint,causeText)=>printJsonError(message,hint,causeText,{code,command:prefix}):(message,hint,causeText)=>printError(prefix,message,hint,causeText))(redact(named??(error instanceof Error?error.message:String(error))),error instanceof Exit?error.hint??helpHint:void 0,cause),code}function packageVersion(entry=Bun.main){let resolved=entry;try{resolved=realpathSync2(entry)}catch{}for(let dir=dirname4(resolved);;dir=dirname4(dir)){try{let{version}=JSON.parse(readFileSync5(join5(dir,"package.json"),"utf8"));if(typeof version==="string")return version}catch{}if(dirname4(dir)===dir)return"0.0.0"}}async function runMain({name,version,run,redact,usage},argv=scriptArgs()){let answered=await askpassClient(argv);if(answered!==void 0)return answered;if(argv[0]===COMPLETE)return printCandidates(leafCandidates(run,argv.slice(1)));if(argv[0]===COMPLETIONS||argv[0]?.startsWith(`${COMPLETIONS}=`)===!0)return printCompletionScript(name,flagValue(argv),printError);if(argv.length===1&&(argv[0]==="--version"||argv[0]==="-v"))return console.log(version??packageVersion()),0;let code,meta=!1,started=performance.now();heading.bin={name,version:()=>version??packageVersion()};try{code=await run(argv)}catch(error){meta=error instanceof HelpShown,code=reportThrown(name,error,redact,wantsJson(argv))}finally{heading.bin=void 0}if(notifyEnd(name,code,performance.now()-started),usage!==!1&&!meta)try{recordUsage(usageEntry(name,void 0,argv,code,{ms:performance.now()-started,mode:outputMode()}))}catch{}return code}init_args();var SHELLS=new Set(["sh","bash","zsh","dash","ash","ksh","fish","csh","tcsh","nu","xonsh","elvish","pwsh","powershell"]),SCANNED_PROGRAMS=new Set(["su","runuser","flock"]),COMMAND_STRING_PROGRAMS=new Set([...SHELLS,...SCANNED_PROGRAMS]);function wrapper(short="",long=[],operands=0,runsString=!1){return{short,long,operands,runsString}}var RUNNER={...wrapper(),afterDashes:!0},WRAPPERS=new Map([["command",wrapper()],["builtin",wrapper()],["nohup",wrapper()],["setsid",wrapper()],["busybox",wrapper()],["exec",wrapper("a")],["time",wrapper("fo",["--format","--output"])],["env",wrapper("uCS",["--unset","--chdir","--split-string","--argv0"])],["sudo",wrapper("ughpCTrtUDR",["--user","--group","--host","--prompt","--close-from","--command-timeout","--role","--type","--other-user","--chdir","--chroot"])],["doas",wrapper("uC")],["timeout",wrapper("sk",["--signal","--kill-after"],1)],["nice",wrapper("n",["--adjustment"])],["ionice",wrapper("cnpPu",["--class","--classdata","--pid","--pgid","--uid"])],["stdbuf",wrapper("ioe",["--input","--output","--error"])],["chroot",wrapper("",["--userspec","--groups"],1)],["watch",wrapper("n",["--interval"],0,!0)],["flock",wrapper("wE",["--timeout","--conflict-exit-code"],1)],["parallel",wrapper("jnNSaIPlLdTsC",["--jobs","--max-args","--max-replace-args","--sshlogin","--arg-file","--delimiter","--colsep"],0,!0)],["unbuffer",wrapper()],["systemd-run",wrapper("puEMH",["--property","--unit","--description","--slice","--setenv","--machine","--host","--uid","--gid","--working-directory","--nice","--service-type"])],["xargs",wrapper("IndsEaPL",["--max-args","--max-procs","--max-chars","--delimiter","--arg-file","--eof","--max-lines","--process-slot-var"])],["strace",wrapper("abeEIoOpPsSuUX",["--trace","--output","--attach","--string-limit","--user","--env","--columns","--trace-path","--signal","--status","--summary-sort-by","--summary-columns","--const-print-style","--interruptible","--detach-on"])],["ltrace",wrapper("aeFlnopsuxX",["--output","--user","--library","--config","--align","--indent"])],["taskset",wrapper("",[],1)],["fakeroot",wrapper("lsib",["--lib","--faked"])],["sshpass",wrapper("pfdP")],["coproc",wrapper()],["proxychains",wrapper("f")],["proxychains4",wrapper("f")],["torsocks",wrapper("upaP",["--user","--pass","--address","--port"])],["chrt",wrapper("TPD",["--sched-runtime","--sched-period","--sched-deadline"],1)],["unshare",wrapper("SGRw",["--setuid","--setgid","--root","--wd","--map-user","--map-group","--map-users","--map-groups","--propagation","--setgroups"])],["nsenter",wrapper("tSG",["--target","--setuid","--setgid"])],["out",RUNNER],["slot",RUNNER],["waitfor",RUNNER],["base",RUNNER]]);init_style();init_config();init_text();init_folders();init_format();init_args();init_args();init_mode();init_style();init_text();var{Glob}=globalThis.Bun;var SESSION_FILES=new Glob("*.json"),ACCOUNT_DIRS=new Glob("*/sessions");init_style();init_text();init_theme();init_user_config();init_args();init_input();init_style();init_user_config();import{basename,dirname as dirname5,join as join6,relative,sep}from"path";var PARENT=`..${sep}`;var WORD_START=/[a-z_$]/i,WORD=/^[\w$-]+/,NUMBER=/^(?:0x[\da-f_]+|\d[\d_]*(?:\.\d[\d_]*)?(?:e[+-]?\d+)?)/i,PREVIOUS_WORD=/[\w$]$/,AFTER_KEY=/^\s*:/,YAML_KEY=/^(\s*(?:- )?)([\w.\-/]+)(?=:(?:\s|$))/,SETTING_KEY=/^(\s*)([\w.-]+)(?=\s*[=:])/,SECTION=/^\s*\[.*\]\s*$/,WHITESPACE=/\s/,FLAG=/^--?[a-z][\w-]*/i,COMMAND_END=/[|&;(]\s*$/,PROMPT=/^\s*(?:[$>]\s*)?$/,DIGIT=/\d/,TRAILING_NEWLINE=/\n$/,LEADING_DOT=/^\./,TRIPLE_QUOTES=['"""',"'''"];function words(list){return new Set(list.split(" "))}var SLASHES={line:["//"],block:["/*","*/"]},HASH={line:["#"]},CONSTANTS="true false null undefined NaN Infinity",C_LIKE="if else for while do switch case default break continue return throw try catch finally new delete typeof instanceof in of void yield await async static public private protected readonly abstract extends implements super this",SCRIPT=`${C_LIKE} const let var function class import export from as type interface enum namespace declare satisfies keyof is get set ${CONSTANTS}`,LANGUAGES={script:{...SLASHES,quotes:"\"'`",keywords:words(SCRIPT)},json:{line:[],quotes:'"',keywords:words("true false null"),quotedKeys:!0},jsonc:{...SLASHES,quotes:'"',keywords:words("true false null"),quotedKeys:!0},python:{...HASH,quotes:`"'`,keywords:words("def class return if elif else for while in not and or is import from as with try except finally raise pass break continue lambda yield async await global nonlocal del assert None True False self")},shell:{...HASH,commands:!0,quotes:"\"'`",keywords:words("if then else elif fi for while until do done case esac in function return exit local export set unset source alias echo cd end switch begin and or not")},yaml:{...HASH,quotes:`"'`,keywords:words("true false null yes no"),key:YAML_KEY,quotedKeys:!0},toml:{...HASH,quotes:`"'`,keywords:words("true false"),key:SETTING_KEY,section:SECTION},ini:{line:["#",";"],quotes:`"'`,keywords:words("true false yes no on off"),key:SETTING_KEY,section:SECTION},css:{line:[],block:["/*","*/"],quotes:`"'`,keywords:words("important inherit initial unset auto none")},html:{line:[],block:["<!--","-->"],quotes:`"'`,keywords:words("")},sql:{line:["--"],block:["/*","*/"],quotes:"\"'`",caseInsensitive:!0,keywords:words("select from where and or not insert into values update set delete create alter drop table index view join left right inner outer full on group by order having limit offset as distinct union all null is in like between case when then else end primary key foreign references default unique with returning true false")},rust:{...SLASHES,quotes:'"',keywords:words("fn let mut const static struct enum impl trait pub use mod crate self super if else match for while loop break continue return as in ref move async await dyn where type unsafe true false None Some Ok Err")},go:{...SLASHES,quotes:"\"'`",keywords:words("func var const type struct interface map chan package import if else for range switch case default break continue return go defer select fallthrough goto nil true false")},php:{...SLASHES,line:["//","#"],quotes:`"'`,keywords:words(`${C_LIKE} function class interface trait namespace use public private protected static final echo array fn match list isset empty require include require_once include_once true false null`)},java:{...SLASHES,quotes:`"'`,keywords:words(`${C_LIKE} class interface enum package import final void int long double float boolean char byte short true false null var record`)},c:{...SLASHES,quotes:`"'`,keywords:words(`${C_LIKE} struct union typedef enum const volatile extern sizeof void int long double float char short unsigned signed auto register inline static include define ifdef ifndef endif pragma true false NULL nullptr class template typename namespace using bool`)},ruby:{...HASH,quotes:`"'`,keywords:words("def end class module if elsif else unless while until for in do begin rescue ensure return yield self nil true false and or not require require_relative include extend attr_accessor attr_reader puts then case when")},lua:{line:["--"],quotes:`"'`,keywords:words("function end if then else elseif for while do repeat until return local break in and or not nil true false")},dockerfile:{...HASH,quotes:`"'`,caseInsensitive:!0,keywords:words("from run cmd label expose env add copy entrypoint volume user workdir arg onbuild stopsignal healthcheck shell as")},makefile:{...HASH,quotes:`"'`,keywords:words("ifeq ifneq ifdef ifndef else endif include define endef export")}},ALIASES={script:["ts","tsx","mts","cts","js","jsx","mjs","cjs","typescript","javascript","vue","svelte"],json:["json","jsonl","ndjson"],jsonc:["jsonc","json5"],python:["py","python"],shell:["sh","bash","zsh","fish","shell","console"],yaml:["yml","yaml"],toml:["toml"],ini:["ini","conf","cfg","properties","editorconfig"],css:["css","scss","less"],html:["html","htm","xml","svg"],sql:["sql"],rust:["rs","rust"],go:["go","golang"],php:["php"],java:["java","kt","kts","cs","swift","dart","scala"],c:["c","h","cpp","cc","hpp","cxx"],ruby:["rb","ruby"],lua:["lua"],dockerfile:["dockerfile","containerfile"],makefile:["makefile","mk","just","justfile"]},BY_NAME=new Map(Object.entries(ALIASES).flatMap(([name,aliases])=>aliases.map((alias)=>[alias,name]))),EXTENSION=/\.([^./]+)$/,BASENAME=/[^/]*$/;function languageOf(nameOrPath){let base=(BASENAME.exec(nameOrPath)?.[0]??"").toLowerCase(),extension=EXTENSION.exec(base)?.[1];return BY_NAME.get(extension??base)??BY_NAME.get(base.replace(LEADING_DOT,""))}function paintLines(text,paint){return text.split(`
|
|
71
|
+
`).map((line)=>line===""?line:paint(line)).join(`
|
|
72
|
+
`)}function stringEnd(source,start,quote){let triple=TRIPLE_QUOTES.find((each)=>source.startsWith(each,start)),multiline=quote==="`"||triple!==void 0,closer=triple??quote,at=start+closer.length;while(at<source.length){let char=source.charAt(at);if(char==="\\")at+=2;else if(source.startsWith(closer,at))return at+closer.length;else if(char===`
|
|
73
|
+
`&&!multiline)return at;else at++}return source.length}function lineLead(line,language,theme){if(language.section?.test(line)===!0)return{done:theme.heading(line),rest:""};let match=language.key?.exec(line);if(match===null||match===void 0)return{done:"",rest:line};return{done:`${match[1]??""}${theme.accent(match[2]??"")}`,rest:line.slice(match[0].length)}}function highlight(source,name,theme){let language=LANGUAGES[name],text=source.replaceAll(`\r
|
|
74
|
+
`,`
|
|
75
|
+
`),out="",at=0;while(at<text.length){if((at===0||text.charAt(at-1)===`
|
|
76
|
+
`)&&(language.key!==void 0||language.section!==void 0)){let lineEnd=text.indexOf(`
|
|
77
|
+
`,at),line=text.slice(at,lineEnd===-1?text.length:lineEnd),{done,rest}=lineLead(line,language,theme);if(done!==""){out+=done,at+=line.length-rest.length;continue}}let char=text.charAt(at);if(language.line.find((each)=>text.startsWith(each,at))!==void 0){let end=text.indexOf(`
|
|
78
|
+
`,at),stop=end===-1?text.length:end;out+=paintLines(text.slice(at,stop),theme.dim),at=stop}else if(language.block!==void 0&&text.startsWith(language.block[0],at)){let end=text.indexOf(language.block[1],at+language.block[0].length),stop=end===-1?text.length:end+language.block[1].length;out+=paintLines(text.slice(at,stop),theme.dim),at=stop}else if(language.quotes.includes(char)){let stop=stringEnd(text,at,char),isKey=language.quotedKeys===!0&&AFTER_KEY.test(text.slice(stop,!text.includes(`
|
|
79
|
+
`,stop)?void 0:text.indexOf(`
|
|
80
|
+
`,stop)));out+=paintLines(text.slice(at,stop),isKey?theme.accent:theme.string),at=stop}else if(DIGIT.test(char)&&!PREVIOUS_WORD.test(text.slice(Math.max(0,at-1),at))){let number=NUMBER.exec(text.slice(at))?.[0]??char;out+=theme.number(number),at+=number.length}else if(language.commands===!0&&char==="-"&&(at===0||WHITESPACE.test(text.charAt(at-1)))&&FLAG.test(text.slice(at))){let flag=FLAG.exec(text.slice(at))?.[0]??char;out+=theme.number(flag),at+=flag.length}else if(WORD_START.test(char)){let word=WORD.exec(text.slice(at))?.[0]??char,before=text.slice(text.lastIndexOf(`
|
|
81
|
+
`,at-1)+1,at),command=language.commands===!0&&(PROMPT.test(before)||COMMAND_END.test(before)),lookup=language.caseInsensitive===!0?word.toLowerCase():word;if(language.keywords.has(lookup))out+=theme.keyword(word);else out+=command&&!word.startsWith("$")?theme.accent(word):word;at+=word.length}else out+=char,at++}return out}function renderCode(source,name,theme,lineNumbers,startLine=1){let text=escapeControls(source.replaceAll(`\r
|
|
82
|
+
`,`
|
|
83
|
+
`)).replace(TRAILING_NEWLINE,""),shown=name===void 0?text:highlight(text,name,theme);if(!lineNumbers)return`${shown}
|
|
84
|
+
`;let lines=shown.split(`
|
|
85
|
+
`),digits=String(startLine+lines.length-1).length;return`${lines.map((line,index)=>`${theme.dim(`${String(startLine+index).padStart(digits)} \u2502`)} ${line}`.trimEnd()).join(`
|
|
1597
86
|
`)}
|
|
1598
|
-
|
|
1599
|
-
}
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
var BODY
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
return `${FIRST}${first}${REST}${rest}${BODY}${text}`;
|
|
1623
|
-
}
|
|
1624
|
-
function trimmed(block) {
|
|
1625
|
-
return block.replace(TRAILING_BREAKS, "");
|
|
1626
|
-
}
|
|
1627
|
-
function indent(block, first, rest) {
|
|
1628
|
-
return block.split(`
|
|
1629
|
-
`).map((line, index) => {
|
|
1630
|
-
const lead = index === 0 ? first : rest;
|
|
1631
|
-
if (!line.startsWith(FIRST))
|
|
1632
|
-
return `${lead}${line}`;
|
|
1633
|
-
const middle = line.indexOf(REST);
|
|
1634
|
-
const body = line.indexOf(BODY);
|
|
1635
|
-
return `${FIRST}${lead}${line.slice(1, middle)}${REST}${rest}${line.slice(middle + 1, body)}${BODY}${line.slice(body + 1)}`;
|
|
1636
|
-
}).join(`
|
|
1637
|
-
`);
|
|
1638
|
-
}
|
|
1639
|
-
function finish(block, width) {
|
|
1640
|
-
return block.split(`
|
|
1641
|
-
`).flatMap((line) => {
|
|
1642
|
-
if (!line.startsWith(FIRST))
|
|
1643
|
-
return [line.trimEnd()];
|
|
1644
|
-
const middle = line.indexOf(REST);
|
|
1645
|
-
const body = line.indexOf(BODY);
|
|
1646
|
-
const first = line.slice(1, middle);
|
|
1647
|
-
const rest = line.slice(middle + 1, body);
|
|
1648
|
-
const room = Math.max(width - Math.max(textWidth(first), textWidth(rest)), MIN_ROOM);
|
|
1649
|
-
return Bun.wrapAnsi(line.slice(body + 1), room).split(`
|
|
1650
|
-
`).map((wrapped, index) => `${index === 0 ? first : rest}${wrapped}`.trimEnd());
|
|
1651
|
-
}).join(`
|
|
1652
|
-
`);
|
|
1653
|
-
}
|
|
1654
|
-
function columnWidths(rows, width) {
|
|
1655
|
-
const longest = rows[0]?.map((_, column) => Math.max(...rows.map((row) => textWidth(row[column] ?? "")))) ?? [];
|
|
1656
|
-
const gaps = COLUMN_GAP * Math.max(0, longest.length - 1);
|
|
1657
|
-
const sum = (list) => list.reduce((total, each) => total + each, 0);
|
|
1658
|
-
if (sum(longest) + gaps <= width)
|
|
1659
|
-
return longest;
|
|
1660
|
-
const typical = longest.map((most, column) => Math.min(most, Math.max(MIN_COLUMN, Math.ceil(TYPICAL * sum(rows.map((row) => textWidth(row[column] ?? ""))) / rows.length))));
|
|
1661
|
-
const widths = [...typical];
|
|
1662
|
-
const room = width - gaps - sum(typical);
|
|
1663
|
-
const wanting = longest.map((most, column) => most - typical[column]);
|
|
1664
|
-
if (room > 0 && sum(wanting) > 0) {
|
|
1665
|
-
for (const [column, want] of wanting.entries())
|
|
1666
|
-
widths[column] += Math.min(want, Math.floor(room * want / sum(wanting)));
|
|
1667
|
-
const left = width - gaps - sum(widths);
|
|
1668
|
-
const hungriest = wanting.indexOf(Math.max(...wanting));
|
|
1669
|
-
widths[hungriest] += Math.max(0, Math.min(left, longest[hungriest] - widths[hungriest]));
|
|
1670
|
-
}
|
|
1671
|
-
const total = () => sum(widths) + gaps;
|
|
1672
|
-
while (total() > width) {
|
|
1673
|
-
const widest = widths.indexOf(Math.max(...widths));
|
|
1674
|
-
if ((widths[widest] ?? 0) <= MIN_COLUMN)
|
|
1675
|
-
break;
|
|
1676
|
-
widths[widest]--;
|
|
1677
|
-
}
|
|
1678
|
-
return widths;
|
|
1679
|
-
}
|
|
1680
|
-
function renderTable(rows, aligns, width, theme) {
|
|
1681
|
-
const widths = columnWidths(rows, width);
|
|
1682
|
-
const wrapped = rows.map((row) => widths.map((each, column) => Bun.wrapAnsi(row[column] ?? "", each, { hard: true }).split(`
|
|
1683
|
-
`)));
|
|
1684
|
-
const spaced = wrapped.some((cells) => cells.some((cell) => cell.length > 1));
|
|
1685
|
-
const lines = rows.flatMap((_, index) => {
|
|
1686
|
-
const cells = wrapped[index];
|
|
1687
|
-
const height = Math.max(...cells.map((cell) => cell.length));
|
|
1688
|
-
const drawn = Array.from({ length: height }, (_, at) => cells.map((cell, column) => {
|
|
1689
|
-
const text = cell[at] ?? "";
|
|
1690
|
-
const gap = " ".repeat(Math.max(0, (widths[column] ?? 0) - textWidth(text)));
|
|
1691
|
-
const aligned = aligns[column] === "right" ? `${gap}${text}` : `${text}${gap}`;
|
|
1692
|
-
return index === 0 ? theme.heading(aligned) : aligned;
|
|
1693
|
-
}).join(" ".repeat(COLUMN_GAP)).trimEnd());
|
|
1694
|
-
if (index === 0)
|
|
1695
|
-
return [...drawn, theme.dim("\u2500".repeat(Math.min(width, widths.reduce((sum, each) => sum + each, 0) + COLUMN_GAP * Math.max(0, widths.length - 1))))];
|
|
1696
|
-
return spaced && index > 1 ? ["", ...drawn] : drawn;
|
|
1697
|
-
});
|
|
1698
|
-
return lines.join(`
|
|
1699
|
-
`);
|
|
1700
|
-
}
|
|
1701
|
-
function printable(source) {
|
|
1702
|
-
return stripControls(stripAnsi(source.replaceAll(`\r
|
|
1703
|
-
`, `
|
|
1704
|
-
`)));
|
|
1705
|
-
}
|
|
1706
|
-
function renderMarkdown(source, { theme, width }) {
|
|
1707
|
-
const quote = [`${theme.shade("\u275D", 0)} `, " "];
|
|
1708
|
-
let aligns = [];
|
|
1709
|
-
const rendered = Bun.markdown.render(printable(source), {
|
|
1710
|
-
heading: (children, { level }) => block(`${reflow(theme.shade(theme.bold(children), HEADING_SHADES[Math.min(level, HEADING_SHADES.length) - 1] ?? 1), theme.dim(`${"#".repeat(level)} `), " ".repeat(level + 1))}
|
|
1711
|
-
|
|
1712
|
-
`),
|
|
1713
|
-
paragraph: (children) => block(`${reflow(children.replaceAll(`
|
|
1714
|
-
`, " "))}
|
|
1715
|
-
|
|
1716
|
-
`),
|
|
1717
|
-
strong: (text) => theme.shade(theme.bold(text), 0),
|
|
1718
|
-
emphasis: theme.italic,
|
|
1719
|
-
strikethrough: theme.strike,
|
|
1720
|
-
codespan: (text) => `${theme.dim("`")}${theme.accent(text)}${theme.dim("`")}`,
|
|
1721
|
-
link: (children, { href }) => theme.link(children, href),
|
|
1722
|
-
image: (children, { src }) => theme.dim(`[image: ${children === "" ? src : children}]`),
|
|
1723
|
-
html: (children) => block(`${theme.dim(trimmed(children))}
|
|
1724
|
-
|
|
1725
|
-
`),
|
|
1726
|
-
code: (children, meta) => {
|
|
1727
|
-
const language = languageOf(meta?.language ?? "");
|
|
1728
|
-
const body = trimmed(children);
|
|
1729
|
-
const lines = (language === undefined ? body : highlight(body, language, theme)).split(`
|
|
1730
|
-
`);
|
|
1731
|
-
const rule = Math.min(width, MAX_CODE_RULE, Math.max(MIN_CODE_RULE, ...lines.map((line) => textWidth(line))));
|
|
1732
|
-
const label = meta?.language === undefined || meta.language === "" ? "" : `${meta.language} `;
|
|
1733
|
-
return block(`${theme.dim(`${label}${"\u2500".repeat(Math.max(0, rule - textWidth(label)))}`)}
|
|
87
|
+
`}var TRAILING_NEWLINE2=/\n$/,HUNK=/^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@(.*)$/,FILE_HEADER=/^diff --git a\/(.*) b\/(.*)$/,NEW_FILE=/^\+\+\+ (?:b\/)?([^\t]*)/,COMMIT=/^(commit )([0-9a-f]{7,40})(.*)$/,HUNK_LINE=new Set([" ","+","-","\\"]),MARKERS=/^(?:--- |\+\+\+ )/,GIT_COLOR=/\x1B\[[\d;]*m/g,META=/^(?:index |old mode |new mode |deleted file mode |new file mode |similarity index |dissimilarity index |rename from |rename to |copy from |copy to |Binary files |GIT binary patch)/,COMMIT_META=/^(?:Author|Date|Merge|AuthorDate|Commit|CommitDate):/,TOKEN=/\w+|\s+|[^\w\s]/g,WORD_CHAR=/\w/,ESCAPE=/\x1B\[([0-9;]*)m/g,CLOSING=new Set(["0","22","23","24","27","29","39","49"]),MAX_TOKENS=300;function looksLikeDiff(text){let first=stripAnsi(text).split(`
|
|
88
|
+
`).find((line)=>line.trim()!=="")??"";return first.startsWith("diff --git ")||first.startsWith("--- ")||first.startsWith("@@ ")||first.startsWith("Index: ")||COMMIT.test(first)}function changedChars(a,b){let left=a.match(TOKEN)??[],right=b.match(TOKEN)??[];if(left.length>MAX_TOKENS||right.length>MAX_TOKENS)return;let common=Array.from({length:left.length+1},()=>Array.from({length:right.length+1}).fill(0));for(let i=left.length-1;i>=0;i--)for(let j=right.length-1;j>=0;j--)common[i][j]=left[i]===right[j]?common[i+1][j+1]+1:Math.max(common[i+1][j],common[i][j+1]);let flags=(tokens)=>tokens.flatMap((token)=>Array.from({length:token.length}).fill(!0)),changedLeft=flags(left),changedRight=flags(right),shared=!1,i=0,j=0,at=0,to=0;while(i<left.length&&j<right.length)if(left[i]===right[j])shared||=WORD_CHAR.test(left[i]),changedLeft.fill(!1,at,at+left[i].length),changedRight.fill(!1,to,to+right[j].length),at+=left[i].length,to+=right[j].length,i++,j++;else if(common[i+1][j]>=common[i][j+1])at+=left[i++].length;else to+=right[j++].length;return shared?[changedLeft,changedRight]:void 0}function paintContent({mark,text,language},theme,changed){let tone=mark==="+"?theme.added:theme.removed,code=text.slice(1),source=language===void 0?code:highlight(code,language,theme),cells=[{char:mark,style:"",changed:!1}],style="",from=0;for(let escape of source.matchAll(ESCAPE)){for(let char of source.slice(from,escape.index).split(""))cells.push({char,style,changed:changed?.[cells.length-1]??!1});style=CLOSING.has(escape[1])?"":style+escape[0],from=escape.index+escape[0].length}for(let char of source.slice(from).split(""))cells.push({char,style,changed:changed?.[cells.length-1]??!1});let out="";for(let at=0;at<cells.length;){let end=at+1;while(end<cells.length&&cells[end].style===cells[at].style&&cells[end].changed===cells[at].changed)end++;let run=cells.slice(at,end).map((cell)=>cell.char).join(""),shown=cells[at].style===""?tone(run):`${cells[at].style}${run}\x1B[0m`;out+=cells[at].changed?theme.changed(shown):shown,at=end}return out}function renderDiff(text,theme){let oldLeft=0,newLeft=0,language,lines=escapeControls(text.replace(GIT_COLOR,"").replaceAll(`\r
|
|
89
|
+
`,`
|
|
90
|
+
`)).replace(TRAILING_NEWLINE2,"").split(`
|
|
91
|
+
`).map((line)=>{if((oldLeft>0||newLeft>0)&&line!==""&&!HUNK_LINE.has(line[0]??""))oldLeft=newLeft=0;if(oldLeft>0||newLeft>0){let mark=line[0];if(mark==="+")return newLeft--,{mark,text:line,language};if(mark==="-")return oldLeft--,{mark,text:line,language};if(mark==="\\")return theme.dim(line);return oldLeft--,newLeft--,line}let hunk=HUNK.exec(line);if(hunk!==null)return oldLeft=Number(hunk[1]??1),newLeft=Number(hunk[2]??1),`${theme.accent(line.slice(0,line.length-(hunk[3]??"").length))}${theme.dim(hunk[3]??"")}`;let file=FILE_HEADER.exec(line);if(file!==null)return language=languageOf(file[2]??""),`${theme.dim("diff")} ${theme.bold(theme.path(file[2]??""))}`;let commit=COMMIT.exec(line);if(commit!==null)return`${theme.dim(commit[1]??"")}${theme.id(commit[2]??"")}${theme.dim(commit[3]??"")}`;let target=NEW_FILE.exec(line)?.[1];if(target!==void 0&&target!=="/dev/null")language=languageOf(target);return MARKERS.test(line)||META.test(line)||COMMIT_META.test(line)?theme.dim(line):line}),changes=new Map;for(let at=0;at<lines.length;){let first=lines[at];if(!(typeof first==="object"&&first.mark==="-")){at++;continue}let split=at;while(typeof lines[split]==="object"&&lines[split].mark==="-")split++;let end=split;while(typeof lines[end]==="object"&&lines[end].mark==="+")end++;for(let pair=0;pair<Math.min(split-at,end-split);pair++){let flags=changedChars(lines[at+pair].text.slice(1),lines[split+pair].text.slice(1));if(flags!==void 0)changes.set(at+pair,flags[0]),changes.set(split+pair,flags[1])}at=Math.max(end,at+1)}return`${lines.map((line,index)=>typeof line==="string"?line:paintContent(line,theme,changes.get(index))).join(`
|
|
92
|
+
`)}
|
|
93
|
+
`}var FIRST="\x01",REST="\x02",BODY="\x03",NESTED="\x05",CELL="\x06",ROW="\x07",BLOCK="\b",MAX_RULE=60,MAX_CODE_RULE=12,MIN_CODE_RULE=8,HEADING_SHADES=[0,0.35,0.7,1],MIN_ROOM=20,MIN_COLUMN=8,TYPICAL=1.4,COLUMN_GAP=2,TRAILING_BREAKS=/\n+$/;function block(text){return`${BLOCK}${text}`}function reflow(text,first="",rest=""){return`${FIRST}${first}${REST}${rest}${BODY}${text}`}function trimmed(block){return block.replace(TRAILING_BREAKS,"")}function indent(block,first,rest){return block.split(`
|
|
94
|
+
`).map((line,index)=>{let lead=index===0?first:rest;if(!line.startsWith(FIRST))return`${lead}${line}`;let middle=line.indexOf(REST),body=line.indexOf(BODY);return`${FIRST}${lead}${line.slice(1,middle)}${REST}${rest}${line.slice(middle+1,body)}${BODY}${line.slice(body+1)}`}).join(`
|
|
95
|
+
`)}function finish(block,width){return block.split(`
|
|
96
|
+
`).flatMap((line)=>{if(!line.startsWith(FIRST))return[line.trimEnd()];let middle=line.indexOf(REST),body=line.indexOf(BODY),first=line.slice(1,middle),rest=line.slice(middle+1,body),room=Math.max(width-Math.max(textWidth(first),textWidth(rest)),MIN_ROOM);return Bun.wrapAnsi(line.slice(body+1),room).split(`
|
|
97
|
+
`).map((wrapped,index)=>`${index===0?first:rest}${wrapped}`.trimEnd())}).join(`
|
|
98
|
+
`)}function columnWidths(rows,width){let longest=rows[0]?.map((_,column)=>Math.max(...rows.map((row)=>textWidth(row[column]??""))))??[],gaps=COLUMN_GAP*Math.max(0,longest.length-1),sum=(list)=>list.reduce((total,each)=>total+each,0);if(sum(longest)+gaps<=width)return longest;let typical=longest.map((most,column)=>Math.min(most,Math.max(MIN_COLUMN,Math.ceil(TYPICAL*sum(rows.map((row)=>textWidth(row[column]??"")))/rows.length)))),widths=[...typical],room=width-gaps-sum(typical),wanting=longest.map((most,column)=>most-typical[column]);if(room>0&&sum(wanting)>0){for(let[column,want]of wanting.entries())widths[column]+=Math.min(want,Math.floor(room*want/sum(wanting)));let left=width-gaps-sum(widths),hungriest=wanting.indexOf(Math.max(...wanting));widths[hungriest]+=Math.max(0,Math.min(left,longest[hungriest]-widths[hungriest]))}let total=()=>sum(widths)+gaps;while(total()>width){let widest=widths.indexOf(Math.max(...widths));if((widths[widest]??0)<=MIN_COLUMN)break;widths[widest]--}return widths}function renderTable(rows,aligns,width,theme){let widths=columnWidths(rows,width),wrapped=rows.map((row)=>widths.map((each,column)=>Bun.wrapAnsi(row[column]??"",each,{hard:!0}).split(`
|
|
99
|
+
`))),spaced=wrapped.some((cells)=>cells.some((cell)=>cell.length>1));return rows.flatMap((_,index)=>{let cells=wrapped[index],height=Math.max(...cells.map((cell)=>cell.length)),drawn=Array.from({length:height},(_,at)=>cells.map((cell,column)=>{let text=cell[at]??"",gap=" ".repeat(Math.max(0,(widths[column]??0)-textWidth(text))),aligned=aligns[column]==="right"?`${gap}${text}`:`${text}${gap}`;return index===0?theme.heading(aligned):aligned}).join(" ".repeat(COLUMN_GAP)).trimEnd());if(index===0)return[...drawn,theme.dim("\u2500".repeat(Math.min(width,widths.reduce((sum,each)=>sum+each,0)+COLUMN_GAP*Math.max(0,widths.length-1))))];return spaced&&index>1?["",...drawn]:drawn}).join(`
|
|
100
|
+
`)}function printable(source){return stripControls(stripAnsi(source.replaceAll(`\r
|
|
101
|
+
`,`
|
|
102
|
+
`)))}function renderMarkdown(source,{theme,width}){let quote=[`${theme.shade("\u275D",0)} `," "],aligns=[],rendered=Bun.markdown.render(printable(source),{heading:(children,{level})=>block(`${reflow(theme.shade(theme.bold(children),HEADING_SHADES[Math.min(level,HEADING_SHADES.length)-1]??1),theme.dim(`${"#".repeat(level)} `)," ".repeat(level+1))}
|
|
103
|
+
|
|
104
|
+
`),paragraph:(children)=>block(`${reflow(children.replaceAll(`
|
|
105
|
+
`," "))}
|
|
106
|
+
|
|
107
|
+
`),strong:(text)=>theme.shade(theme.bold(text),0),emphasis:theme.italic,strikethrough:theme.strike,codespan:(text)=>`${theme.dim("`")}${theme.accent(text)}${theme.dim("`")}`,link:(children,{href})=>theme.link(children,href),image:(children,{src})=>theme.dim(`[image: ${children===""?src:children}]`),html:(children)=>block(`${theme.dim(trimmed(children))}
|
|
108
|
+
|
|
109
|
+
`),code:(children,meta)=>{let language=languageOf(meta?.language??""),body=trimmed(children),lines=(language===void 0?body:highlight(body,language,theme)).split(`
|
|
110
|
+
`),rule=Math.min(width,MAX_CODE_RULE,Math.max(MIN_CODE_RULE,...lines.map((line)=>textWidth(line)))),label=meta?.language===void 0||meta.language===""?"":`${meta.language} `;return block(`${theme.dim(`${label}${"\u2500".repeat(Math.max(0,rule-textWidth(label)))}`)}
|
|
1734
111
|
${lines.join(`
|
|
1735
112
|
`)}
|
|
1736
113
|
${theme.dim("\u2500".repeat(rule))}
|
|
1737
114
|
|
|
1738
|
-
`)
|
|
1739
|
-
},
|
|
1740
|
-
blockquote: (children) => block(`${indent(trimmed(children.replaceAll(BLOCK, "")), quote[0], quote[1])}
|
|
115
|
+
`)},blockquote:(children)=>block(`${indent(trimmed(children.replaceAll(BLOCK,"")),quote[0],quote[1])}
|
|
1741
116
|
|
|
1742
|
-
`),
|
|
1743
|
-
hr: () => block(`${theme.dim("\u2500".repeat(Math.min(width, MAX_RULE)))}
|
|
117
|
+
`),hr:()=>block(`${theme.dim("\u2500".repeat(Math.min(width,MAX_RULE)))}
|
|
1744
118
|
|
|
1745
|
-
`),
|
|
1746
|
-
list: (children, { depth }) => depth > 0 ? `${NESTED}${trimmed(children)}
|
|
119
|
+
`),list:(children,{depth})=>depth>0?`${NESTED}${trimmed(children)}
|
|
1747
120
|
|
|
1748
|
-
|
|
121
|
+
`:block(`${trimmed(children)}
|
|
1749
122
|
|
|
1750
|
-
`),
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
const blocks = blocksAt === -1 ? "" : trimmed(head.slice(blocksAt).replaceAll(BLOCK, ""));
|
|
1756
|
-
const text = [inline === "" ? "" : reflow(inline.replaceAll(`
|
|
1757
|
-
`, " ")), blocks].filter((part) => part !== "").join(`
|
|
1758
|
-
`) || reflow("");
|
|
1759
|
-
let marker = theme.dim("-");
|
|
1760
|
-
if (checked !== undefined)
|
|
1761
|
-
marker = checked ? theme.added("\u2713") : theme.dim("\u25CB");
|
|
1762
|
-
else if (ordered)
|
|
1763
|
-
marker = theme.dim(`${(start ?? 1) + index}.`);
|
|
1764
|
-
return `${indent([text, ...nested.map(trimmed)].join(`
|
|
1765
|
-
`), `${marker} `, " ".repeat(textWidth(marker) + 1))}
|
|
1766
|
-
`;
|
|
1767
|
-
},
|
|
1768
|
-
th: (children, meta) => {
|
|
1769
|
-
aligns.push(meta?.align === "right" ? "right" : "left");
|
|
1770
|
-
return `${children}${CELL}`;
|
|
1771
|
-
},
|
|
1772
|
-
td: (children) => `${children}${CELL}`,
|
|
1773
|
-
tr: (children) => `${children}${ROW}`,
|
|
1774
|
-
table: (children) => {
|
|
1775
|
-
const rows = children.split(ROW).filter((row) => row !== "").map((row) => row.split(CELL).slice(0, -1));
|
|
1776
|
-
const drawn = renderTable(rows, aligns, width, theme);
|
|
1777
|
-
aligns = [];
|
|
1778
|
-
return block(`${drawn}
|
|
123
|
+
`),listItem:(children,{index,ordered,start,checked})=>{let[head="",...nested]=children.split(NESTED),blocksAt=head.indexOf(BLOCK),inline=(blocksAt===-1?head:head.slice(0,blocksAt)).trim(),blocks=blocksAt===-1?"":trimmed(head.slice(blocksAt).replaceAll(BLOCK,"")),text=[inline===""?"":reflow(inline.replaceAll(`
|
|
124
|
+
`," ")),blocks].filter((part)=>part!=="").join(`
|
|
125
|
+
`)||reflow(""),marker=theme.dim("-");if(checked!==void 0)marker=checked?theme.added("\u2713"):theme.dim("\u25CB");else if(ordered)marker=theme.dim(`${(start??1)+index}.`);return`${indent([text,...nested.map(trimmed)].join(`
|
|
126
|
+
`),`${marker} `," ".repeat(textWidth(marker)+1))}
|
|
127
|
+
`},th:(children,meta)=>(aligns.push(meta?.align==="right"?"right":"left"),`${children}${CELL}`),td:(children)=>`${children}${CELL}`,tr:(children)=>`${children}${ROW}`,table:(children)=>{let rows=children.split(ROW).filter((row)=>row!=="").map((row)=>row.split(CELL).slice(0,-1)),drawn=renderTable(rows,aligns,width,theme);return aligns=[],block(`${drawn}
|
|
1779
128
|
|
|
1780
|
-
`);
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
}
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
const colors = paint(stream, env);
|
|
1791
|
-
const accent = role("accent", stream, env);
|
|
1792
|
-
const path = role("path", stream, env);
|
|
1793
|
-
return {
|
|
1794
|
-
heading: (text) => accent(colors.bold(text)),
|
|
1795
|
-
code: role("id", stream, env),
|
|
1796
|
-
path,
|
|
1797
|
-
id: role("id", stream, env),
|
|
1798
|
-
dim: role("label", stream, env),
|
|
1799
|
-
bold: colors.bold,
|
|
1800
|
-
italic: colors.italic,
|
|
1801
|
-
strike: colors.strikethrough,
|
|
1802
|
-
changed: colors.inverse,
|
|
1803
|
-
added: colors.green,
|
|
1804
|
-
removed: colors.red,
|
|
1805
|
-
accent,
|
|
1806
|
-
keyword: colors.magenta,
|
|
1807
|
-
string: colors.green,
|
|
1808
|
-
number: colors.yellow,
|
|
1809
|
-
link: (text, url) => path(colors.underline(link(text, url, stream, env))),
|
|
1810
|
-
shade: (text, ratio) => takesControlCodes(stream, env) ? tinted(colors, gradientAt(activeTheme().theme, ratio) ?? activeTheme().theme.colors.accent, env)(text) : text
|
|
1811
|
-
};
|
|
1812
|
-
}
|
|
1813
|
-
|
|
1814
|
-
// src/view.ts
|
|
1815
|
-
var DEFAULT_WIDTH = 80;
|
|
1816
|
-
var MARKDOWN_FILE = /\.(?:md|markdown|mdx)$/i;
|
|
1817
|
-
var DIFF_FILE = /\.(?:diff|patch)$/i;
|
|
1818
|
-
var USAGE = `view [options] [file]: shows a markdown file, a source file or a git diff in the colours of the other @kaynooo CLIs
|
|
1819
|
-
|
|
1820
|
-
A file, or what is piped on stdin (or - for stdin). A source file is highlighted behind line numbers by its extension or --lang, a diff, a \`git log -p\` or a \`git show\` is recognised by its first line or a .diff or .patch name, and anything else is markdown; --diff and --markdown force one.
|
|
1821
|
-
Lines wrap to the terminal width and a long output on a terminal goes through $PAGER, unless --no-pager. No colour with NO_COLOR, a pipe or --plain. Control characters of the text, escape sequences included, show as cat -v writes them (^[) in code and diffs and are dropped from markdown, --json too.`;
|
|
1822
|
-
var EXITS = [[0, "it showed the text"], [1, "there is nothing to show"], [2, "a usage error or a file that is missing"]];
|
|
1823
|
-
var OPTIONS = {
|
|
1824
|
-
diff: { type: "boolean", description: "show the text as a diff" },
|
|
1825
|
-
markdown: { type: "boolean", description: "show the text as markdown" },
|
|
1826
|
-
lang: { type: "string", short: "l", description: "show the text as code in this language (ts, json, yaml, sh...)" },
|
|
1827
|
-
lines: { type: "boolean", description: "number the lines of code (--no-lines turns it off; on a terminal by default)" },
|
|
1828
|
-
width: { type: "string", short: "w", description: "columns to wrap to, instead of the terminal's" },
|
|
1829
|
-
pager: { type: "boolean", description: "page a long output on a terminal (--no-pager turns it off)" },
|
|
1830
|
-
json: jsonOption("{kind: code, diff or markdown, language, text}, the text rendered without colour")
|
|
1831
|
-
};
|
|
1832
|
-
function columnsOf(variable) {
|
|
1833
|
-
const columns = Number(variable);
|
|
1834
|
-
return Number.isInteger(columns) && columns >= 20 ? columns : DEFAULT_WIDTH;
|
|
1835
|
-
}
|
|
1836
|
-
function pagerCommand(pager = process18.env.PAGER) {
|
|
1837
|
-
return pager === undefined || pager.trim() === "" || pager.trim() === "less" ? ["less", "-FRX"] : ["sh", "-c", pager];
|
|
1838
|
-
}
|
|
1839
|
-
async function page(text) {
|
|
1840
|
-
try {
|
|
1841
|
-
const pager = Bun.spawn(pagerCommand(), { stdin: "pipe", stdout: "inherit", stderr: "inherit" });
|
|
1842
|
-
try {
|
|
1843
|
-
pager.stdin.write(text);
|
|
1844
|
-
await pager.stdin.end();
|
|
1845
|
-
} catch {}
|
|
1846
|
-
await pager.exited;
|
|
1847
|
-
} catch {
|
|
1848
|
-
process18.stdout.write(text);
|
|
1849
|
-
}
|
|
1850
|
-
}
|
|
1851
|
-
async function main(args) {
|
|
1852
|
-
const { values, positionals } = parse(args, USAGE, OPTIONS, { exits: EXITS, positionals: ["[file]"], allowNegative: true, replaces: "cat, bat or less on a markdown file, delta on a diff", examples: ["view README.md", "git diff | view"] });
|
|
1853
|
-
if (positionals.length > 1)
|
|
1854
|
-
badUsage("give one file");
|
|
1855
|
-
if (values.diff === true && values.markdown === true)
|
|
1856
|
-
badUsage("--diff and --markdown exclude each other");
|
|
1857
|
-
const path = positionals[0] ?? "-";
|
|
1858
|
-
const text = await readInput(path, { noStdin: "give a file, or pipe the text on stdin" });
|
|
1859
|
-
if (text.trim() === "")
|
|
1860
|
-
fail("nothing to show", 1);
|
|
1861
|
-
const width = wholeNumber(values.width, "width", process18.stdout.isTTY === true ? process18.stdout.columns || DEFAULT_WIDTH : columnsOf(process18.env.COLUMNS), 20);
|
|
1862
|
-
const theme = themeFor(process18.stdout);
|
|
1863
|
-
const language = values.lang === undefined ? languageOf(path) : languageOf(values.lang);
|
|
1864
|
-
if (values.lang !== undefined && language === undefined)
|
|
1865
|
-
badUsage(`unknown language ${values.lang}`);
|
|
1866
|
-
const forced = values.diff === true || values.markdown === true;
|
|
1867
|
-
const isCode = values.lang !== undefined || !forced && language !== undefined && !MARKDOWN_FILE.test(path) && !DIFF_FILE.test(path);
|
|
1868
|
-
const isDiff = !isCode && (values.diff === true || values.markdown !== true && !MARKDOWN_FILE.test(path) && (DIFF_FILE.test(path) || looksLikeDiff(text)));
|
|
1869
|
-
const kind = isDiff ? "diff" : "markdown";
|
|
1870
|
-
function render(as, numbered) {
|
|
1871
|
-
if (isCode)
|
|
1872
|
-
return renderCode(text, language, as, numbered);
|
|
1873
|
-
return isDiff ? renderDiff(text, as) : renderMarkdown(text, { theme: as, width });
|
|
1874
|
-
}
|
|
1875
|
-
if (values.json === true) {
|
|
1876
|
-
printJson({ kind: isCode ? "code" : kind, language: isCode ? language ?? null : null, text: stripAnsi(render(themeFor({ isTTY: false }), values.lines ?? false)) });
|
|
1877
|
-
return 0;
|
|
1878
|
-
}
|
|
1879
|
-
const shown = render(theme, values.lines ?? process18.stdout.isTTY === true);
|
|
1880
|
-
if (process18.stdout.isTTY === true && values.pager !== false && shown.split(`
|
|
1881
|
-
`).length > (process18.stdout.rows || 24))
|
|
1882
|
-
await page(shown);
|
|
1883
|
-
else
|
|
1884
|
-
process18.stdout.write(shown);
|
|
1885
|
-
return 0;
|
|
1886
|
-
}
|
|
1887
|
-
process18.exitCode = await runMain({ name: "view", run: main });
|
|
129
|
+
`)}});return`${finish(trimmed(rendered.replaceAll(BLOCK,"")),width)}
|
|
130
|
+
`}import process16 from"process";function themeFor(stream=process16.stdout,env=process16.env){let colors=paint(stream,env),accent=role("accent",stream,env),path=role("path",stream,env);return{heading:(text)=>accent(colors.bold(text)),code:role("id",stream,env),path,id:role("id",stream,env),dim:role("label",stream,env),bold:colors.bold,italic:colors.italic,strike:colors.strikethrough,changed:colors.inverse,added:colors.green,removed:colors.red,accent,keyword:colors.magenta,string:colors.green,number:colors.yellow,link:(text,url)=>path(colors.underline(link(text,url,stream,env))),shade:(text,ratio)=>takesControlCodes(stream,env)?tinted(colors,gradientAt(activeTheme().theme,ratio)??activeTheme().theme.colors.accent,env)(text):text}}var DEFAULT_WIDTH=80,MARKDOWN_FILE=/\.(?:md|markdown|mdx)$/i,DIFF_FILE=/\.(?:diff|patch)$/i,FILE_RANGE=/^(.+):(\d+)(?:-(\d*))?$/,TRAILING_NEWLINE3=/\n$/,USAGE="view [options] [file...]: shows markdown files, source files, plain text files or git diffs in the colours of the other @kaynooo CLIs\n\nFiles (each optionally with a line range such as src/a.ts:10-50), or what is piped on stdin (or - for stdin). A source file is highlighted behind line numbers by its extension or --lang, a diff, a `git log -p` or a `git show` is recognised by its first line or a .diff or .patch name, .md/.mdx/.markdown files (and stdin by default) are markdown, and unknown or .txt/.log files are shown as plain text preserving line breaks; --diff and --markdown force one.\nLines wrap to the terminal width and a long output on a terminal goes through $PAGER, unless --no-pager. No colour with NO_COLOR, a pipe or --plain. Control characters of the text, escape sequences included, show as cat -v writes them (^[) in code, text and diffs and are dropped from markdown, --json too.",EXITS=[[0,"it showed the text"],[1,"there is nothing to show"],[2,"a usage error or a file that is missing"]],OPTIONS={diff:{type:"boolean",description:"show the text as a diff"},markdown:{type:"boolean",description:"show the text as markdown"},lang:{type:"string",short:"l",description:"show the text as code in this language (ts, json, yaml, sh...)"},lines:{type:"boolean",description:"number the lines of code and text (--no-lines turns it off; on a terminal by default)"},width:{type:"string",short:"w",description:"columns to wrap to, instead of the terminal's"},pager:{type:"boolean",description:"page a long output on a terminal (--no-pager turns it off)"},json:jsonOption("{kind: code, diff, markdown or text, language, text} (or an array for multiple files), rendered without colour")};function parseSpec(raw){if(raw==="-"||existsSync4(raw))return{raw,path:raw};let match=FILE_RANGE.exec(raw);if(match===null)return{raw,path:raw};let start=Number(match[2]),end;if(match[3]===void 0)end=start;else if(match[3]!=="")end=Number(match[3]);if(start<1||end!==void 0&&end<start)badUsage(`invalid line range in '${raw}'`);return{raw,path:match[1],start,...end===void 0?{}:{end}}}function sliceRange(text,start,end){if(start===void 0)return{text,startLine:1};let slice=text.replaceAll(`\r
|
|
131
|
+
`,`
|
|
132
|
+
`).replace(TRAILING_NEWLINE3,"").split(`
|
|
133
|
+
`).slice(start-1,end);return{text:slice.length===0?"":`${slice.join(`
|
|
134
|
+
`)}
|
|
135
|
+
`,startLine:start}}function columnsOf(variable){let columns=Number(variable);return Number.isInteger(columns)&&columns>=20?columns:DEFAULT_WIDTH}function pagerCommand(pager=process17.env.PAGER){return pager===void 0||pager.trim()===""||pager.trim()==="less"?["less","-FRX"]:["sh","-c",pager]}async function page(text){try{let pager=Bun.spawn(pagerCommand(),{stdin:"pipe",stdout:"inherit",stderr:"inherit"});try{pager.stdin.write(text),await pager.stdin.end()}catch{}await pager.exited}catch{process17.stdout.write(text)}}function detectKind(path,text,language,forced){if(forced.lang)return"code";if(forced.diff)return"diff";if(forced.markdown)return"markdown";if(MARKDOWN_FILE.test(path))return"markdown";if(DIFF_FILE.test(path)||looksLikeDiff(text))return"diff";if(language!==void 0)return"code";return path==="-"?"markdown":"text"}function renderKind(kind,text,language,theme,numbered,width,startLine){if(kind==="code")return renderCode(text,language,theme,numbered,startLine);if(kind==="text")return renderCode(text,void 0,theme,numbered,startLine);return kind==="diff"?renderDiff(text,theme):renderMarkdown(text,{theme,width})}async function main(args){let{values,positionals}=parse(args,USAGE,OPTIONS,{exits:EXITS,positionals:["[file...]"],allowNegative:!0,replaces:"cat, bat or less on a markdown or source file, delta on a diff",examples:["view README.md","view src/a.ts:10-40","view a.ts b.ts","git diff | view"]});if(values.diff===!0&&values.markdown===!0)badUsage("--diff and --markdown exclude each other");let forcedLanguage=values.lang===void 0?void 0:languageOf(values.lang);if(values.lang!==void 0&&forcedLanguage===void 0)badUsage(`unknown language ${values.lang}`);let specs=(positionals.length===0?["-"]:positionals).map(parseSpec),human=isHumanTerminal(process17.stdout),width=wholeNumber(values.width,"width",human?process17.stdout.columns||DEFAULT_WIDTH:columnsOf(process17.env.COLUMNS),20),theme=themeFor(process17.stdout),plainTheme=themeFor({isTTY:!1}),forced={diff:values.diff===!0,markdown:values.markdown===!0,lang:values.lang!==void 0},rendered=[];for(let spec of specs){let raw=await readInput(spec.path,{noStdin:"give a file, or pipe the text on stdin"}),{text,startLine}=sliceRange(raw,spec.start,spec.end);if(text.trim()==="")fail("nothing to show",1);let language=forcedLanguage??(spec.path==="-"?void 0:languageOf(spec.path)),kind=detectKind(spec.path,text,language,forced),shown=renderKind(kind,text,language,theme,values.lines??human,width,startLine),plain=stripAnsi(renderKind(kind,text,language,plainTheme,values.lines??!1,width,startLine));rendered.push({spec,kind,language,shown,plain})}if(values.json===!0){if(rendered.length===1){let[only]=rendered;printJson({kind:only.kind,language:only.kind==="code"?only.language??null:null,text:only.plain})}else printJson(rendered.map((item)=>({path:item.spec.raw,kind:item.kind,language:item.kind==="code"?item.language??null:null,text:item.plain})));return 0}let output=rendered.length===1?rendered[0].shown:rendered.map((item)=>`${theme.bold(theme.path(item.spec.raw))}
|
|
136
|
+
${item.shown}`).join(`
|
|
137
|
+
`);if(canPage(process17.stdout)&&values.pager!==!1&&output.split(`
|
|
138
|
+
`).length>(process17.stdout.rows||24))await page(output);else process17.stdout.write(output);return 0}process17.exitCode=await runMain({name:"view",run:main});
|