@kaynooo/cli-changelog 2.4.1 → 2.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +35 -2989
- package/package.json +13 -4
package/dist/cli.js
CHANGED
|
@@ -1,1160 +1,17 @@
|
|
|
1
1
|
#!/bin/sh
|
|
2
2
|
// @bun 2>/dev/null; exec bun --config=/dev/null "$0" "$@"
|
|
3
|
-
var __esm = (fn, res, err) => () => {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
err = [e];
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
};
|
|
14
|
-
|
|
15
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-yfkscv18.js
|
|
16
|
-
var b, M, n;
|
|
17
|
-
var init_chunk_yfkscv18 = __esm(() => {
|
|
18
|
-
b = new TextEncoder;
|
|
19
|
-
M = new TextDecoder("utf-8", { fatal: true });
|
|
20
|
-
n = { y: 31536000000, M: 2592000000, w: 604800000, d: 86400000, h: 3600000, m: 60000, s: 1000 };
|
|
21
|
-
});
|
|
22
|
-
|
|
23
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rkhsft4a.js
|
|
24
|
-
function d(t) {
|
|
25
|
-
return t.charAt(0).toUpperCase() + t.slice(1);
|
|
26
|
-
}
|
|
27
|
-
function G(t, e, { plural: r, zero: n = "singular" } = {}) {
|
|
28
|
-
if (e === 1 || e === 0 && n === "singular")
|
|
29
|
-
return t;
|
|
30
|
-
if (r !== undefined)
|
|
31
|
-
return r;
|
|
32
|
-
if (t.endsWith("y") && !ct.test(t))
|
|
33
|
-
return `${t.slice(0, -1)}ies`;
|
|
34
|
-
if (t.endsWith("s") || t.endsWith("x") || t.endsWith("z") || t.endsWith("ch") || t.endsWith("sh"))
|
|
35
|
-
return `${t}es`;
|
|
36
|
-
if (Ot.test(t))
|
|
37
|
-
return `${t.slice(0, -1)}ves`;
|
|
38
|
-
return Gt.test(t) ? `${t.slice(0, -2)}ves` : `${t}s`;
|
|
39
|
-
}
|
|
40
|
-
var ct, N, Ot, Gt, be, W;
|
|
41
|
-
var init_chunk_rkhsft4a = __esm(() => {
|
|
42
|
-
ct = /[aeiou]y$/;
|
|
43
|
-
N = new Map;
|
|
44
|
-
Ot = /(?:leaf|loaf|thief|wolf|half|calf|elf|sheaf|scarf|dwarf|hoof|wharf)$/;
|
|
45
|
-
Gt = /(?:knife|life|wife)$/;
|
|
46
|
-
be = new Map(["\u20AC", "", "\u201A", "\u0192", "\u201E", "\u2026", "\u2020", "\u2021", "\u02C6", "\u2030", "\u0160", "\u2039", "\u0152", "", "\u017D", "", "", "\u2018", "\u2019", "\u201C", "\u201D", "\u2022", "\u2013", "\u2014", "\u02DC", "\u2122", "\u0161", "\u203A", "\u0153", "", "\u017E", "\u0178"].map((t, e) => [t, 128 + e]).filter(([t]) => t));
|
|
47
|
-
W = new Map;
|
|
48
|
-
});
|
|
49
|
-
|
|
50
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/text.js
|
|
51
|
-
var init_text = __esm(() => {
|
|
52
|
-
init_chunk_rkhsft4a();
|
|
53
|
-
});
|
|
54
|
-
|
|
55
|
-
// ../kit/src/mode.ts
|
|
56
|
-
import process2 from "process";
|
|
57
|
-
function isSet(value) {
|
|
58
|
-
return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
|
|
59
|
-
}
|
|
60
|
-
function outputMode(stream = process2.stdout, env = process2.env) {
|
|
61
|
-
const chosen = env.KIT_MODE;
|
|
62
|
-
if (chosen !== undefined && MODES.has(chosen))
|
|
63
|
-
return chosen;
|
|
64
|
-
if (AGENT_VARIABLES.some((name) => isSet(env[name])))
|
|
65
|
-
return "agent";
|
|
66
|
-
if (stream.isTTY === true)
|
|
67
|
-
return "terminal";
|
|
68
|
-
return isSet(env.CI) ? "ci" : "pipe";
|
|
69
|
-
}
|
|
70
|
-
function isInteractive(streams = process2) {
|
|
71
|
-
return streams.stdin?.isTTY === true && streams.stderr?.isTTY === true;
|
|
72
|
-
}
|
|
73
|
-
var MODES, AGENT_VARIABLES;
|
|
74
|
-
var init_mode = __esm(() => {
|
|
75
|
-
MODES = new Set(["terminal", "ci", "agent", "pipe"]);
|
|
76
|
-
AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
|
|
77
|
-
});
|
|
78
|
-
|
|
79
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
|
|
80
|
-
function b2(r) {
|
|
81
|
-
let e = r.startsWith("#") ? r.slice(1) : r;
|
|
82
|
-
if (!G2.test(e))
|
|
83
|
-
return [0, 0, 0];
|
|
84
|
-
if (e.length === 3 || e.length === 4)
|
|
85
|
-
return [Number.parseInt(e[0] + e[0], 16), Number.parseInt(e[1] + e[1], 16), Number.parseInt(e[2] + e[2], 16)];
|
|
86
|
-
if (e.length !== 6 && e.length !== 8)
|
|
87
|
-
throw Error(`Invalid hex color length: ${e.length}`);
|
|
88
|
-
return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
|
|
89
|
-
}
|
|
90
|
-
function C(r, e = globalThis.process?.env ?? {}) {
|
|
91
|
-
if (e.FORCE_COLOR !== undefined)
|
|
92
|
-
return h.has(e.FORCE_COLOR);
|
|
93
|
-
if (e.NO_COLOR !== undefined || e.NODE_DISABLE_COLORS !== undefined || e.TERM === "dumb")
|
|
94
|
-
return false;
|
|
95
|
-
return r?.isTTY === true;
|
|
96
|
-
}
|
|
97
|
-
function f(r, e = []) {
|
|
98
|
-
let l = "", n = "";
|
|
99
|
-
for (let t = 0, i = e.length;t < i; t++)
|
|
100
|
-
l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
|
|
101
|
-
let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
|
|
102
|
-
return new Proxy(c, { get(t, i) {
|
|
103
|
-
let a = B[i];
|
|
104
|
-
if (Array.isArray(a)) {
|
|
105
|
-
let s = g.get(i);
|
|
106
|
-
if (s === undefined)
|
|
107
|
-
s = f(r, [...e, a]), g.set(i, s);
|
|
108
|
-
return s;
|
|
109
|
-
}
|
|
110
|
-
if (typeof a === "function")
|
|
111
|
-
return (...s) => {
|
|
112
|
-
let y = `${i}:${s.join(",")}`, u = g.get(y);
|
|
113
|
-
if (u === undefined) {
|
|
114
|
-
if (g.size >= 64)
|
|
115
|
-
g.clear();
|
|
116
|
-
u = f(r, [...e, a(...s)]), g.set(y, u);
|
|
117
|
-
}
|
|
118
|
-
return u;
|
|
119
|
-
};
|
|
120
|
-
throw Error(`Unknown style: ${String(i)}`);
|
|
121
|
-
} });
|
|
122
|
-
}
|
|
123
|
-
function Fe(r = {}) {
|
|
124
|
-
return f(r);
|
|
125
|
-
}
|
|
126
|
-
var G2, B, h, o;
|
|
127
|
-
var init_chunk_x450vn3m = __esm(() => {
|
|
128
|
-
G2 = /^[a-f0-9]+$/i;
|
|
129
|
-
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") => {
|
|
130
|
-
let [l, n, c] = b2(r);
|
|
131
|
-
return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
|
|
132
|
-
}, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
|
|
133
|
-
h = new Set(["", "1", "2", "3", "true"]);
|
|
134
|
-
o = Fe();
|
|
135
|
-
});
|
|
136
|
-
|
|
137
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/tools/colors.js
|
|
138
|
-
var init_colors = __esm(() => {
|
|
139
|
-
init_chunk_x450vn3m();
|
|
140
|
-
});
|
|
141
|
-
|
|
142
|
-
// ../kit/src/config.ts
|
|
143
|
-
import { existsSync } from "fs";
|
|
144
|
-
import { dirname, join, resolve } from "path";
|
|
145
|
-
import process3 from "process";
|
|
146
|
-
function findUp(names, from = process3.cwd(), stop = () => false) {
|
|
147
|
-
const wanted = typeof names === "string" ? [names] : names;
|
|
148
|
-
for (let dir = resolve(from);; dir = dirname(dir)) {
|
|
149
|
-
const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
|
|
150
|
-
if (found !== undefined)
|
|
151
|
-
return found;
|
|
152
|
-
if (stop(dir) || dirname(dir) === dir)
|
|
153
|
-
return;
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
var init_config = __esm(() => {
|
|
157
|
-
init_args();
|
|
158
|
-
});
|
|
159
|
-
|
|
160
|
-
// ../kit/src/user-config.ts
|
|
161
|
-
import { existsSync as existsSync2, readFileSync } from "fs";
|
|
162
|
-
import { homedir } from "os";
|
|
163
|
-
import { isAbsolute, join as join2 } from "path";
|
|
164
|
-
import process4 from "process";
|
|
165
|
-
function xdgFolder(value, fallback) {
|
|
166
|
-
return value !== undefined && isAbsolute(value) ? value : fallback;
|
|
167
|
-
}
|
|
168
|
-
function configBase(where = {}) {
|
|
169
|
-
const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
|
|
170
|
-
return xdgFolder(xdg, join2(where.home ?? homedir(), ".config"));
|
|
171
|
-
}
|
|
172
|
-
function userConfigPath(bin, where = {}) {
|
|
173
|
-
return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
|
|
174
|
-
}
|
|
175
|
-
function userConfigReadPath(bin, legacy = [], where = {}) {
|
|
176
|
-
const current = userConfigPath(bin, where);
|
|
177
|
-
if (existsSync2(current))
|
|
178
|
-
return current;
|
|
179
|
-
const base = configBase(where);
|
|
180
|
-
return legacy.map((parts) => join2(base, ...parts)).find((path) => existsSync2(path)) ?? current;
|
|
181
|
-
}
|
|
182
|
-
function readUserConfig(bin, where = {}, legacy = []) {
|
|
183
|
-
const path = userConfigReadPath(bin, legacy, where);
|
|
184
|
-
if (!existsSync2(path))
|
|
185
|
-
return {};
|
|
186
|
-
try {
|
|
187
|
-
const parsed = Bun.JSONC.parse(readFileSync(path, "utf8"));
|
|
188
|
-
return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : {};
|
|
189
|
-
} catch {
|
|
190
|
-
return {};
|
|
191
|
-
}
|
|
192
|
-
}
|
|
193
|
-
function configuredForge(where = {}) {
|
|
194
|
-
const value = readUserConfig("config", where).forge;
|
|
195
|
-
if (typeof value !== "string" || value.trim() === "")
|
|
196
|
-
return;
|
|
197
|
-
const url = (URL_SCHEME.test(value.trim()) ? value.trim() : `https://${value.trim()}`).replace(TRAILING_SLASHES, "");
|
|
198
|
-
return URL.canParse(url) ? { host: new URL(url).host, url } : undefined;
|
|
199
|
-
}
|
|
200
|
-
var URL_SCHEME, TRAILING_SLASHES;
|
|
201
|
-
var init_user_config = __esm(() => {
|
|
202
|
-
URL_SCHEME = /^[a-z][a-z\d+.-]*:\/\//i;
|
|
203
|
-
TRAILING_SLASHES = /\/+$/;
|
|
204
|
-
});
|
|
205
|
-
|
|
206
|
-
// ../kit/src/theme.ts
|
|
207
|
-
import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
|
|
208
|
-
import { homedir as homedir2 } from "os";
|
|
209
|
-
import { join as join3, resolve as resolve2 } from "path";
|
|
210
|
-
import process5 from "process";
|
|
211
|
-
function isColorSpec(spec) {
|
|
212
|
-
if (typeof spec === "number")
|
|
213
|
-
return Number.isInteger(spec) && spec >= 0 && spec <= 255;
|
|
214
|
-
return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
|
|
215
|
-
}
|
|
216
|
-
function cubeLevel(channel) {
|
|
217
|
-
return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
|
|
218
|
-
}
|
|
219
|
-
function nearest256(hex) {
|
|
220
|
-
const rgb = [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
|
|
221
|
-
const levels = rgb.map(cubeLevel);
|
|
222
|
-
const cube = levels.map((level) => CUBE[level]);
|
|
223
|
-
const grey = Math.min(23, Math.max(0, Math.round((rgb.reduce((sum, channel) => sum + channel, 0) / 3 - 8) / 10)));
|
|
224
|
-
const greyValue = 8 + grey * 10;
|
|
225
|
-
const distance = (colour) => colour.reduce((sum, channel, at) => sum + (channel - rgb[at]) ** 2, 0);
|
|
226
|
-
return distance([greyValue, greyValue, greyValue]) < distance(cube) ? 232 + grey : 16 + 36 * levels[0] + 6 * levels[1] + levels[2];
|
|
227
|
-
}
|
|
228
|
-
function hasTrueColor(env) {
|
|
229
|
-
return env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
|
|
230
|
-
}
|
|
231
|
-
function tinted(colors, spec, env = process5.env) {
|
|
232
|
-
if (typeof spec === "number")
|
|
233
|
-
return colors.ansi256(spec);
|
|
234
|
-
return spec.trim().split(SPACES).reduce((chain, token) => {
|
|
235
|
-
if (HEX.test(token))
|
|
236
|
-
return hasTrueColor(env) ? chain.hex(token) : chain.ansi256(nearest256(token));
|
|
237
|
-
return chain[token] ?? chain;
|
|
238
|
-
}, colors);
|
|
239
|
-
}
|
|
240
|
-
function isRecord(value) {
|
|
241
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
242
|
-
}
|
|
243
|
-
function readThemeFile(path, warn) {
|
|
244
|
-
try {
|
|
245
|
-
const stat = statSync(path, { throwIfNoEntry: false });
|
|
246
|
-
if (stat === undefined)
|
|
247
|
-
return;
|
|
248
|
-
if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
|
|
249
|
-
warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
|
|
250
|
-
return;
|
|
251
|
-
}
|
|
252
|
-
const parsed = JSON.parse(readFileSync2(path, "utf8"));
|
|
253
|
-
if (isRecord(parsed))
|
|
254
|
-
return parsed;
|
|
255
|
-
warn(`${path} is not a JSON object, theme ignored`);
|
|
256
|
-
} catch (error) {
|
|
257
|
-
warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
|
|
258
|
-
}
|
|
259
|
-
return;
|
|
260
|
-
}
|
|
261
|
-
function applyPreset(theme, name, warn, where) {
|
|
262
|
-
if (name === undefined)
|
|
263
|
-
return;
|
|
264
|
-
if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
|
|
265
|
-
warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
|
|
266
|
-
return;
|
|
267
|
-
}
|
|
268
|
-
const preset = PRESETS[name];
|
|
269
|
-
Object.assign(theme.colors, preset.colors);
|
|
270
|
-
Object.assign(theme.glyphs, preset.glyphs);
|
|
271
|
-
if (preset.accents !== undefined)
|
|
272
|
-
theme.accents = [...preset.accents];
|
|
273
|
-
if (Object.hasOwn(preset, "gradient"))
|
|
274
|
-
theme.gradient = preset.gradient;
|
|
275
|
-
return name;
|
|
276
|
-
}
|
|
277
|
-
function applyFile(theme, file, where, warn) {
|
|
278
|
-
if (isRecord(file.colors)) {
|
|
279
|
-
for (const [key, value] of Object.entries(file.colors)) {
|
|
280
|
-
if (!Object.hasOwn(DEFAULT.colors, key))
|
|
281
|
-
warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
|
|
282
|
-
else if (!isColorSpec(value))
|
|
283
|
-
warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
|
|
284
|
-
else
|
|
285
|
-
theme.colors[key] = value;
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
if (isRecord(file.glyphs)) {
|
|
289
|
-
for (const [key, value] of Object.entries(file.glyphs)) {
|
|
290
|
-
if (!Object.hasOwn(DEFAULT.glyphs, key))
|
|
291
|
-
warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
|
|
292
|
-
else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
|
|
293
|
-
warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
|
|
294
|
-
else
|
|
295
|
-
theme.glyphs[key] = value;
|
|
296
|
-
}
|
|
297
|
-
}
|
|
298
|
-
if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
|
|
299
|
-
theme.accents = [...file.accents];
|
|
300
|
-
else if (file.accents !== undefined)
|
|
301
|
-
warn(`${where}: accents must be a non-empty list of colours`);
|
|
302
|
-
if (file.gradient === null)
|
|
303
|
-
theme.gradient = undefined;
|
|
304
|
-
else if (Array.isArray(file.gradient) && file.gradient.length === 2 && file.gradient.every((end) => typeof end === "string" && HEX.test(end)))
|
|
305
|
-
theme.gradient = [file.gradient[0], file.gradient[1]];
|
|
306
|
-
else if (file.gradient !== undefined)
|
|
307
|
-
warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);
|
|
308
|
-
if (isRecord(file.bins)) {
|
|
309
|
-
for (const [bin, value] of Object.entries(file.bins)) {
|
|
310
|
-
if (isColorSpec(value))
|
|
311
|
-
theme.bins[bin] = value;
|
|
312
|
-
else
|
|
313
|
-
warn(`${where}: bin ${bin} has no valid colour`);
|
|
314
|
-
}
|
|
315
|
-
}
|
|
316
|
-
}
|
|
317
|
-
function endsWalk(home) {
|
|
318
|
-
return (dir) => dir === resolve2(home) || existsSync3(join3(dir, ".git"));
|
|
319
|
-
}
|
|
320
|
-
function warnOnce(message) {
|
|
321
|
-
if (warned.has(message))
|
|
322
|
-
return;
|
|
323
|
-
warned.add(message);
|
|
324
|
-
console.error(`warning: theme ${message}`);
|
|
325
|
-
}
|
|
326
|
-
function isPath(chosen) {
|
|
327
|
-
return chosen.includes("/") || chosen.endsWith(".json");
|
|
328
|
-
}
|
|
329
|
-
function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(), warn = warnOnce } = {}) {
|
|
330
|
-
const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null), gradient: DEFAULT.gradient };
|
|
331
|
-
const sources = [];
|
|
332
|
-
const chosen = env.KIT_THEME ?? "";
|
|
333
|
-
const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
|
|
334
|
-
if (isPath(chosen))
|
|
335
|
-
wanted.push(resolve2(from, chosen));
|
|
336
|
-
const files = [];
|
|
337
|
-
for (const path of wanted) {
|
|
338
|
-
const file = path === undefined ? undefined : readThemeFile(path, warn);
|
|
339
|
-
if (path !== undefined && file !== undefined)
|
|
340
|
-
files.push({ path, file });
|
|
341
|
-
}
|
|
342
|
-
let preset = "default";
|
|
343
|
-
if (chosen !== "" && !isPath(chosen)) {
|
|
344
|
-
preset = applyPreset(theme, chosen, warn, "KIT_THEME") ?? preset;
|
|
345
|
-
} else {
|
|
346
|
-
const named = files.findLast(({ file }) => file.preset !== undefined);
|
|
347
|
-
if (named !== undefined)
|
|
348
|
-
preset = applyPreset(theme, named.file.preset, warn, named.path) ?? preset;
|
|
349
|
-
}
|
|
350
|
-
for (const { path, file } of files) {
|
|
351
|
-
applyFile(theme, file, path, warn);
|
|
352
|
-
sources.push(path);
|
|
353
|
-
}
|
|
354
|
-
return { theme, sources, preset };
|
|
355
|
-
}
|
|
356
|
-
function activeTheme() {
|
|
357
|
-
const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
|
|
358
|
-
if (current === undefined || key !== currentKey) {
|
|
359
|
-
current = loadTheme();
|
|
360
|
-
currentKey = key;
|
|
361
|
-
}
|
|
362
|
-
return current;
|
|
363
|
-
}
|
|
364
|
-
var ENDS, DEFAULT, BRIGHT, MONO, ASCII, PRESETS, STYLES, HEX, CONTROL, MAX_FILE_BYTES, SPACES, CUBE, warned, current, currentKey = "";
|
|
365
|
-
var init_theme = __esm(() => {
|
|
366
|
-
init_config();
|
|
367
|
-
init_user_config();
|
|
368
|
-
ENDS = new Map;
|
|
369
|
-
DEFAULT = {
|
|
370
|
-
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" },
|
|
371
|
-
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" },
|
|
372
|
-
accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
|
|
373
|
-
bins: {},
|
|
374
|
-
gradient: ["#c084fc", "#67e8f9"]
|
|
375
|
-
};
|
|
376
|
-
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" };
|
|
377
|
-
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" };
|
|
378
|
-
ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
|
|
379
|
-
PRESETS = {
|
|
380
|
-
default: {},
|
|
381
|
-
"high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
|
|
382
|
-
mono: { colors: MONO, accents: ["bold"], gradient: undefined },
|
|
383
|
-
ascii: { glyphs: ASCII }
|
|
384
|
-
};
|
|
385
|
-
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"]);
|
|
386
|
-
HEX = /^#[0-9a-f]{6}$/i;
|
|
387
|
-
CONTROL = /\p{Cc}/u;
|
|
388
|
-
MAX_FILE_BYTES = 64 * 1024;
|
|
389
|
-
SPACES = /\s+/;
|
|
390
|
-
CUBE = [0, 95, 135, 175, 215, 255];
|
|
391
|
-
warned = new Set;
|
|
392
|
-
});
|
|
393
|
-
|
|
394
|
-
// ../kit/src/style.ts
|
|
395
|
-
import process6 from "process";
|
|
396
|
-
function takesControlCodes(stream, env = process6.env) {
|
|
397
|
-
return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
|
|
398
|
-
}
|
|
399
|
-
function paint(stream, env = process6.env) {
|
|
400
|
-
return Fe({ stream: { isTTY: takesControlCodes(stream, env) }, env });
|
|
401
|
-
}
|
|
402
|
-
function role(name, stream, env = process6.env) {
|
|
403
|
-
const colors = paint(stream, env);
|
|
404
|
-
return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
|
|
405
|
-
}
|
|
406
|
-
var STATUS_WORDS, STATUS_OF;
|
|
407
|
-
var init_style = __esm(() => {
|
|
408
|
-
init_colors();
|
|
409
|
-
init_mode();
|
|
410
|
-
init_theme();
|
|
411
|
-
STATUS_WORDS = {
|
|
412
|
-
passed: ["passed", "success", "succeeded", "ok"],
|
|
413
|
-
failed: ["failed", "failure", "error", "errored"],
|
|
414
|
-
running: ["running", "in_progress", "started", "holding"],
|
|
415
|
-
queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
|
|
416
|
-
skipped: ["skipped", "cancelled", "canceled", "manual"]
|
|
417
|
-
};
|
|
418
|
-
STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
|
|
419
|
-
});
|
|
420
|
-
|
|
421
|
-
// ../kit/src/format.ts
|
|
422
|
-
import process7 from "process";
|
|
423
|
-
function formatSeconds(total) {
|
|
424
|
-
let rest = Math.max(0, Math.round(total));
|
|
425
|
-
const amounts = UNITS.map(([unit, size]) => {
|
|
426
|
-
const amount = Math.floor(rest / size);
|
|
427
|
-
rest -= amount * size;
|
|
428
|
-
return `${amount}${unit}`;
|
|
429
|
-
});
|
|
430
|
-
const first = amounts.findIndex((amount) => !amount.startsWith("0"));
|
|
431
|
-
if (first === -1)
|
|
432
|
-
return "0s";
|
|
433
|
-
const next = amounts[first + 1];
|
|
434
|
-
return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
|
|
435
|
-
}
|
|
436
|
-
function formatDuration(ms) {
|
|
437
|
-
return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
|
|
438
|
-
}
|
|
439
|
-
function upTo(text, separator) {
|
|
440
|
-
const end = text.indexOf(separator);
|
|
441
|
-
return end === -1 ? text : text.slice(0, end);
|
|
442
|
-
}
|
|
443
|
-
function textWidth(text) {
|
|
444
|
-
return Bun.stringWidth(text);
|
|
445
|
-
}
|
|
446
|
-
function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
|
|
447
|
-
return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
|
|
448
|
-
}
|
|
449
|
-
function printJson(value) {
|
|
450
|
-
console.log(jsonText(value));
|
|
451
|
-
}
|
|
452
|
-
var UNITS, ESCAPE;
|
|
453
|
-
var init_format = __esm(() => {
|
|
454
|
-
init_mode();
|
|
455
|
-
init_style();
|
|
456
|
-
UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
|
|
457
|
-
ESCAPE = String.fromCharCode(27);
|
|
458
|
-
});
|
|
459
|
-
|
|
460
|
-
// ../kit/src/help.ts
|
|
461
|
-
import process8 from "process";
|
|
462
|
-
function usageLine(usage, colors = paint(process8.stdout), { summary: withSummary = true } = {}) {
|
|
463
|
-
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
464
|
-
`);
|
|
465
|
-
const blank = lines.indexOf("");
|
|
466
|
-
const synopses = blank === -1 ? lines : lines.slice(0, blank);
|
|
467
|
-
const details = blank === -1 ? [] : lines.slice(blank + 1);
|
|
468
|
-
const colon = synopses[0].indexOf(": ");
|
|
469
|
-
const inline = synopses[0].slice(colon + 2);
|
|
470
|
-
const summary = colon === -1 ? details.shift() : `${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;
|
|
471
|
-
if (colon !== -1)
|
|
472
|
-
synopses[0] = synopses[0].slice(0, colon);
|
|
473
|
-
const head = `${colors.bold("Usage:")} ${synopses.map((line) => line.replaceAll(OPTIONAL, (part) => colors.dim(part))).join(`
|
|
474
|
-
`)}`;
|
|
475
|
-
const lead = summary === undefined || !withSummary ? [] : ["", colors.bold(prose(summary, colors))];
|
|
476
|
-
const rest = details.length === 0 ? [] : ["", ...details.map((line) => prose(line, colors))];
|
|
477
|
-
return [head, ...lead, ...rest].join(`
|
|
478
|
-
`);
|
|
479
|
-
}
|
|
480
|
-
function prose(line, colors) {
|
|
481
|
-
if (colors.cyan("x") === "x")
|
|
482
|
-
return line;
|
|
483
|
-
return line.replaceAll(PROSE_MARKS, (match, code, flag) => code === undefined ? colors.cyan(flag ?? match) : colors.bold(code));
|
|
484
|
-
}
|
|
485
|
-
function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [], bin } = {}) {
|
|
486
|
-
const { summary } = description(usage);
|
|
487
|
-
const head = bin === undefined ? [usageLine(usage, colors)] : [`${colors.bold(bin.name)} ${colors.dim(bin.version())}${summary === "" ? "" : ` ${summary}`}`, "", usageLine(usage, colors, { summary: false })];
|
|
488
|
-
return [...head, "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
|
|
489
|
-
`);
|
|
490
|
-
}
|
|
491
|
-
function exitRows(exits, colors = paint(process8.stdout)) {
|
|
492
|
-
if (exits.length === 0)
|
|
493
|
-
return [];
|
|
494
|
-
return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
|
|
495
|
-
}
|
|
496
|
-
function wantsHelpJson(env = process8.env) {
|
|
497
|
-
return env.KIT_HELP === "json";
|
|
498
|
-
}
|
|
499
|
-
function description(usage, { examples = [], replaces, exits } = {}, options) {
|
|
500
|
-
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
501
|
-
`);
|
|
502
|
-
const first = lines[0];
|
|
503
|
-
const colon = first.indexOf(": ");
|
|
504
|
-
const prose = lines[lines.indexOf("") + 1] ?? "";
|
|
505
|
-
const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
|
|
506
|
-
return {
|
|
507
|
-
synopsis: colon === -1 ? first : first.slice(0, colon),
|
|
508
|
-
summary: colon === -1 ? fallback : first.slice(colon + 2),
|
|
509
|
-
...replaces === undefined ? {} : { replaces },
|
|
510
|
-
examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
|
|
511
|
-
...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
|
|
512
|
-
...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
|
|
513
|
-
};
|
|
514
|
-
}
|
|
515
|
-
function exampleRows(examples, colors = paint(process8.stdout)) {
|
|
516
|
-
if (examples.length === 0 || outputMode() === "agent")
|
|
517
|
-
return [];
|
|
518
|
-
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
519
|
-
}
|
|
520
|
-
function optionRows(options, colors = paint(process8.stdout)) {
|
|
521
|
-
const rows = Object.entries(options).map(([name, option]) => {
|
|
522
|
-
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
523
|
-
const choices = option.choices?.join("|");
|
|
524
|
-
const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
|
|
525
|
-
const named = inline ? `<${choices}>` : "<value>";
|
|
526
|
-
const placeholder = option.optional === undefined ? named : `[${named}]`;
|
|
527
|
-
const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
|
|
528
|
-
const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
|
|
529
|
-
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
|
|
530
|
-
});
|
|
531
|
-
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
532
|
-
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
533
|
-
}
|
|
534
|
-
var OPTIONAL, USAGE_PREFIX, FULL_STOP, PROSE_MARKS, MAX_INLINE_CHOICES = 24;
|
|
535
|
-
var init_help = __esm(() => {
|
|
536
|
-
init_mode();
|
|
537
|
-
init_style();
|
|
538
|
-
OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
|
|
539
|
-
USAGE_PREFIX = /^usage:\s*/i;
|
|
540
|
-
FULL_STOP = /\.$/;
|
|
541
|
-
PROSE_MARKS = /`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;
|
|
542
|
-
});
|
|
543
|
-
|
|
544
|
-
// ../kit/src/text.ts
|
|
545
|
-
function distance(a, b) {
|
|
546
|
-
const left = [...a];
|
|
547
|
-
const right = [...b];
|
|
548
|
-
let before = [];
|
|
549
|
-
let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
|
|
550
|
-
for (const [i, x] of left.entries()) {
|
|
551
|
-
const current = [i + 1];
|
|
552
|
-
for (const [j, y] of right.entries()) {
|
|
553
|
-
let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
|
|
554
|
-
if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
|
|
555
|
-
cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
|
|
556
|
-
current.push(cost);
|
|
557
|
-
}
|
|
558
|
-
before = previous;
|
|
559
|
-
previous = current;
|
|
560
|
-
}
|
|
561
|
-
return previous[right.length] ?? 0;
|
|
562
|
-
}
|
|
563
|
-
function closest(name, names) {
|
|
564
|
-
const started = names.find((known) => known.startsWith(name));
|
|
565
|
-
if (started !== undefined)
|
|
566
|
-
return started;
|
|
567
|
-
const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
|
|
568
|
-
return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
|
|
569
|
-
}
|
|
570
|
-
var init_text2 = () => {};
|
|
571
|
-
|
|
572
|
-
// ../kit/src/input.ts
|
|
573
|
-
var init_input = __esm(() => {
|
|
574
|
-
init_args();
|
|
575
|
-
});
|
|
576
|
-
|
|
577
|
-
// ../kit/src/args.ts
|
|
578
|
-
import process9 from "process";
|
|
579
|
-
import { parseArgs } from "util";
|
|
580
|
-
function jsonOption(holds) {
|
|
581
|
-
return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
|
|
582
|
-
}
|
|
583
|
-
function fail(message, code = 2, hint) {
|
|
584
|
-
throw new Exit(message, code, hint);
|
|
585
|
-
}
|
|
586
|
-
function badUsage(message) {
|
|
587
|
-
throw new UsageError(message);
|
|
588
|
-
}
|
|
589
|
-
|
|
590
|
-
class Completing {
|
|
591
|
-
options;
|
|
592
|
-
positionals;
|
|
593
|
-
candidates;
|
|
594
|
-
constructor(options, positionals = [], candidates = {}) {
|
|
595
|
-
this.options = options;
|
|
596
|
-
this.positionals = positionals;
|
|
597
|
-
this.candidates = candidates;
|
|
598
|
-
}
|
|
599
|
-
}
|
|
600
|
-
function applyOutput(color, plain, env = process9.env) {
|
|
601
|
-
const when = plain === true ? "never" : color ?? "auto";
|
|
602
|
-
if (when === "auto")
|
|
603
|
-
return;
|
|
604
|
-
if (when !== "always" && when !== "never")
|
|
605
|
-
badUsage(`--color takes auto, always or never, not ${when}`);
|
|
606
|
-
if (when === "always") {
|
|
607
|
-
env.FORCE_COLOR = "1";
|
|
608
|
-
delete env.NO_COLOR;
|
|
609
|
-
} else {
|
|
610
|
-
env.NO_COLOR = "1";
|
|
611
|
-
delete env.FORCE_COLOR;
|
|
612
|
-
}
|
|
613
|
-
}
|
|
614
|
-
function parse(args, usage, options, settings = {}) {
|
|
615
|
-
const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
|
|
616
|
-
const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
|
|
617
|
-
const listing = listed(all, settings.allowNegative === true);
|
|
618
|
-
if (completion.active)
|
|
619
|
-
throw new Completing(listing, settings.positionals, settings.candidates);
|
|
620
|
-
const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
|
|
621
|
-
let parsed;
|
|
622
|
-
try {
|
|
623
|
-
parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
|
|
624
|
-
} catch (error) {
|
|
625
|
-
const message = parseError(error);
|
|
626
|
-
throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
|
|
627
|
-
}
|
|
628
|
-
const values = parsed.values;
|
|
629
|
-
applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
|
|
630
|
-
if (values.help === true) {
|
|
631
|
-
console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, { ...settings, bin: heading.bin }));
|
|
632
|
-
throw new HelpShown;
|
|
633
|
-
}
|
|
634
|
-
checkChoices(parsed.values, all);
|
|
635
|
-
checkConflicts(parsed.values, all);
|
|
636
|
-
if (settings.positionals !== undefined)
|
|
637
|
-
checkPositionals(parsed.positionals, settings.positionals);
|
|
638
|
-
return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
|
|
639
|
-
}
|
|
640
|
-
function splitRest(args, passes) {
|
|
641
|
-
const separator = passes ? args.indexOf("--") : -1;
|
|
642
|
-
return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
|
|
643
|
-
}
|
|
644
|
-
function splitTrailing(args, options, count) {
|
|
645
|
-
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
646
|
-
let seen = 0;
|
|
647
|
-
if (count === 0)
|
|
648
|
-
return { own: args, rest: undefined };
|
|
649
|
-
for (let at = 0;at < args.length; at++) {
|
|
650
|
-
const word = args[at];
|
|
651
|
-
if (word === "--")
|
|
652
|
-
break;
|
|
653
|
-
if (word.startsWith("-")) {
|
|
654
|
-
if (takesValue(word))
|
|
655
|
-
at++;
|
|
656
|
-
continue;
|
|
657
|
-
}
|
|
658
|
-
seen++;
|
|
659
|
-
if (seen === count)
|
|
660
|
-
return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
|
|
661
|
-
}
|
|
662
|
-
return { own: args, rest: undefined };
|
|
663
|
-
}
|
|
664
|
-
function listed(options, allowNegative) {
|
|
665
|
-
if (!allowNegative)
|
|
666
|
-
return options;
|
|
667
|
-
return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
|
|
668
|
-
if (option.type !== "boolean" || option.negative === undefined)
|
|
669
|
-
return [[name, option]];
|
|
670
|
-
return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
|
|
671
|
-
}));
|
|
672
|
-
}
|
|
673
|
-
function withAliases(args, options) {
|
|
674
|
-
const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
|
|
675
|
-
if (named.size === 0)
|
|
676
|
-
return args;
|
|
677
|
-
const separator = args.indexOf("--");
|
|
678
|
-
const own = separator === -1 ? args : args.slice(0, separator);
|
|
679
|
-
return [...own.map((arg) => {
|
|
680
|
-
const at = arg.indexOf("=");
|
|
681
|
-
const current = named.get(at === -1 ? arg : arg.slice(0, at));
|
|
682
|
-
return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
|
|
683
|
-
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
684
|
-
}
|
|
685
|
-
function withBare(args, options) {
|
|
686
|
-
const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
|
|
687
|
-
if (bare.size === 0)
|
|
688
|
-
return args;
|
|
689
|
-
const separator = args.indexOf("--");
|
|
690
|
-
const own = separator === -1 ? args : args.slice(0, separator);
|
|
691
|
-
return [...own.flatMap((arg, index) => {
|
|
692
|
-
const optional = bare.get(arg);
|
|
693
|
-
const next = own[index + 1];
|
|
694
|
-
const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
|
|
695
|
-
return optional === undefined || value ? [arg] : [arg, optional.bare];
|
|
696
|
-
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
697
|
-
}
|
|
698
|
-
function checkConflicts(values, options) {
|
|
699
|
-
const given = (name) => values[name] !== undefined && values[name] !== false;
|
|
700
|
-
for (const [name, { conflicts = [] }] of Object.entries(options)) {
|
|
701
|
-
const other = given(name) ? conflicts.find(given) : undefined;
|
|
702
|
-
if (other !== undefined)
|
|
703
|
-
badUsage(`--${name} cannot be used with --${other}`);
|
|
704
|
-
}
|
|
705
|
-
}
|
|
706
|
-
function checkChoices(values, options) {
|
|
707
|
-
for (const [name, option] of Object.entries(options)) {
|
|
708
|
-
if (option.choices === undefined)
|
|
709
|
-
continue;
|
|
710
|
-
const given = values[name];
|
|
711
|
-
for (const value of Array.isArray(given) ? given : [given]) {
|
|
712
|
-
if (typeof value === "string")
|
|
713
|
-
oneOf(value, name, option.choices);
|
|
714
|
-
}
|
|
715
|
-
}
|
|
716
|
-
}
|
|
717
|
-
function oneOf(value, name, choices) {
|
|
718
|
-
if (!choices.includes(value))
|
|
719
|
-
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
|
|
720
|
-
return value;
|
|
721
|
-
}
|
|
722
|
-
function checkPositionals(given, names) {
|
|
723
|
-
const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
|
|
724
|
-
const required = names.filter((name) => !name.startsWith("[")).length;
|
|
725
|
-
if (given.length < required)
|
|
726
|
-
badUsage(`missing ${names[given.length]}`);
|
|
727
|
-
if (!variadic && given.length > names.length)
|
|
728
|
-
badUsage(`unexpected argument ${given[names.length]}`);
|
|
729
|
-
}
|
|
730
|
-
function joinDashValues(args, options) {
|
|
731
|
-
const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
|
|
732
|
-
const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
|
|
733
|
-
const joined = [];
|
|
734
|
-
for (let i = 0;i < args.length; i++) {
|
|
735
|
-
const arg = args[i] ?? "";
|
|
736
|
-
if (arg === "--")
|
|
737
|
-
return [...joined, ...args.slice(i)];
|
|
738
|
-
const name = longOf.get(arg);
|
|
739
|
-
const next = args[i + 1];
|
|
740
|
-
if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
|
|
741
|
-
joined.push(`--${name}=${next}`);
|
|
742
|
-
i++;
|
|
743
|
-
} else {
|
|
744
|
-
joined.push(arg);
|
|
745
|
-
}
|
|
746
|
-
}
|
|
747
|
-
return joined;
|
|
748
|
-
}
|
|
749
|
-
function parseError(error) {
|
|
750
|
-
const message = upTo(error instanceof Error ? error.message : String(error), ". ");
|
|
751
|
-
return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
|
|
752
|
-
}
|
|
753
|
-
function nearestOption(message, options, allowNegative) {
|
|
754
|
-
const typed = UNKNOWN_OPTION.exec(message)?.[1];
|
|
755
|
-
if (typed === undefined)
|
|
756
|
-
return;
|
|
757
|
-
const word = typed.replace(DASHES, "");
|
|
758
|
-
if (word.length < 2 && !typed.startsWith("--"))
|
|
759
|
-
return;
|
|
760
|
-
const known = Object.entries(options).flatMap(([name, option]) => [
|
|
761
|
-
...option.short === undefined ? [] : [`-${option.short}`],
|
|
762
|
-
`--${name}`,
|
|
763
|
-
...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
|
|
764
|
-
]);
|
|
765
|
-
const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
|
|
766
|
-
return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
|
|
767
|
-
}
|
|
768
|
-
var DASHES, EXIT, Exit, UsageError, HelpShown, completion, heading, OUTPUT_OPTIONS, UNKNOWN_OPTION;
|
|
769
|
-
var init_args = __esm(() => {
|
|
770
|
-
init_format();
|
|
771
|
-
init_help();
|
|
772
|
-
init_text2();
|
|
773
|
-
init_help();
|
|
774
|
-
init_input();
|
|
775
|
-
DASHES = /^-+/;
|
|
776
|
-
EXIT = Symbol.for("@kaynooo/cli-kit/Exit");
|
|
777
|
-
Exit = class Exit extends Error {
|
|
778
|
-
code;
|
|
779
|
-
hint;
|
|
780
|
-
[EXIT] = true;
|
|
781
|
-
constructor(message, code, hint) {
|
|
782
|
-
super(message);
|
|
783
|
-
this.code = code;
|
|
784
|
-
this.hint = hint;
|
|
785
|
-
}
|
|
786
|
-
static [Symbol.hasInstance](value) {
|
|
787
|
-
if (this !== Exit)
|
|
788
|
-
return Function.prototype[Symbol.hasInstance].call(this, value);
|
|
789
|
-
return typeof value === "object" && value !== null && value[EXIT] === true;
|
|
790
|
-
}
|
|
791
|
-
};
|
|
792
|
-
UsageError = class UsageError extends Exit {
|
|
793
|
-
constructor(message, hint) {
|
|
794
|
-
super(message, 2, hint);
|
|
795
|
-
}
|
|
796
|
-
};
|
|
797
|
-
HelpShown = class HelpShown extends Exit {
|
|
798
|
-
constructor() {
|
|
799
|
-
super("help shown", 0);
|
|
800
|
-
}
|
|
801
|
-
};
|
|
802
|
-
completion = { active: false };
|
|
803
|
-
heading = { bin: undefined };
|
|
804
|
-
OUTPUT_OPTIONS = {
|
|
805
|
-
color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
|
|
806
|
-
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
807
|
-
};
|
|
808
|
-
UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
|
|
809
|
-
});
|
|
810
|
-
|
|
811
|
-
// ../kit/src/folders.ts
|
|
812
|
-
var SKIPPED_FOLDERS;
|
|
813
|
-
var init_folders = __esm(() => {
|
|
814
|
-
init_user_config();
|
|
815
|
-
SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
|
|
816
|
-
});
|
|
817
|
-
|
|
818
|
-
// ../kit/src/answers.ts
|
|
819
|
-
var init_answers = __esm(() => {
|
|
820
|
-
init_folders();
|
|
821
|
-
});
|
|
822
|
-
|
|
823
|
-
// ../kit/src/job.ts
|
|
824
|
-
import process16 from "process";
|
|
825
|
-
function stopJob() {
|
|
826
|
-
process16.kill(0, "SIGTSTP");
|
|
827
|
-
}
|
|
828
|
-
var init_job = () => {};
|
|
829
|
-
|
|
830
|
-
// ../kit/src/picker/line.ts
|
|
831
|
-
function isEditKey(key) {
|
|
832
|
-
return EDIT_KEYS.has(key);
|
|
833
|
-
}
|
|
834
|
-
var EDIT_KEYS, BACKWARD_KILLS, FORWARD_KILLS;
|
|
835
|
-
var init_line = __esm(() => {
|
|
836
|
-
EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
|
|
837
|
-
BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
|
|
838
|
-
FORWARD_KILLS = new Set(["killnext", "killend"]);
|
|
839
|
-
});
|
|
840
|
-
|
|
841
|
-
// ../kit/src/picker/score.ts
|
|
842
|
-
var BOUNDARY_AFTER, NONE;
|
|
843
|
-
var init_score = __esm(() => {
|
|
844
|
-
BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
|
|
845
|
-
NONE = Number.NEGATIVE_INFINITY;
|
|
846
|
-
});
|
|
847
|
-
|
|
848
|
-
// ../kit/src/picker/state.ts
|
|
849
|
-
function repeat(value, count) {
|
|
850
|
-
return Array.from({ length: count }).fill(value);
|
|
851
|
-
}
|
|
852
|
-
function parseKeys(input, paste = { active: false }, ctrls = []) {
|
|
853
|
-
const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
|
|
854
|
-
return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
|
|
855
|
-
const wheel = MOUSE.exec(sequence)?.[1];
|
|
856
|
-
if (wheel !== undefined)
|
|
857
|
-
return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
|
|
858
|
-
const named = codes.get(sequence);
|
|
859
|
-
const key = named === undefined ? KEYS[sequence] : { ctrl: named };
|
|
860
|
-
if (sequence === PASTE_START || sequence === PASTE_END) {
|
|
861
|
-
paste.active = sequence === PASTE_START;
|
|
862
|
-
return [];
|
|
863
|
-
}
|
|
864
|
-
if (paste.active && (sequence === "\r" || sequence === `
|
|
865
|
-
`))
|
|
866
|
-
return [];
|
|
867
|
-
if (key !== undefined)
|
|
868
|
-
return [key];
|
|
869
|
-
return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
|
|
870
|
-
});
|
|
871
|
-
}
|
|
872
|
-
var IS_CONTROL, PASTE_START = "\x1B[200~", PASTE_END = "\x1B[201~", KEY_SEQUENCES, MOUSE, WHEEL_LINES = 3, KEYS;
|
|
873
|
-
var init_state = __esm(() => {
|
|
874
|
-
init_text2();
|
|
875
|
-
init_line();
|
|
876
|
-
init_score();
|
|
877
|
-
IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
|
|
878
|
-
KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
|
|
879
|
-
MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
|
|
880
|
-
KEYS = {
|
|
881
|
-
"\x1B[A": "up",
|
|
882
|
-
"\x1BOA": "up",
|
|
883
|
-
"\x10": "up",
|
|
884
|
-
"\x1B[B": "down",
|
|
885
|
-
"\x1BOB": "down",
|
|
886
|
-
"\x0E": "down",
|
|
887
|
-
"\x1B[5~": "pageup",
|
|
888
|
-
"\x1B[6~": "pagedown",
|
|
889
|
-
"\x1B[H": "home",
|
|
890
|
-
"\x1B[1~": "home",
|
|
891
|
-
"\x1BOH": "home",
|
|
892
|
-
"\x1B[F": "end",
|
|
893
|
-
"\x1B[4~": "end",
|
|
894
|
-
"\x1BOF": "end",
|
|
895
|
-
"\r": "enter",
|
|
896
|
-
"\n": "enter",
|
|
897
|
-
"\x03": "cancel",
|
|
898
|
-
"\x1B": "cancel",
|
|
899
|
-
"\x1B[D": "left",
|
|
900
|
-
"\x1BOD": "left",
|
|
901
|
-
"\x1B[C": "right",
|
|
902
|
-
"\x1BOC": "right",
|
|
903
|
-
"\x1B[1;5D": "wordleft",
|
|
904
|
-
"\x1B[1;3D": "wordleft",
|
|
905
|
-
"\x1Bb": "wordleft",
|
|
906
|
-
"\x1B[1;5C": "wordright",
|
|
907
|
-
"\x1B[1;3C": "wordright",
|
|
908
|
-
"\x1Bf": "wordright",
|
|
909
|
-
"\x01": "linestart",
|
|
910
|
-
"\x05": "lineend",
|
|
911
|
-
"\x7F": "erase",
|
|
912
|
-
"\x1B[3~": "delete",
|
|
913
|
-
"\b": "killword",
|
|
914
|
-
"\x1B\x7F": "killword",
|
|
915
|
-
"\x1B[3;5~": "killnext",
|
|
916
|
-
"\x1Bd": "killnext",
|
|
917
|
-
"\x15": "clear",
|
|
918
|
-
"\v": "killend",
|
|
919
|
-
"\x17": "word",
|
|
920
|
-
"\x19": "yank",
|
|
921
|
-
"\x1A": "suspend",
|
|
922
|
-
"\t": "tab",
|
|
923
|
-
"\x1F": "help",
|
|
924
|
-
"\x1BOP": "help",
|
|
925
|
-
"\x1B[11~": "help"
|
|
926
|
-
};
|
|
927
|
-
});
|
|
928
|
-
|
|
929
|
-
// ../kit/src/redraw.ts
|
|
930
|
-
function overwrite(lines, columns) {
|
|
931
|
-
return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
|
|
932
|
-
`);
|
|
933
|
-
}
|
|
934
|
-
function rowsTaken(lines, columns) {
|
|
935
|
-
return lines.reduce((rows, line) => rows + Math.max(1, Math.ceil(textWidth(line) / columns)), 0);
|
|
936
|
-
}
|
|
937
|
-
var SYNC_START = "\x1B[?2026h", SYNC_END = "\x1B[?2026l";
|
|
938
|
-
var init_redraw = __esm(() => {
|
|
939
|
-
init_format();
|
|
940
|
-
});
|
|
941
|
-
|
|
942
|
-
// ../kit/src/prompt.ts
|
|
943
|
-
import process17 from "process";
|
|
944
|
-
function readKeys(input, paste = { active: false }) {
|
|
945
|
-
return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key) || isEditKey(key));
|
|
946
|
-
}
|
|
947
|
-
async function confirm(question, { default: fallback, ...settings } = {}) {
|
|
948
|
-
let answered = fallback;
|
|
949
|
-
const choices = { true: "Y/n", false: "y/N", undefined: "y/n" }[String(fallback)];
|
|
950
|
-
const accepted = await ask(question, settings, (colors, state) => [state === "asking" ? asking(colors, question, "", choices) : answer(colors, question, state, answered ? "yes" : "no")], (key) => {
|
|
951
|
-
if (key === "cancel")
|
|
952
|
-
return "cancel";
|
|
953
|
-
if (key === "enter")
|
|
954
|
-
return answered === undefined ? undefined : "enter";
|
|
955
|
-
const letter = typeof key === "object" ? key.text.toLowerCase() : "";
|
|
956
|
-
if (letter !== "y" && letter !== "n")
|
|
957
|
-
return;
|
|
958
|
-
answered = letter === "y";
|
|
959
|
-
return "enter";
|
|
960
|
-
});
|
|
961
|
-
return accepted ? answered : undefined;
|
|
962
|
-
}
|
|
963
|
-
function asking(colors, question, typed, keys) {
|
|
964
|
-
return `${colors.cyan("?")} ${question} ${typed === "" ? colors.dim(`(${keys})`) : typed}`;
|
|
965
|
-
}
|
|
966
|
-
function answer(colors, question, state, picked) {
|
|
967
|
-
return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
|
|
968
|
-
}
|
|
969
|
-
async function ask(question, { hint, terminal = process17 }, render, press) {
|
|
970
|
-
const { stdin, stderr } = terminal;
|
|
971
|
-
if (!isInteractive(terminal))
|
|
972
|
-
fail(`cannot ask "${question}" off a terminal`, 2, hint);
|
|
973
|
-
const colors = paint(stderr);
|
|
974
|
-
let current = "asking";
|
|
975
|
-
let outcome;
|
|
976
|
-
const columns = () => stderr.columns || 80;
|
|
977
|
-
const draw = (state, last = false) => {
|
|
978
|
-
const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
|
|
979
|
-
const rows = rowsTaken(frame, columns());
|
|
980
|
-
stderr.write(`${SYNC_START}\r${overwrite(frame, columns())}\x1B[0J${last || rows < 2 ? "" : `\x1B[${rows - 1}A`}${last ? "" : "\r"}${SYNC_END}`);
|
|
981
|
-
current = state;
|
|
982
|
-
};
|
|
983
|
-
const redraw = () => draw(current);
|
|
984
|
-
const paste = { active: false };
|
|
985
|
-
const stop = terminal.stop ?? (terminal === process17 ? stopJob : undefined);
|
|
986
|
-
const suspend = () => {
|
|
987
|
-
if (stop === undefined)
|
|
988
|
-
return;
|
|
989
|
-
stderr.write("\x1B[0J\x1B[?25h\x1B[?2004l");
|
|
990
|
-
stdin.setRawMode(false);
|
|
991
|
-
stop();
|
|
992
|
-
stdin.setRawMode(true);
|
|
993
|
-
stderr.write("\x1B[?25l\x1B[?2004h");
|
|
994
|
-
};
|
|
995
|
-
try {
|
|
996
|
-
stderr.on?.("resize", redraw);
|
|
997
|
-
stdin.setRawMode(true);
|
|
998
|
-
stdin.resume();
|
|
999
|
-
stderr.write("\x1B[?25l\x1B[?2004h");
|
|
1000
|
-
draw("asking");
|
|
1001
|
-
return await new Promise((resolve) => {
|
|
1002
|
-
function onData(data) {
|
|
1003
|
-
for (const key of readKeys(data.toString(), paste)) {
|
|
1004
|
-
if (key === "suspend") {
|
|
1005
|
-
suspend();
|
|
1006
|
-
continue;
|
|
1007
|
-
}
|
|
1008
|
-
const pressed = press(key);
|
|
1009
|
-
if (pressed !== undefined) {
|
|
1010
|
-
settle(pressed);
|
|
1011
|
-
return;
|
|
1012
|
-
}
|
|
1013
|
-
}
|
|
1014
|
-
draw("asking");
|
|
1015
|
-
}
|
|
1016
|
-
function onEnd() {
|
|
1017
|
-
settle("cancel");
|
|
1018
|
-
}
|
|
1019
|
-
function settle(settled) {
|
|
1020
|
-
outcome = settled;
|
|
1021
|
-
stdin.off("data", onData);
|
|
1022
|
-
stdin.off("end", onEnd);
|
|
1023
|
-
resolve(settled === "enter");
|
|
1024
|
-
}
|
|
1025
|
-
stdin.on("data", onData);
|
|
1026
|
-
stdin.on("end", onEnd);
|
|
1027
|
-
});
|
|
1028
|
-
} finally {
|
|
1029
|
-
stderr.off?.("resize", redraw);
|
|
1030
|
-
draw(outcome ?? "cancel", true);
|
|
1031
|
-
stderr.write(`
|
|
1032
|
-
\x1B[?25h\x1B[?2004l`);
|
|
1033
|
-
stdin.setRawMode(false);
|
|
1034
|
-
stdin.pause();
|
|
1035
|
-
}
|
|
1036
|
-
}
|
|
1037
|
-
var PROMPT_KEYS;
|
|
1038
|
-
var init_prompt = __esm(() => {
|
|
1039
|
-
init_answers();
|
|
1040
|
-
init_args();
|
|
1041
|
-
init_format();
|
|
1042
|
-
init_job();
|
|
1043
|
-
init_mode();
|
|
1044
|
-
init_line();
|
|
1045
|
-
init_state();
|
|
1046
|
-
init_redraw();
|
|
1047
|
-
init_style();
|
|
1048
|
-
PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "suspend", "tab"]);
|
|
1049
|
-
});
|
|
1050
|
-
|
|
1051
|
-
// src/cli.ts
|
|
1052
|
-
import { tmpdir } from "os";
|
|
1053
|
-
import { join as join9 } from "path";
|
|
1054
|
-
|
|
1055
|
-
// ../kit/src/index.ts
|
|
1056
|
-
init_args();
|
|
1057
|
-
|
|
1058
|
-
// ../kit/src/argv.ts
|
|
1059
|
-
import { readFileSync as readFileSync3, realpathSync } from "fs";
|
|
1060
|
-
import { resolve as resolve3 } from "path";
|
|
1061
|
-
import process10 from "process";
|
|
1062
|
-
function commandLine() {
|
|
1063
|
-
try {
|
|
1064
|
-
return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
|
|
1065
|
-
} catch {
|
|
1066
|
-
return;
|
|
1067
|
-
}
|
|
1068
|
-
}
|
|
1069
|
-
function realPath(word) {
|
|
1070
|
-
try {
|
|
1071
|
-
return realpathSync(resolve3(word));
|
|
1072
|
-
} catch {
|
|
1073
|
-
return;
|
|
1074
|
-
}
|
|
1075
|
-
}
|
|
1076
|
-
function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
|
|
1077
|
-
const target = script === undefined ? undefined : realPath(script) ?? script;
|
|
1078
|
-
const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
|
|
1079
|
-
const after = at === -1 ? [] : cmdline.slice(at + 1);
|
|
1080
|
-
return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
|
|
1081
|
-
}
|
|
1082
|
-
// ../kit/src/chart.ts
|
|
1083
|
-
init_format();
|
|
1084
|
-
init_mode();
|
|
1085
|
-
init_style();
|
|
1086
|
-
init_theme();
|
|
1087
|
-
// ../kit/src/ci.ts
|
|
1088
|
-
init_args();
|
|
1089
|
-
init_format();
|
|
1090
|
-
|
|
1091
|
-
// ../kit/src/progress.ts
|
|
1092
|
-
init_format();
|
|
1093
|
-
|
|
1094
|
-
// ../kit/src/process.ts
|
|
1095
|
-
var GROUP_SIGNALS = new Set(["SIGINT", "SIGHUP"]);
|
|
1096
|
-
|
|
1097
|
-
// ../kit/src/progress.ts
|
|
1098
|
-
init_style();
|
|
1099
|
-
init_theme();
|
|
1100
|
-
var ESC = String.fromCharCode(27);
|
|
1101
|
-
var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
|
|
1102
|
-
var RESET_STYLE = `${ESC}[0m`;
|
|
1103
|
-
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
1104
|
-
|
|
1105
|
-
// ../kit/src/ci.ts
|
|
1106
|
-
init_style();
|
|
1107
|
-
|
|
1108
|
-
// ../kit/src/tool.ts
|
|
1109
|
-
init_format();
|
|
1110
|
-
// ../kit/src/cli.ts
|
|
1111
|
-
init_args();
|
|
1112
|
-
import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
|
|
1113
|
-
import { dirname as dirname3, join as join5 } from "path";
|
|
1114
|
-
import process14 from "process";
|
|
1115
|
-
|
|
1116
|
-
// ../kit/src/askpass.ts
|
|
1117
|
-
import process11 from "process";
|
|
1118
|
-
var SOCKET_VARIABLE = "KAYNOOO_ASKPASS_SOCKET";
|
|
1119
|
-
async function askpassClient(argv) {
|
|
1120
|
-
const socketPath = process11.env[SOCKET_VARIABLE];
|
|
1121
|
-
if (socketPath === undefined)
|
|
1122
|
-
return;
|
|
1123
|
-
const request = { prompt: argv[0] ?? "", ...process11.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
|
|
1124
|
-
const { promise, resolve } = Promise.withResolvers();
|
|
1125
|
-
let received = "";
|
|
1126
|
-
try {
|
|
1127
|
-
await Bun.connect({
|
|
1128
|
-
unix: socketPath,
|
|
1129
|
-
socket: {
|
|
1130
|
-
open: (socket) => void socket.write(`${JSON.stringify(request)}
|
|
1131
|
-
`),
|
|
1132
|
-
data: (_, chunk) => {
|
|
1133
|
-
received += chunk.toString();
|
|
1134
|
-
},
|
|
1135
|
-
close: () => resolve(received),
|
|
1136
|
-
error: () => resolve("")
|
|
1137
|
-
}
|
|
1138
|
-
});
|
|
1139
|
-
} catch {
|
|
1140
|
-
return 1;
|
|
1141
|
-
}
|
|
1142
|
-
const reply = await promise;
|
|
1143
|
-
if (reply === "")
|
|
1144
|
-
return 1;
|
|
1145
|
-
const { answer } = JSON.parse(reply);
|
|
1146
|
-
if (request.notice === true)
|
|
1147
|
-
return 0;
|
|
1148
|
-
if (answer === undefined)
|
|
1149
|
-
return 1;
|
|
1150
|
-
process11.stdout.write(`${answer}
|
|
1151
|
-
`);
|
|
1152
|
-
return 0;
|
|
1153
|
-
}
|
|
1154
|
-
|
|
1155
|
-
// ../kit/src/completions.ts
|
|
1156
|
-
var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
|
|
1157
|
-
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};var M,n;var init_chunk_yfkscv18=__esm(()=>{M=new TextDecoder("utf-8",{fatal:!0}),n={y:31536000000,M:2592000000,w:604800000,d:86400000,h:3600000,m:60000,s:1000}});function d(t){return t.charAt(0).toUpperCase()+t.slice(1)}function G(t,e,{plural:r,zero:n="singular"}={}){if(e===1||e===0&&n==="singular")return t;if(r!==void 0)return r;if(t.endsWith("y")&&!ct.test(t))return`${t.slice(0,-1)}ies`;if(t.endsWith("s")||t.endsWith("x")||t.endsWith("z")||t.endsWith("ch")||t.endsWith("sh"))return`${t}es`;if(Ot.test(t))return`${t.slice(0,-1)}ves`;return Gt.test(t)?`${t.slice(0,-2)}ves`:`${t}s`}var ct,Ot,Gt,be;var init_chunk_rkhsft4a=__esm(()=>{ct=/[aeiou]y$/;Ot=/(?:leaf|loaf|thief|wolf|half|calf|elf|sheaf|scarf|dwarf|hoof|wharf)$/,Gt=/(?:knife|life|wife)$/;be=new Map(["\u20AC","","\u201A","\u0192","\u201E","\u2026","\u2020","\u2021","\u02C6","\u2030","\u0160","\u2039","\u0152","","\u017D","","","\u2018","\u2019","\u201C","\u201D","\u2022","\u2013","\u2014","\u02DC","\u2122","\u0161","\u203A","\u0153","","\u017E","\u0178"].map((t,e)=>[t,128+e]).filter(([t])=>t))});var init_text=__esm(()=>{init_chunk_rkhsft4a()});import process2 from"process";function isSet(value){return value!==void 0&&value!==""&&value!=="0"&&value.toLowerCase()!=="false"}function outputMode(stream=process2.stdout,env=process2.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 isInteractive(streams=process2){return streams.stdin?.isTTY===!0&&streams.stderr?.isTTY===!0}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(!G2.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 G2,B,h,o;var init_chunk_x450vn3m=__esm(()=>{G2=/^[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 process3 from"process";function findUp(names,from=process3.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,readFileSync}from"fs";import{homedir}from"os";import{isAbsolute,join as join2}from"path";import process4 from"process";function xdgFolder(value,fallback){return value!==void 0&&isAbsolute(value)?value:fallback}function configBase(where={}){let xdg=where.xdg??(where.home===void 0?process4.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 userConfigReadPath(bin,legacy=[],where={}){let current=userConfigPath(bin,where);if(existsSync2(current))return current;let base=configBase(where);return legacy.map((parts)=>join2(base,...parts)).find((path)=>existsSync2(path))??current}function readUserConfig(bin,where={},legacy=[]){let path=userConfigReadPath(bin,legacy,where);if(!existsSync2(path))return{};try{let parsed=Bun.JSONC.parse(readFileSync(path,"utf8"));return typeof parsed==="object"&&parsed!==null&&!Array.isArray(parsed)?parsed:{}}catch{return{}}}function configuredForge(where={}){let value=readUserConfig("config",where).forge;if(typeof value!=="string"||value.trim()==="")return;let url=(URL_SCHEME.test(value.trim())?value.trim():`https://${value.trim()}`).replace(TRAILING_SLASHES,"");return URL.canParse(url)?{host:new URL(url).host,url}:void 0}var URL_SCHEME,TRAILING_SLASHES;var init_user_config=__esm(()=>{URL_SCHEME=/^[a-z][a-z\d+.-]*:\/\//i,TRAILING_SLASHES=/\/+$/});import{existsSync as existsSync3,readFileSync as readFileSync2,statSync}from"fs";import{homedir as homedir2}from"os";import{join as join3,resolve as resolve2}from"path";import process5 from"process";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=process5.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 isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function readThemeFile(path,warn){try{let stat=statSync(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=JSON.parse(readFileSync2(path,"utf8"));if(isRecord(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(isRecord(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(isRecord(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(isRecord(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=process5.env,from=process5.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=[];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=`${process5.cwd()}\x00${process5.env.KIT_THEME??""}\x00${process5.env.XDG_CONFIG_HOME??""}`;if(current===void 0||key!==currentKey)current=loadTheme(),currentKey=key;return current}var 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();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 process6 from"process";function takesControlCodes(stream,env=process6.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=process6.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=process6.env){let colors=paint(stream,env);return takesControlCodes(stream,env)?tinted(colors,activeTheme().theme.colors[name],env):colors}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 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 ESC,ESCAPE_CODE,RESET_STYLE,CLOSE_LINK;var init_text2=__esm(()=>{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 process7 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=process7.stdout,env=process7.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_text2();init_theme();UNITS=[["d",86400],["h",3600],["m",60],["s",1]]});import process8 from"process";function usageLine(usage,colors=paint(process8.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(process8.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(process8.stdout)){if(exits.length===0)return[];return["",`${colors.bold("Exit codes:")} ${exits.map(([code,meaning])=>`${colors.cyan(String(code))} ${meaning}`).join(", ")}`]}function wantsHelpJson(env=process8.env){return env.KIT_HELP==="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(process8.stdout)){if(examples.length===0||outputMode()==="agent")return[];return["",colors.bold("Examples:"),...examples.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(process8.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_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});var init_input=__esm(()=>{init_args()});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),parsed;try{parsed=parseArgs({args:joinDashValues(withBare(withAliases(own,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(wantsHelpJson()?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_text2();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()});var init_answers=__esm(()=>{init_folders()});import process16 from"process";function stopJob(){process16.kill(0,"SIGTSTP")}var init_job=()=>{};function isEditKey(key){return EDIT_KEYS.has(key)}var EDIT_KEYS;var init_line=__esm(()=>{EDIT_KEYS=new Set(["left","right","wordleft","wordright","linestart","lineend","erase","delete","word","killword","killnext","clear","killend","yank"])});var NONE;var init_score=__esm(()=>{NONE=Number.NEGATIVE_INFINITY});function repeat(value,count){return Array.from({length:count}).fill(value)}function parseKeys(input,paste={active:!1},ctrls=[]){let codes=new Map(ctrls.map((name)=>[String.fromCharCode(name.codePointAt(name.length-1)-96),name]));return(input.match(KEY_SEQUENCES)??[]).flatMap((sequence)=>{let wheel=MOUSE.exec(sequence)?.[1];if(wheel!==void 0)return repeat(wheel==="64"?"up":"down",wheel==="64"||wheel==="65"?WHEEL_LINES:0);let named=codes.get(sequence),key=named===void 0?KEYS[sequence]:{ctrl:named};if(sequence===PASTE_START||sequence===PASTE_END)return paste.active=sequence===PASTE_START,[];if(paste.active&&(sequence==="\r"||sequence===`
|
|
9
|
+
`))return[];if(key!==void 0)return[key];return IS_CONTROL.test(sequence)||sequence.startsWith("\x1B")?[]:[{text:sequence}]})}var IS_CONTROL,PASTE_START="\x1B[200~",PASTE_END="\x1B[201~",KEY_SEQUENCES,MOUSE,WHEEL_LINES=3,KEYS;var init_state=__esm(()=>{init_text2();init_line();init_score();IS_CONTROL=/[\x00-\x1F\x7F-\x9F]/,KEY_SEQUENCES=/\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu,MOUSE=/^\x1B\[<(\d+);\d+;\d+[a-z]$/i,KEYS={"\x1B[A":"up","\x1BOA":"up","\x10":"up","\x1B[B":"down","\x1BOB":"down","\x0E":"down","\x1B[5~":"pageup","\x1B[6~":"pagedown","\x1B[H":"home","\x1B[1~":"home","\x1BOH":"home","\x1B[F":"end","\x1B[4~":"end","\x1BOF":"end","\r":"enter","\n":"enter","\x03":"cancel","\x1B":"cancel","\x1B[D":"left","\x1BOD":"left","\x1B[C":"right","\x1BOC":"right","\x1B[1;5D":"wordleft","\x1B[1;3D":"wordleft","\x1Bb":"wordleft","\x1B[1;5C":"wordright","\x1B[1;3C":"wordright","\x1Bf":"wordright","\x01":"linestart","\x05":"lineend","\x7F":"erase","\x1B[3~":"delete","\b":"killword","\x1B\x7F":"killword","\x1B[3;5~":"killnext","\x1Bd":"killnext","\x15":"clear","\v":"killend","\x17":"word","\x19":"yank","\x1A":"suspend","\t":"tab","\x1F":"help","\x1BOP":"help","\x1B[11~":"help"}});function overwrite(lines,columns){return lines.map((line)=>textWidth(line)%columns===0?`\x1B[2K${line}`:`${line}\x1B[K`).join(`
|
|
10
|
+
`)}function rowsTaken(lines,columns){return lines.reduce((rows,line)=>rows+Math.max(1,Math.ceil(textWidth(line)/columns)),0)}var SYNC_START="\x1B[?2026h",SYNC_END="\x1B[?2026l";var init_redraw=__esm(()=>{init_format()});import process17 from"process";function readKeys(input,paste={active:!1}){return parseKeys(input,paste).filter((key)=>typeof key==="object"?"text"in key:PROMPT_KEYS.has(key)||isEditKey(key))}async function confirm(question,{default:fallback,...settings}={}){let answered=fallback,choices={true:"Y/n",false:"y/N",undefined:"y/n"}[String(fallback)];return await ask(question,settings,(colors,state)=>[state==="asking"?asking(colors,question,"",choices):answer(colors,question,state,answered?"yes":"no")],(key)=>{if(key==="cancel")return"cancel";if(key==="enter")return answered===void 0?void 0:"enter";let letter=typeof key==="object"?key.text.toLowerCase():"";if(letter!=="y"&&letter!=="n")return;return answered=letter==="y","enter"})?answered:void 0}function asking(colors,question,typed,keys){return`${colors.cyan("?")} ${question} ${typed===""?colors.dim(`(${keys})`):typed}`}function answer(colors,question,state,picked){return state==="enter"?`${colors.green("\u2713")} ${question} ${colors.cyan(picked)}`:`${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`}async function ask(question,{hint,terminal=process17},render,press){let{stdin,stderr}=terminal;if(!isInteractive(terminal))fail(`cannot ask "${question}" off a terminal`,2,hint);let colors=paint(stderr),current="asking",outcome,columns=()=>stderr.columns||80,draw=(state,last=!1)=>{let frame=render(colors,state,{columns:columns(),rows:stderr.rows||24}),rows=rowsTaken(frame,columns());stderr.write(`${SYNC_START}\r${overwrite(frame,columns())}\x1B[0J${last||rows<2?"":`\x1B[${rows-1}A`}${last?"":"\r"}${SYNC_END}`),current=state},redraw=()=>draw(current),paste={active:!1},stop=terminal.stop??(terminal===process17?stopJob:void 0),suspend=()=>{if(stop===void 0)return;stderr.write("\x1B[0J\x1B[?25h\x1B[?2004l"),stdin.setRawMode(!1),stop(),stdin.setRawMode(!0),stderr.write("\x1B[?25l\x1B[?2004h")};try{return stderr.on?.("resize",redraw),stdin.setRawMode(!0),stdin.resume(),stderr.write("\x1B[?25l\x1B[?2004h"),draw("asking"),await new Promise((resolve)=>{function onData(data){for(let key of readKeys(data.toString(),paste)){if(key==="suspend"){suspend();continue}let pressed=press(key);if(pressed!==void 0){settle(pressed);return}}draw("asking")}function onEnd(){settle("cancel")}function settle(settled){outcome=settled,stdin.off("data",onData),stdin.off("end",onEnd),resolve(settled==="enter")}stdin.on("data",onData),stdin.on("end",onEnd)})}finally{stderr.off?.("resize",redraw),draw(outcome??"cancel",!0),stderr.write(`
|
|
11
|
+
\x1B[?25h\x1B[?2004l`),stdin.setRawMode(!1),stdin.pause()}}var PROMPT_KEYS;var init_prompt=__esm(()=>{init_answers();init_args();init_format();init_job();init_mode();init_line();init_state();init_redraw();init_style();PROMPT_KEYS=new Set(["up","down","pageup","pagedown","home","end","enter","cancel","suspend","tab"])});import{tmpdir}from"os";import{join as join9}from"path";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_text2();init_theme();init_style();init_format();init_args();import{readFileSync as readFileSync5,realpathSync as realpathSync2}from"fs";import{dirname as dirname3,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)}
|
|
12
|
+
`),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}
|
|
13
|
+
`),0}var COMPLETION_SHELLS=["fish","bash","zsh"];function completionScript(shell,bins,header=`# Generated by \`${bins[0]} --completions ${shell}\``){if(shell==="fish")return`${header}
|
|
14
|
+
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'
|
|
1158
15
|
set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
|
|
1159
16
|
set -l current (commandline -ct)
|
|
1160
17
|
for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
|
|
@@ -1164,8 +21,10 @@ var FISH_FUNCTION = `functions -q __kaynooo_cli_complete; or function __kaynooo_
|
|
|
1164
21
|
echo $line
|
|
1165
22
|
end
|
|
1166
23
|
end
|
|
1167
|
-
end
|
|
1168
|
-
|
|
24
|
+
end
|
|
25
|
+
${bins.map((bin)=>`complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
|
|
26
|
+
`).join("")}`;if(shell==="bash")return`${header}
|
|
27
|
+
__kaynooo_cli_complete() {
|
|
1169
28
|
local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
|
|
1170
29
|
local -a lines
|
|
1171
30
|
COMPREPLY=()
|
|
@@ -1178,8 +37,10 @@ var BASH_FUNCTION = `__kaynooo_cli_complete() {
|
|
|
1178
37
|
fi
|
|
1179
38
|
done
|
|
1180
39
|
COMPREPLY+=($(compgen -W "$words" -- "$cur"))
|
|
1181
|
-
}
|
|
1182
|
-
|
|
40
|
+
}
|
|
41
|
+
complete -F __kaynooo_cli_complete ${bins.join(" ")}
|
|
42
|
+
`;return`${header}
|
|
43
|
+
__kaynooo_cli_complete() {
|
|
1183
44
|
local line
|
|
1184
45
|
local -a described plain
|
|
1185
46
|
for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
|
|
@@ -1202,1837 +63,22 @@ __kaynooo_cli_register() {
|
|
|
1202
63
|
}
|
|
1203
64
|
autoload -Uz add-zsh-hook
|
|
1204
65
|
add-zsh-hook precmd __kaynooo_cli_register
|
|
1205
|
-
typeset -gaU __kaynooo_cli_bins
|
|
1206
|
-
function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
|
|
1207
|
-
if (shell === "fish")
|
|
1208
|
-
return `${header}
|
|
1209
|
-
${FISH_FUNCTION}
|
|
1210
|
-
${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
|
|
1211
|
-
`).join("")}`;
|
|
1212
|
-
if (shell === "bash")
|
|
1213
|
-
return `${header}
|
|
1214
|
-
${BASH_FUNCTION}
|
|
1215
|
-
complete -F __kaynooo_cli_complete ${bins.join(" ")}
|
|
1216
|
-
`;
|
|
1217
|
-
return `${header}
|
|
1218
|
-
${ZSH_FUNCTION}
|
|
66
|
+
typeset -gaU __kaynooo_cli_bins
|
|
1219
67
|
__kaynooo_cli_bins+=(${bins.join(" ")})
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
import process12 from "process";
|
|
1227
|
-
|
|
1228
|
-
var
|
|
1229
|
-
function
|
|
1230
|
-
|
|
1231
|
-
}
|
|
1232
|
-
function notification(title, body, env = process12.env) {
|
|
1233
|
-
const id = `kit${process12.pid}`;
|
|
1234
|
-
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\\`];
|
|
1235
|
-
return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
|
|
1236
|
-
}
|
|
1237
|
-
function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
|
|
1238
|
-
if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
|
|
1239
|
-
return;
|
|
1240
|
-
stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
|
|
1241
|
-
}
|
|
1242
|
-
|
|
1243
|
-
// ../kit/src/cli.ts
|
|
1244
|
-
init_style();
|
|
1245
|
-
init_text2();
|
|
1246
|
-
|
|
1247
|
-
// ../kit/src/usage.ts
|
|
1248
|
-
import { appendFileSync, mkdirSync } from "fs";
|
|
1249
|
-
import { homedir as homedir3 } from "os";
|
|
1250
|
-
import { dirname as dirname2, join as join4 } from "path";
|
|
1251
|
-
import process13 from "process";
|
|
1252
|
-
|
|
1253
|
-
// ../kit/src/logs.ts
|
|
1254
|
-
init_user_config();
|
|
1255
|
-
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
1256
|
-
var CLI_FOLDER = "kaynooo-cli";
|
|
1257
|
-
|
|
1258
|
-
// ../kit/src/usage.ts
|
|
1259
|
-
init_user_config();
|
|
1260
|
-
var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
|
|
1261
|
-
var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
|
|
1262
|
-
var LONGEST_NAME = 40;
|
|
1263
|
-
var usageError;
|
|
1264
|
-
function noteUsageError(message) {
|
|
1265
|
-
usageError = message;
|
|
1266
|
-
}
|
|
1267
|
-
function stateHome(env = process13.env) {
|
|
1268
|
-
return xdgFolder(env.XDG_STATE_HOME, join4(homedir3(), ".local", "state"));
|
|
1269
|
-
}
|
|
1270
|
-
function usagePath(env = process13.env) {
|
|
1271
|
-
return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
1272
|
-
}
|
|
1273
|
-
function usageRecorded(env = process13.env) {
|
|
1274
|
-
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
1275
|
-
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
1276
|
-
}
|
|
1277
|
-
function flagNames(argv) {
|
|
1278
|
-
const end = argv.indexOf("--");
|
|
1279
|
-
const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
|
|
1280
|
-
return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
|
|
1281
|
-
}
|
|
1282
|
-
function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
|
|
1283
|
-
const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
|
|
1284
|
-
usageError = undefined;
|
|
1285
|
-
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
|
|
1286
|
-
}
|
|
1287
|
-
function recordUsage(entry, env = process13.env) {
|
|
1288
|
-
if (!usageRecorded(env))
|
|
1289
|
-
return;
|
|
1290
|
-
try {
|
|
1291
|
-
const path = usagePath(env);
|
|
1292
|
-
mkdirSync(dirname2(path), { recursive: true, mode: 448 });
|
|
1293
|
-
appendFileSync(path, `${JSON.stringify(entry)}
|
|
1294
|
-
`, { mode: 384 });
|
|
1295
|
-
} catch {}
|
|
1296
|
-
}
|
|
1297
|
-
|
|
1298
|
-
// ../kit/src/cli.ts
|
|
1299
|
-
var LEVEL_OPTIONS = {
|
|
1300
|
-
...OUTPUT_OPTIONS,
|
|
1301
|
-
help: { type: "boolean", short: "h", description: "show this help" }
|
|
1302
|
-
};
|
|
1303
|
-
var TOP_OPTIONS = {
|
|
1304
|
-
...LEVEL_OPTIONS,
|
|
1305
|
-
version: { type: "boolean", short: "v", description: "print the version" },
|
|
1306
|
-
completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
|
|
1307
|
-
};
|
|
1308
|
-
async function commandRows(all, colors) {
|
|
1309
|
-
const commands = shown(all);
|
|
1310
|
-
const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
|
|
1311
|
-
const groups = new Map([["Commands:", []]]);
|
|
1312
|
-
const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
|
|
1313
|
-
for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
|
|
1314
|
-
const heading = group === undefined ? "Commands:" : `${group}:`;
|
|
1315
|
-
const rows = groups.get(heading) ?? [];
|
|
1316
|
-
rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`);
|
|
1317
|
-
groups.set(heading, rows);
|
|
1318
|
-
}
|
|
1319
|
-
return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
|
|
1320
|
-
}
|
|
1321
|
-
function shown(commands) {
|
|
1322
|
-
return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
|
|
1323
|
-
}
|
|
1324
|
-
function takeOutputFlags(argv) {
|
|
1325
|
-
let index = 0;
|
|
1326
|
-
for (;index < argv.length; index++) {
|
|
1327
|
-
const word = argv[index];
|
|
1328
|
-
if (word === "--plain")
|
|
1329
|
-
applyOutput(undefined, true);
|
|
1330
|
-
else if (word.startsWith("--color="))
|
|
1331
|
-
applyOutput(word.slice("--color=".length), undefined);
|
|
1332
|
-
else if (word === "--color" && argv[index + 1] !== undefined)
|
|
1333
|
-
applyOutput(argv[++index], undefined);
|
|
1334
|
-
else
|
|
1335
|
-
break;
|
|
1336
|
-
}
|
|
1337
|
-
return argv.slice(index);
|
|
1338
|
-
}
|
|
1339
|
-
async function resolveSummary(summary) {
|
|
1340
|
-
return typeof summary === "string" ? summary : summary();
|
|
1341
|
-
}
|
|
1342
|
-
function lookup({ commands, aliases }, word) {
|
|
1343
|
-
const name = aliases !== undefined && Object.hasOwn(aliases, word) ? aliases[word] ?? word : word;
|
|
1344
|
-
return Object.hasOwn(commands, name) ? commands[name] : undefined;
|
|
1345
|
-
}
|
|
1346
|
-
function scopeOf(commands, extra, aliases) {
|
|
1347
|
-
return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
|
|
1348
|
-
}
|
|
1349
|
-
async function expand(scope, words) {
|
|
1350
|
-
if (scope.lazy.length === 0)
|
|
1351
|
-
return scope;
|
|
1352
|
-
const commands = { ...scope.commands };
|
|
1353
|
-
for (const added of await Promise.all(scope.lazy.map(async (lazy) => lazy(words)))) {
|
|
1354
|
-
for (const [name, command] of Object.entries(added))
|
|
1355
|
-
commands[name] ??= command;
|
|
1356
|
-
}
|
|
1357
|
-
return { ...scope, commands, lazy: [] };
|
|
1358
|
-
}
|
|
1359
|
-
async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
|
|
1360
|
-
const colors = paint(stream);
|
|
1361
|
-
const prefix = path.join(" ");
|
|
1362
|
-
const summary = await resolveSummary(lazySummary);
|
|
1363
|
-
if (wantsHelpJson())
|
|
1364
|
-
return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`, { examples, replaces }));
|
|
1365
|
-
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1366
|
-
const options = fallback !== undefined && "run" in fallback ? await optionsOf(fallback.run) : undefined;
|
|
1367
|
-
const own = Object.entries(options ?? {}).filter(([name]) => !(name in TOP_OPTIONS));
|
|
1368
|
-
return [
|
|
1369
|
-
header(colors, summary),
|
|
1370
|
-
"",
|
|
1371
|
-
usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
|
|
1372
|
-
"",
|
|
1373
|
-
...await commandRows(commands, colors),
|
|
1374
|
-
...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
|
|
1375
|
-
"",
|
|
1376
|
-
colors.bold("Options:"),
|
|
1377
|
-
...optionRows(path.length === 1 ? TOP_OPTIONS : LEVEL_OPTIONS, colors),
|
|
1378
|
-
...exampleRows(examples ?? [], colors),
|
|
1379
|
-
"",
|
|
1380
|
-
`${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`
|
|
1381
|
-
].join(`
|
|
1382
|
-
`);
|
|
1383
|
-
}
|
|
1384
|
-
function printError(prefix, message, hint, cause) {
|
|
1385
|
-
const colors = paint(process14.stderr);
|
|
1386
|
-
const styled = takesControlCodes(process14.stderr);
|
|
1387
|
-
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
1388
|
-
const under = (label, text, tint) => text === undefined ? "" : `
|
|
1389
|
-
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
1390
|
-
console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
|
|
1391
|
-
}
|
|
1392
|
-
function printJsonError(message, hint, cause) {
|
|
1393
|
-
console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
|
|
1394
|
-
}
|
|
1395
|
-
function wantsJson(argv) {
|
|
1396
|
-
const end = argv.indexOf("--");
|
|
1397
|
-
return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
|
|
1398
|
-
}
|
|
1399
|
-
function reportThrown(prefix, error, redact = (text) => text, json = false) {
|
|
1400
|
-
if (error instanceof HelpShown)
|
|
1401
|
-
return 0;
|
|
1402
|
-
const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
|
|
1403
|
-
const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
|
|
1404
|
-
const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
|
|
1405
|
-
if (error instanceof Exit && error.code === 2)
|
|
1406
|
-
noteUsageError(error.message);
|
|
1407
|
-
const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
|
|
1408
|
-
report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
|
|
1409
|
-
return error instanceof Exit ? error.code : 1;
|
|
1410
|
-
}
|
|
1411
|
-
async function dispatch(level, typed, { version, redact }) {
|
|
1412
|
-
const prefix = level.path.join(" ");
|
|
1413
|
-
let argv;
|
|
1414
|
-
try {
|
|
1415
|
-
argv = takeOutputFlags(typed);
|
|
1416
|
-
} catch (error) {
|
|
1417
|
-
return reportThrown(prefix, error);
|
|
1418
|
-
}
|
|
1419
|
-
const [name, ...args] = argv;
|
|
1420
|
-
const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
|
|
1421
|
-
if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
|
|
1422
|
-
try {
|
|
1423
|
-
return await fallback.run([]);
|
|
1424
|
-
} catch (error) {
|
|
1425
|
-
return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
|
|
1426
|
-
}
|
|
1427
|
-
}
|
|
1428
|
-
if (name === undefined && level.path.length > 1) {
|
|
1429
|
-
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stderr));
|
|
1430
|
-
return 2;
|
|
1431
|
-
}
|
|
1432
|
-
if (name === undefined || name === "help" || name === "--help" || name === "-h") {
|
|
1433
|
-
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stdout));
|
|
1434
|
-
return 0;
|
|
1435
|
-
}
|
|
1436
|
-
if (level.path.length === 1 && (name === "--version" || name === "-v")) {
|
|
1437
|
-
console.log(version);
|
|
1438
|
-
return 0;
|
|
1439
|
-
}
|
|
1440
|
-
let command = lookup(level, name);
|
|
1441
|
-
let rest = args;
|
|
1442
|
-
let ran = name;
|
|
1443
|
-
if (command === undefined && level.lazy.length > 0) {
|
|
1444
|
-
level = await expand(level, [...level.path.slice(1), ...argv]);
|
|
1445
|
-
command = lookup(level, name);
|
|
1446
|
-
}
|
|
1447
|
-
if (command === undefined && level.defaultCommand !== undefined) {
|
|
1448
|
-
command = level.commands[level.defaultCommand];
|
|
1449
|
-
rest = argv;
|
|
1450
|
-
ran = level.defaultCommand;
|
|
1451
|
-
}
|
|
1452
|
-
if (command === undefined) {
|
|
1453
|
-
const meant = closest(name, Object.keys(shown(level.commands)));
|
|
1454
|
-
printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
|
|
1455
|
-
return 2;
|
|
1456
|
-
}
|
|
1457
|
-
if ("commands" in command) {
|
|
1458
|
-
const { summary } = command;
|
|
1459
|
-
return dispatch({ path: [...level.path, name], header: (colors, text) => `${colors.bold(`${prefix} ${name}`)} ${text}`, summary, ...scopeOf(command.commands, command.extraCommands, command.aliases), defaultCommand: undefined, runBare: false, examples: command.examples, replaces: undefined }, rest, { version, redact });
|
|
1460
|
-
}
|
|
1461
|
-
try {
|
|
1462
|
-
return await command.run(rest);
|
|
1463
|
-
} catch (error) {
|
|
1464
|
-
return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
|
|
1465
|
-
}
|
|
1466
|
-
}
|
|
1467
|
-
var COMPLETE = "__complete";
|
|
1468
|
-
var FILES = "__files__";
|
|
1469
|
-
async function completingOf(run) {
|
|
1470
|
-
completion.active = true;
|
|
1471
|
-
try {
|
|
1472
|
-
await run([]);
|
|
1473
|
-
} catch (error) {
|
|
1474
|
-
if (error instanceof Completing)
|
|
1475
|
-
return error;
|
|
1476
|
-
} finally {
|
|
1477
|
-
completion.active = false;
|
|
1478
|
-
}
|
|
1479
|
-
return new Completing({});
|
|
1480
|
-
}
|
|
1481
|
-
async function optionsOf(run) {
|
|
1482
|
-
return (await completingOf(run)).options;
|
|
1483
|
-
}
|
|
1484
|
-
function candidateLine(candidate) {
|
|
1485
|
-
return typeof candidate === "string" ? candidate : candidate.join("\t");
|
|
1486
|
-
}
|
|
1487
|
-
function positionalBeingTyped(before, { options, positionals }) {
|
|
1488
|
-
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
1489
|
-
const typed = [];
|
|
1490
|
-
let at = 0;
|
|
1491
|
-
while (at < before.length) {
|
|
1492
|
-
const word = before[at];
|
|
1493
|
-
if (word === "--") {
|
|
1494
|
-
typed.push(...before.slice(at + 1));
|
|
1495
|
-
break;
|
|
1496
|
-
}
|
|
1497
|
-
if (!word.startsWith("-"))
|
|
1498
|
-
typed.push(word);
|
|
1499
|
-
else if (takesValue(word))
|
|
1500
|
-
at++;
|
|
1501
|
-
at++;
|
|
1502
|
-
}
|
|
1503
|
-
const last = positionals.at(-1);
|
|
1504
|
-
if (typed.length < positionals.length)
|
|
1505
|
-
return { name: positionals[typed.length], typed };
|
|
1506
|
-
return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
|
|
1507
|
-
}
|
|
1508
|
-
async function leafCandidates(run, words) {
|
|
1509
|
-
const completing = await completingOf(run);
|
|
1510
|
-
if ((words.at(-1) ?? "").startsWith("-"))
|
|
1511
|
-
return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
|
|
1512
|
-
const flag = words.at(-2);
|
|
1513
|
-
const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
|
|
1514
|
-
const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
|
|
1515
|
-
if (option?.type === "string") {
|
|
1516
|
-
const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
|
|
1517
|
-
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1518
|
-
}
|
|
1519
|
-
const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
|
|
1520
|
-
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1521
|
-
}
|
|
1522
|
-
async function candidates(scope, defaultCommand, words, before = []) {
|
|
1523
|
-
const [word = "", ...rest] = words;
|
|
1524
|
-
const listing = rest.length === 0 && !word.startsWith("-");
|
|
1525
|
-
let { commands } = scope;
|
|
1526
|
-
let command = lookup(scope, word);
|
|
1527
|
-
if (listing || command === undefined) {
|
|
1528
|
-
const expanded = await expand(scope, [...before, ...words]);
|
|
1529
|
-
commands = expanded.commands;
|
|
1530
|
-
command = lookup(expanded, word);
|
|
1531
|
-
}
|
|
1532
|
-
if (listing) {
|
|
1533
|
-
const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
|
|
1534
|
-
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1535
|
-
const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
|
|
1536
|
-
const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
|
|
1537
|
-
return [...own, ...values.filter((line) => line !== FILES && !Object.hasOwn(commands, valueOf(line)))];
|
|
1538
|
-
}
|
|
1539
|
-
if (command === undefined) {
|
|
1540
|
-
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1541
|
-
return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
|
|
1542
|
-
}
|
|
1543
|
-
return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
|
|
1544
|
-
}
|
|
1545
|
-
var COMPLETIONS = "--completions";
|
|
1546
|
-
function flagValue([flag = "", ...rest]) {
|
|
1547
|
-
return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
|
|
1548
|
-
}
|
|
1549
|
-
function printCompletionScript(name, args) {
|
|
1550
|
-
const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
|
|
1551
|
-
if (shell === undefined || args.length !== 1) {
|
|
1552
|
-
printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
|
|
1553
|
-
return 2;
|
|
1554
|
-
}
|
|
1555
|
-
console.log(completionScript(shell, [name]).trimEnd());
|
|
1556
|
-
return 0;
|
|
1557
|
-
}
|
|
1558
|
-
async function printCandidates(found) {
|
|
1559
|
-
for (const line of await found)
|
|
1560
|
-
console.log(line);
|
|
1561
|
-
return 0;
|
|
1562
|
-
}
|
|
1563
|
-
function packageVersion(entry = Bun.main) {
|
|
1564
|
-
let resolved = entry;
|
|
1565
|
-
try {
|
|
1566
|
-
resolved = realpathSync2(entry);
|
|
1567
|
-
} catch {}
|
|
1568
|
-
for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
|
|
1569
|
-
try {
|
|
1570
|
-
const { version } = JSON.parse(readFileSync4(join5(dir, "package.json"), "utf8"));
|
|
1571
|
-
if (typeof version === "string")
|
|
1572
|
-
return version;
|
|
1573
|
-
} catch {}
|
|
1574
|
-
if (dirname3(dir) === dir)
|
|
1575
|
-
return "0.0.0";
|
|
1576
|
-
}
|
|
1577
|
-
}
|
|
1578
|
-
async function runCli(cli, argv = scriptArgs()) {
|
|
1579
|
-
const version = cli.version ?? packageVersion();
|
|
1580
|
-
const answered = await askpassClient(argv);
|
|
1581
|
-
if (answered !== undefined)
|
|
1582
|
-
return answered;
|
|
1583
|
-
if (argv[0] === COMPLETE)
|
|
1584
|
-
return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
|
|
1585
|
-
if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
|
|
1586
|
-
return printCompletionScript(cli.name, flagValue(argv));
|
|
1587
|
-
const started = performance.now();
|
|
1588
|
-
const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, runBare: cli.runBare === true, examples: cli.examples, replaces: cli.replaces }, argv, { version, redact: cli.redact });
|
|
1589
|
-
const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
|
|
1590
|
-
notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
|
|
1591
|
-
if (cli.usage !== false) {
|
|
1592
|
-
try {
|
|
1593
|
-
recordUsage(usageEntry(cli.name, command, argv, code, { ms: performance.now() - started }));
|
|
1594
|
-
} catch {}
|
|
1595
|
-
}
|
|
1596
|
-
return code;
|
|
1597
|
-
}
|
|
1598
|
-
function commandPath(scope, argv) {
|
|
1599
|
-
const path = [];
|
|
1600
|
-
let level = scope;
|
|
1601
|
-
for (const word of argv.filter((each) => !each.startsWith("-"))) {
|
|
1602
|
-
const command = lookup(level, word);
|
|
1603
|
-
if (command === undefined)
|
|
1604
|
-
break;
|
|
1605
|
-
path.push(word);
|
|
1606
|
-
if (!("commands" in command))
|
|
1607
|
-
break;
|
|
1608
|
-
level = scopeOf(command.commands, command.extraCommands, command.aliases);
|
|
1609
|
-
}
|
|
1610
|
-
return path.length === 0 ? undefined : path.join(" ");
|
|
1611
|
-
}
|
|
1612
|
-
|
|
1613
|
-
// ../kit/src/index.ts
|
|
1614
|
-
init_config();
|
|
1615
|
-
|
|
1616
|
-
// ../kit/src/excerpt.ts
|
|
1617
|
-
init_text2();
|
|
1618
|
-
|
|
1619
|
-
// ../kit/src/index.ts
|
|
1620
|
-
init_folders();
|
|
1621
|
-
init_format();
|
|
1622
|
-
|
|
1623
|
-
// ../kit/src/git.ts
|
|
1624
|
-
init_args();
|
|
1625
|
-
// ../kit/src/limit.ts
|
|
1626
|
-
init_args();
|
|
1627
|
-
|
|
1628
|
-
// ../kit/src/index.ts
|
|
1629
|
-
init_mode();
|
|
1630
|
-
|
|
1631
|
-
// ../kit/src/report.ts
|
|
1632
|
-
init_style();
|
|
1633
|
-
init_text2();
|
|
1634
|
-
// ../kit/src/secrets.ts
|
|
1635
|
-
var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
|
|
1636
|
-
var NOT_PASSWORDS = new Set(["compass", "encompass", "bypass", "overpass", "underpass", "surpass", "trespass"]);
|
|
1637
|
-
// ../kit/src/sessions.ts
|
|
1638
|
-
var {Glob } = globalThis.Bun;
|
|
1639
|
-
var SESSION_FILES = new Glob("*.json");
|
|
1640
|
-
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
1641
|
-
|
|
1642
|
-
// ../kit/src/index.ts
|
|
1643
|
-
init_style();
|
|
1644
|
-
init_text2();
|
|
1645
|
-
init_theme();
|
|
1646
|
-
init_user_config();
|
|
1647
|
-
|
|
1648
|
-
// ../kit/src/watch.ts
|
|
1649
|
-
init_args();
|
|
1650
|
-
init_input();
|
|
1651
|
-
init_style();
|
|
1652
|
-
// ../kit/src/workspace-root.ts
|
|
1653
|
-
init_user_config();
|
|
1654
|
-
// src/cli.ts
|
|
1655
|
-
init_prompt();
|
|
1656
|
-
|
|
1657
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-3624x5ew.js
|
|
1658
|
-
init_chunk_yfkscv18();
|
|
1659
|
-
var W2 = 1000;
|
|
1660
|
-
var ht = 60 * W2;
|
|
1661
|
-
var Ue = 60 * ht;
|
|
1662
|
-
var S = 24 * Ue;
|
|
1663
|
-
var ei = 7 * S;
|
|
1664
|
-
var p = new Map;
|
|
1665
|
-
var Y = [[n.y, "year"], [n.M, "month"], [n.w, "week"], [n.d, "day"], [n.h, "hour"], [n.m, "minute"], [n.s, "second"]];
|
|
1666
|
-
|
|
1667
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-1nmct6ry.js
|
|
1668
|
-
var T = 15 * W2;
|
|
1669
|
-
function l(e, n) {
|
|
1670
|
-
if (n === undefined)
|
|
1671
|
-
return e ?? undefined;
|
|
1672
|
-
let t = AbortSignal.timeout(n);
|
|
1673
|
-
return e ? AbortSignal.any([e, t]) : t;
|
|
1674
|
-
}
|
|
1675
|
-
|
|
1676
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-1dqf2hrj.js
|
|
1677
|
-
function w(e) {
|
|
1678
|
-
if (typeof e !== "object" || e === null)
|
|
1679
|
-
return false;
|
|
1680
|
-
let n = Object.getPrototypeOf(e);
|
|
1681
|
-
return n === Object.prototype || n === null;
|
|
1682
|
-
}
|
|
1683
|
-
|
|
1684
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-sgh0r8t7.js
|
|
1685
|
-
function J(e, { signal: n } = {}) {
|
|
1686
|
-
return new Promise((t, o) => {
|
|
1687
|
-
if (n?.aborted)
|
|
1688
|
-
return o(n.reason);
|
|
1689
|
-
let r = setTimeout(() => {
|
|
1690
|
-
n?.removeEventListener("abort", s), t();
|
|
1691
|
-
}, e);
|
|
1692
|
-
function s() {
|
|
1693
|
-
clearTimeout(r), o(n.reason);
|
|
1694
|
-
}
|
|
1695
|
-
n?.addEventListener("abort", s, { once: true });
|
|
1696
|
-
});
|
|
1697
|
-
}
|
|
1698
|
-
|
|
1699
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-8xadcg99.js
|
|
1700
|
-
init_chunk_rkhsft4a();
|
|
1701
|
-
async function ae(r, { attempts: t = 3, delay: s = 1000, backoff: m = 2, maxDelay: o = 1 / 0, jitter: i = false, shouldRetry: a, onRetry: u, signal: l } = {}) {
|
|
1702
|
-
let c = i === true ? 1 : Number(i), e;
|
|
1703
|
-
for (let n = 0;n < t + 1; n++) {
|
|
1704
|
-
l?.throwIfAborted();
|
|
1705
|
-
try {
|
|
1706
|
-
return await r(n);
|
|
1707
|
-
} catch (f) {
|
|
1708
|
-
if (e = f, a && !a(f, n))
|
|
1709
|
-
throw f;
|
|
1710
|
-
if (n < t) {
|
|
1711
|
-
let p = Math.min(s * m ** n, o) * (1 - c * Math.random());
|
|
1712
|
-
u?.(f, n, p), await J(p, { signal: l });
|
|
1713
|
-
}
|
|
1714
|
-
}
|
|
1715
|
-
}
|
|
1716
|
-
throw Error(`Failed after ${t} ${G("retry", t)}`, { cause: e });
|
|
1717
|
-
}
|
|
1718
|
-
|
|
1719
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-4faezqnz.js
|
|
1720
|
-
function s(...e) {
|
|
1721
|
-
let r = new Headers;
|
|
1722
|
-
for (let n of e) {
|
|
1723
|
-
if (!n)
|
|
1724
|
-
continue;
|
|
1725
|
-
let i;
|
|
1726
|
-
if (n instanceof Headers)
|
|
1727
|
-
i = [...n];
|
|
1728
|
-
else
|
|
1729
|
-
i = Array.isArray(n) ? n : Object.entries(n);
|
|
1730
|
-
for (let [a, t] of i)
|
|
1731
|
-
if (t !== undefined)
|
|
1732
|
-
r.set(a, t);
|
|
1733
|
-
}
|
|
1734
|
-
return r;
|
|
1735
|
-
}
|
|
1736
|
-
function T2(e) {
|
|
1737
|
-
return w(e) || Array.isArray(e);
|
|
1738
|
-
}
|
|
1739
|
-
function J2(e) {
|
|
1740
|
-
return typeof e === "string" || e instanceof ArrayBuffer || ArrayBuffer.isView(e) || e instanceof FormData || e instanceof URLSearchParams || e instanceof ReadableStream || typeof Blob < "u" && e instanceof Blob;
|
|
1741
|
-
}
|
|
1742
|
-
var b3 = "http://relative.invalid";
|
|
1743
|
-
function I(e) {
|
|
1744
|
-
try {
|
|
1745
|
-
return { parsed: new URL(e), relative: false };
|
|
1746
|
-
} catch {
|
|
1747
|
-
return { parsed: new URL(e, b3), relative: true };
|
|
1748
|
-
}
|
|
1749
|
-
}
|
|
1750
|
-
function B2(e, r) {
|
|
1751
|
-
if (!r)
|
|
1752
|
-
return e;
|
|
1753
|
-
let { parsed: n, relative: i } = I(e);
|
|
1754
|
-
for (let [t, o] of Object.entries(r))
|
|
1755
|
-
for (let u of Array.isArray(o) ? o : [o])
|
|
1756
|
-
if (u !== undefined)
|
|
1757
|
-
n.searchParams.append(t, String(u));
|
|
1758
|
-
if (!i)
|
|
1759
|
-
return n.href;
|
|
1760
|
-
let a = `${n.pathname}${n.search}${n.hash}`;
|
|
1761
|
-
return n.origin === b3 ? a : `//${n.host}${a}`;
|
|
1762
|
-
}
|
|
1763
|
-
function E(e) {
|
|
1764
|
-
if (!e)
|
|
1765
|
-
return;
|
|
1766
|
-
try {
|
|
1767
|
-
return JSON.parse(e);
|
|
1768
|
-
} catch {
|
|
1769
|
-
return;
|
|
1770
|
-
}
|
|
1771
|
-
}
|
|
1772
|
-
function v(e) {
|
|
1773
|
-
if (!w(e))
|
|
1774
|
-
return;
|
|
1775
|
-
for (let r of ["error", "message", "detail"])
|
|
1776
|
-
if (typeof e[r] === "string" && e[r])
|
|
1777
|
-
return e[r];
|
|
1778
|
-
return;
|
|
1779
|
-
}
|
|
1780
|
-
|
|
1781
|
-
class ie extends Error {
|
|
1782
|
-
status;
|
|
1783
|
-
statusText;
|
|
1784
|
-
url;
|
|
1785
|
-
body;
|
|
1786
|
-
data;
|
|
1787
|
-
said;
|
|
1788
|
-
constructor(e, r, n, i, a) {
|
|
1789
|
-
let t = v(a), o = t ?? i;
|
|
1790
|
-
super(`HTTP ${e} ${r} - ${n}${o ? ` - ${o}` : ""}`);
|
|
1791
|
-
this.status = e;
|
|
1792
|
-
this.statusText = r;
|
|
1793
|
-
this.url = n;
|
|
1794
|
-
this.body = i;
|
|
1795
|
-
this.data = a;
|
|
1796
|
-
this.name = "FetchError", this.said = t;
|
|
1797
|
-
}
|
|
1798
|
-
}
|
|
1799
|
-
async function x(e, r) {
|
|
1800
|
-
let n;
|
|
1801
|
-
try {
|
|
1802
|
-
n = await e.text();
|
|
1803
|
-
} catch {
|
|
1804
|
-
n = "";
|
|
1805
|
-
}
|
|
1806
|
-
return new ie(e.status, e.statusText, e.url || r, n || undefined, E(n));
|
|
1807
|
-
}
|
|
1808
|
-
|
|
1809
|
-
class _e extends Error {
|
|
1810
|
-
url;
|
|
1811
|
-
body;
|
|
1812
|
-
constructor(e, r, n) {
|
|
1813
|
-
super(`Invalid JSON response from ${e} - ${r.slice(0, 200)}`, { cause: n });
|
|
1814
|
-
this.url = e;
|
|
1815
|
-
this.body = r;
|
|
1816
|
-
this.name = "FetchParseError";
|
|
1817
|
-
}
|
|
1818
|
-
}
|
|
1819
|
-
function q(e) {
|
|
1820
|
-
if (e instanceof ie)
|
|
1821
|
-
return e.status === 408 || e.status === 429 || e.status >= 500;
|
|
1822
|
-
return e instanceof TypeError || e instanceof DOMException && e.name === "TimeoutError";
|
|
1823
|
-
}
|
|
1824
|
-
async function c(e, r = {}) {
|
|
1825
|
-
let { retry: n, onError: i, ...a } = r, { signal: t } = a;
|
|
1826
|
-
try {
|
|
1827
|
-
let o = H2(e, a);
|
|
1828
|
-
if (!n)
|
|
1829
|
-
return await m(o);
|
|
1830
|
-
let { attempts: u = 3, shouldRetry: d = q, ...f } = typeof n === "number" ? { attempts: n } : n;
|
|
1831
|
-
return await ae(() => m(o), { ...f, attempts: u, signal: t ?? undefined, shouldRetry: (p, y) => y < u && !t?.aborted && d(p, y) });
|
|
1832
|
-
} catch (o) {
|
|
1833
|
-
throw i?.(o), o;
|
|
1834
|
-
}
|
|
1835
|
-
}
|
|
1836
|
-
function A(e, r, n) {
|
|
1837
|
-
if (e === undefined || e === null)
|
|
1838
|
-
return null;
|
|
1839
|
-
return r ? n(e) : e;
|
|
1840
|
-
}
|
|
1841
|
-
function H2(e, r) {
|
|
1842
|
-
let { baseUrl: n, token: i, query: a, body: t, headers: o, timeout: u, signal: d, onResponse: f, fetch: p = fetch, parse: y = JSON.parse, serialize: R = JSON.stringify, ...k } = r, g = B2(n ? new URL(e, n).href : e, a), h = T2(t);
|
|
1843
|
-
if (t !== undefined && t !== null && !h && !J2(t))
|
|
1844
|
-
throw TypeError(`Unsupported body type for ${g}: ${Object.getPrototypeOf(t)?.constructor?.name ?? typeof t}`);
|
|
1845
|
-
let O = s({ Accept: "application/json", "Content-Type": h ? "application/json" : undefined, Authorization: i ? `Bearer ${i}` : undefined }, o);
|
|
1846
|
-
return { fullUrl: g, init: { ...k, headers: O, body: A(t, h, R) }, fetcher: p, parse: y, onResponse: f, timeout: u, signal: d };
|
|
1847
|
-
}
|
|
1848
|
-
async function m({ fullUrl: e, init: r, fetcher: n, parse: i, onResponse: a, timeout: t, signal: o }) {
|
|
1849
|
-
let u = l(o, t), d = await n(e, { ...r, ...u ? { signal: u } : {} });
|
|
1850
|
-
if (a?.(d), !d.ok)
|
|
1851
|
-
throw await x(d, e);
|
|
1852
|
-
let f = await d.text();
|
|
1853
|
-
if (!f)
|
|
1854
|
-
return null;
|
|
1855
|
-
try {
|
|
1856
|
-
return i(f);
|
|
1857
|
-
} catch (p) {
|
|
1858
|
-
throw new _e(d.url || e, f, p);
|
|
1859
|
-
}
|
|
1860
|
-
}
|
|
1861
|
-
|
|
1862
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-dzf6hacc.js
|
|
1863
|
-
async function cr(r, t, o = [], s = {}) {
|
|
1864
|
-
let n = new FormData;
|
|
1865
|
-
n.append("payload_json", JSON.stringify(t));
|
|
1866
|
-
for (let e = 0;e < o.length; ++e) {
|
|
1867
|
-
let i = o[e], p = new Blob([new Uint8Array(i.buffer)], { type: i.contentType ?? "image/png" });
|
|
1868
|
-
n.append(`files[${e}]`, p, i.filename);
|
|
1869
|
-
}
|
|
1870
|
-
return await c(r, { ...s, timeout: s.timeout ?? T, method: "POST", body: n });
|
|
1871
|
-
}
|
|
1872
|
-
// package.json
|
|
1873
|
-
var version = "2.4.1";
|
|
1874
|
-
|
|
1875
|
-
// src/flags.ts
|
|
1876
|
-
var shared = {
|
|
1877
|
-
token: { type: "string", description: "The forge's token, defaults to GITHUB_TOKEN, then on GitHub to gh's login" },
|
|
1878
|
-
from: { type: "string", description: "From tag" },
|
|
1879
|
-
to: { type: "string", description: "To tag" },
|
|
1880
|
-
repo: { type: "string", short: "r", description: "Repository, e.g. kaynooo/cli, origin's by default (--gitea is kept as an alias)" },
|
|
1881
|
-
"release-repo": { type: "string", description: "Release repository, defaults to --repo (--release-gitea is kept as an alias)" },
|
|
1882
|
-
name: { type: "string", description: "Name of the release" },
|
|
1883
|
-
contributors: { type: "boolean", description: "Show contributors" },
|
|
1884
|
-
prerelease: { type: "boolean", description: "Mark release as prerelease" },
|
|
1885
|
-
draft: { type: "boolean", short: "d", description: "Mark release as draft" },
|
|
1886
|
-
output: { type: "string", description: "Output to file instead of sending to the forge" },
|
|
1887
|
-
capitalize: { type: "boolean", description: "Capitalize each commit message" },
|
|
1888
|
-
emoji: { type: "boolean", description: "Use emojis in section titles, --no-emoji to drop them" },
|
|
1889
|
-
group: { type: "boolean", description: "Nest commit messages under their scopes" },
|
|
1890
|
-
"first-parent": { type: "boolean", description: "Walk only the first parent of each merge" },
|
|
1891
|
-
"discord-webhook": { type: "string", description: "Discord webhook to post the release to, defaults to DISCORD_WEBHOOK" },
|
|
1892
|
-
"dry-run": { type: "boolean", description: "Dry run (--dry is kept as an alias)" },
|
|
1893
|
-
assets: { type: "string", multiple: true, description: "Files to upload as assets to the release, repeatable or comma separated; quote globs, e.g. --assets 'dist/*.js'" },
|
|
1894
|
-
json: jsonOption("release: {command, status, from, to, commits, notes, url, output, assetsFailed, discord}; undo: {command, status, tag, releaseNote, remoteTag, localTag, commitReset}. Progress goes to stderr"),
|
|
1895
|
-
debug: { type: "boolean", description: "Print the stack of an unexpected error" }
|
|
1896
|
-
};
|
|
1897
|
-
var undoFlags = {
|
|
1898
|
-
...shared,
|
|
1899
|
-
note: { type: "boolean", description: "Also delete the release note on the forge (skips the question)" },
|
|
1900
|
-
yes: { type: "boolean", description: "Skip confirmation prompts" }
|
|
1901
|
-
};
|
|
1902
|
-
var ALIASES = {
|
|
1903
|
-
"--dry": "--dry-run",
|
|
1904
|
-
"--gitea": "--repo",
|
|
1905
|
-
"--release-gitea": "--release-repo"
|
|
1906
|
-
};
|
|
1907
|
-
function aliasFlags(argv) {
|
|
1908
|
-
const end = argv.indexOf("--");
|
|
1909
|
-
const head = end === -1 ? argv : argv.slice(0, end);
|
|
1910
|
-
return [...head.map((word) => {
|
|
1911
|
-
const [name = "", ...value] = word.split("=");
|
|
1912
|
-
const current = ALIASES[name];
|
|
1913
|
-
return current === undefined ? word : [current, ...value].join("=");
|
|
1914
|
-
}), ...end === -1 ? [] : argv.slice(end)];
|
|
1915
|
-
}
|
|
1916
|
-
function defined(values) {
|
|
1917
|
-
return Object.fromEntries(Object.entries(values).filter(([, value]) => value !== undefined));
|
|
1918
|
-
}
|
|
1919
|
-
function toOptions(args) {
|
|
1920
|
-
return defined({
|
|
1921
|
-
token: args.token,
|
|
1922
|
-
from: args.from,
|
|
1923
|
-
to: args.to,
|
|
1924
|
-
repo: args.repo,
|
|
1925
|
-
releaseRepo: args["release-repo"],
|
|
1926
|
-
name: args.name,
|
|
1927
|
-
contributors: args.contributors,
|
|
1928
|
-
prerelease: args.prerelease,
|
|
1929
|
-
draft: args.draft,
|
|
1930
|
-
output: args.output,
|
|
1931
|
-
capitalize: args.capitalize,
|
|
1932
|
-
emoji: args.emoji,
|
|
1933
|
-
group: args.group,
|
|
1934
|
-
firstParent: args["first-parent"],
|
|
1935
|
-
discordWebhook: args["discord-webhook"],
|
|
1936
|
-
dry: args["dry-run"],
|
|
1937
|
-
assets: args.assets
|
|
1938
|
-
});
|
|
1939
|
-
}
|
|
1940
|
-
function withToken(options) {
|
|
1941
|
-
const token = [options.token, process.env.GITHUB_TOKEN].find((value) => value !== undefined && value !== "");
|
|
1942
|
-
return token === undefined ? options : { ...options, token };
|
|
1943
|
-
}
|
|
1944
|
-
function shouldAskNote({ release, note, yes, dry }) {
|
|
1945
|
-
return Boolean(release) && note !== true && yes !== true && dry !== true;
|
|
1946
|
-
}
|
|
1947
|
-
|
|
1948
|
-
// src/gitea.ts
|
|
1949
|
-
import path from "path";
|
|
1950
|
-
|
|
1951
|
-
// src/ui.ts
|
|
1952
|
-
var out = () => paint(process.stdout);
|
|
1953
|
-
var err = () => paint(process.stderr);
|
|
1954
|
-
async function stdoutToStderr(active, body) {
|
|
1955
|
-
const log = console.log;
|
|
1956
|
-
if (active)
|
|
1957
|
-
console.log = (...args) => console.error(...args.length === 0 ? [""] : args);
|
|
1958
|
-
try {
|
|
1959
|
-
return await body();
|
|
1960
|
-
} finally {
|
|
1961
|
-
console.log = log;
|
|
1962
|
-
}
|
|
1963
|
-
}
|
|
1964
|
-
|
|
1965
|
-
// src/gitea.ts
|
|
1966
|
-
var REQUEST_MS = 60000;
|
|
1967
|
-
function onGithub(options) {
|
|
1968
|
-
return options.provider === "github";
|
|
1969
|
-
}
|
|
1970
|
-
function tagPath(options, repo, tag, write = false) {
|
|
1971
|
-
return onGithub(options) ? `repos/${repo}/git/${write ? "refs" : "ref"}/tags/${encodeURIComponent(tag)}` : `repos/${repo}/tags/${encodeURIComponent(tag)}`;
|
|
1972
|
-
}
|
|
1973
|
-
async function request(url, init) {
|
|
1974
|
-
const res = await fetch(url, { ...init, signal: AbortSignal.timeout(REQUEST_MS) });
|
|
1975
|
-
if (!res.ok)
|
|
1976
|
-
throw new Error(`${res.status} ${res.statusText}: ${await res.text()}`);
|
|
1977
|
-
return res;
|
|
1978
|
-
}
|
|
1979
|
-
async function api(url, init) {
|
|
1980
|
-
return await (await request(url, init)).json();
|
|
1981
|
-
}
|
|
1982
|
-
async function sendRelease(options, content) {
|
|
1983
|
-
const headers = getHeaders(options);
|
|
1984
|
-
let url = `https://${options.baseUrlApi}/repos/${options.releaseRepo}/releases`;
|
|
1985
|
-
let method = "POST";
|
|
1986
|
-
try {
|
|
1987
|
-
const exists = await api(`https://${options.baseUrlApi}/repos/${options.releaseRepo}/releases/tags/${encodeURIComponent(options.to ?? "")}`, {
|
|
1988
|
-
headers
|
|
1989
|
-
});
|
|
1990
|
-
if (exists.url) {
|
|
1991
|
-
url = exists.url;
|
|
1992
|
-
method = "PATCH";
|
|
1993
|
-
}
|
|
1994
|
-
} catch {}
|
|
1995
|
-
const body = {
|
|
1996
|
-
body: content,
|
|
1997
|
-
draft: options.draft || false,
|
|
1998
|
-
name: options.name ?? options.to,
|
|
1999
|
-
prerelease: options.prerelease,
|
|
2000
|
-
tag_name: options.to
|
|
2001
|
-
};
|
|
2002
|
-
console.log(out().cyan(method === "POST" ? "Creating release notes..." : "Updating release notes..."));
|
|
2003
|
-
const res = await api(url, {
|
|
2004
|
-
method,
|
|
2005
|
-
body: JSON.stringify(body),
|
|
2006
|
-
headers: { ...headers, "content-type": "application/json" }
|
|
2007
|
-
});
|
|
2008
|
-
console.log(out().green(`Released on ${res.html_url}`));
|
|
2009
|
-
return res.html_url;
|
|
2010
|
-
}
|
|
2011
|
-
async function getRelease(options, tag) {
|
|
2012
|
-
try {
|
|
2013
|
-
return await api(`https://${options.baseUrlApi}/repos/${options.releaseRepo}/releases/tags/${encodeURIComponent(tag)}`, {
|
|
2014
|
-
headers: getHeaders(options)
|
|
2015
|
-
});
|
|
2016
|
-
} catch {
|
|
2017
|
-
return null;
|
|
2018
|
-
}
|
|
2019
|
-
}
|
|
2020
|
-
async function deleteRelease(options, releaseId) {
|
|
2021
|
-
await request(`https://${options.baseUrlApi}/repos/${options.releaseRepo}/releases/${releaseId}`, {
|
|
2022
|
-
method: "DELETE",
|
|
2023
|
-
headers: getHeaders(options)
|
|
2024
|
-
});
|
|
2025
|
-
}
|
|
2026
|
-
async function hasRemoteTag(options, tag) {
|
|
2027
|
-
try {
|
|
2028
|
-
await api(`https://${options.baseUrlApi}/${tagPath(options, options.releaseRepo, tag)}`, {
|
|
2029
|
-
headers: getHeaders(options)
|
|
2030
|
-
});
|
|
2031
|
-
return true;
|
|
2032
|
-
} catch {
|
|
2033
|
-
return false;
|
|
2034
|
-
}
|
|
2035
|
-
}
|
|
2036
|
-
async function deleteRemoteTag(options, tag) {
|
|
2037
|
-
await request(`https://${options.baseUrlApi}/${tagPath(options, options.releaseRepo, tag, true)}`, {
|
|
2038
|
-
method: "DELETE",
|
|
2039
|
-
headers: getHeaders(options)
|
|
2040
|
-
});
|
|
2041
|
-
}
|
|
2042
|
-
function getHeaders(options) {
|
|
2043
|
-
if (onGithub(options))
|
|
2044
|
-
return { accept: "application/vnd.github+json", authorization: `Bearer ${options.token}`, "x-github-api-version": "2022-11-28" };
|
|
2045
|
-
return {
|
|
2046
|
-
accept: "application/vnd.gitea.v3+json",
|
|
2047
|
-
authorization: `token ${options.token}`
|
|
2048
|
-
};
|
|
2049
|
-
}
|
|
2050
|
-
var excludeAuthors = [
|
|
2051
|
-
/\[bot\]/i,
|
|
2052
|
-
/dependabot/i,
|
|
2053
|
-
/\(bot\)/i
|
|
2054
|
-
];
|
|
2055
|
-
async function resolveAuthorInfo(options, info) {
|
|
2056
|
-
if ((info.login ?? "") !== "")
|
|
2057
|
-
return info;
|
|
2058
|
-
if ((options.token ?? "") === "")
|
|
2059
|
-
return info;
|
|
2060
|
-
if (info.commits.length) {
|
|
2061
|
-
try {
|
|
2062
|
-
const data = await api(`https://${options.baseUrlApi}/repos/${options.repo}/${onGithub(options) ? "commits" : "git/commits"}/${info.commits[0]}`, {
|
|
2063
|
-
headers: getHeaders(options)
|
|
2064
|
-
});
|
|
2065
|
-
if (data.author !== null) {
|
|
2066
|
-
info.login = data.author.login;
|
|
2067
|
-
info.avatar = data.author.avatar_url;
|
|
2068
|
-
}
|
|
2069
|
-
} catch {}
|
|
2070
|
-
}
|
|
2071
|
-
if ((info.login ?? "") !== "" || onGithub(options))
|
|
2072
|
-
return info;
|
|
2073
|
-
try {
|
|
2074
|
-
const data = await api(`https://${options.baseUrlApi}/users/search?q=${encodeURIComponent(info.email)}`, {
|
|
2075
|
-
headers: getHeaders(options)
|
|
2076
|
-
});
|
|
2077
|
-
const user = data.data.find((user) => user.email.toLowerCase() === info.email.toLowerCase());
|
|
2078
|
-
if (user !== undefined) {
|
|
2079
|
-
info.login = user.login;
|
|
2080
|
-
if (user.avatar_url !== undefined)
|
|
2081
|
-
info.avatar = user.avatar_url;
|
|
2082
|
-
}
|
|
2083
|
-
} catch {}
|
|
2084
|
-
return info;
|
|
2085
|
-
}
|
|
2086
|
-
async function resolveAuthors(commits, options) {
|
|
2087
|
-
const map = new Map;
|
|
2088
|
-
for (const commit of commits) {
|
|
2089
|
-
for (const [idx, author] of commit.authors.entries()) {
|
|
2090
|
-
if (!author.email || !author.name || excludeAuthors.some((re) => re.test(author.name)))
|
|
2091
|
-
continue;
|
|
2092
|
-
if (!map.has(author.email))
|
|
2093
|
-
map.set(author.email, { commits: [], name: author.name, email: author.email });
|
|
2094
|
-
if (idx === 0)
|
|
2095
|
-
map.get(author.email).commits.push(commit.shortHash);
|
|
2096
|
-
}
|
|
2097
|
-
}
|
|
2098
|
-
const authors = Array.from(map.values());
|
|
2099
|
-
const resolved = await Promise.all(authors.map(async (info) => resolveAuthorInfo(options, info)));
|
|
2100
|
-
const loginSet = new Set;
|
|
2101
|
-
const nameSet = new Set;
|
|
2102
|
-
return resolved.sort((a, b) => (a.login ?? a.name).localeCompare(b.login ?? b.name)).filter((i) => {
|
|
2103
|
-
if (i.login !== undefined && loginSet.has(i.login))
|
|
2104
|
-
return false;
|
|
2105
|
-
if (i.login !== undefined) {
|
|
2106
|
-
loginSet.add(i.login);
|
|
2107
|
-
} else {
|
|
2108
|
-
if (nameSet.has(i.name))
|
|
2109
|
-
return false;
|
|
2110
|
-
nameSet.add(i.name);
|
|
2111
|
-
}
|
|
2112
|
-
return true;
|
|
2113
|
-
});
|
|
2114
|
-
}
|
|
2115
|
-
async function hasTagOnGitea(tag, options) {
|
|
2116
|
-
try {
|
|
2117
|
-
const url = `https://${options.baseUrlApi}/${tagPath(options, options.repo, tag)}`;
|
|
2118
|
-
console.log(`checking if tag exists on ${url}`);
|
|
2119
|
-
await api(url, {
|
|
2120
|
-
headers: getHeaders(options)
|
|
2121
|
-
});
|
|
2122
|
-
return true;
|
|
2123
|
-
} catch {
|
|
2124
|
-
return false;
|
|
2125
|
-
}
|
|
2126
|
-
}
|
|
2127
|
-
async function uploadAssets(options, assets) {
|
|
2128
|
-
const headers = getHeaders(options);
|
|
2129
|
-
let assetList = [];
|
|
2130
|
-
if (typeof assets === "string") {
|
|
2131
|
-
assetList = assets.split(",").map((s) => s.trim()).filter(Boolean);
|
|
2132
|
-
} else if (Array.isArray(assets)) {
|
|
2133
|
-
assetList = assets.flatMap((item) => typeof item === "string" ? item.split(",").map((s) => s.trim()) : []).filter(Boolean);
|
|
2134
|
-
}
|
|
2135
|
-
const expandedAssets = [];
|
|
2136
|
-
for (const pattern of assetList) {
|
|
2137
|
-
try {
|
|
2138
|
-
const glob = new Bun.Glob(pattern);
|
|
2139
|
-
const matches = Array.from(glob.scanSync());
|
|
2140
|
-
if (matches.length) {
|
|
2141
|
-
expandedAssets.push(...matches);
|
|
2142
|
-
} else {
|
|
2143
|
-
expandedAssets.push(pattern);
|
|
2144
|
-
}
|
|
2145
|
-
} catch (error) {
|
|
2146
|
-
console.error(err().red(`Failed to process glob pattern "${pattern}": ${String(error)}`));
|
|
2147
|
-
expandedAssets.push(pattern);
|
|
2148
|
-
}
|
|
2149
|
-
}
|
|
2150
|
-
const release = await api(`https://${options.baseUrlApi}/repos/${options.releaseRepo}/releases/tags/${encodeURIComponent(options.to ?? "")}`, {
|
|
2151
|
-
headers
|
|
2152
|
-
});
|
|
2153
|
-
let failed = 0;
|
|
2154
|
-
for (const asset of expandedAssets) {
|
|
2155
|
-
const filePath = path.resolve(asset);
|
|
2156
|
-
const file = Bun.file(filePath);
|
|
2157
|
-
if (!await file.exists()) {
|
|
2158
|
-
console.error(err().red(`Failed to read file ${filePath}: file does not exist`));
|
|
2159
|
-
failed++;
|
|
2160
|
-
continue;
|
|
2161
|
-
}
|
|
2162
|
-
const fileName = path.basename(filePath);
|
|
2163
|
-
const assetsPath = `repos/${options.releaseRepo}/releases/${release.id}/assets?name=${encodeURIComponent(fileName)}`;
|
|
2164
|
-
console.log(out().cyan(`Uploading ${fileName}...`));
|
|
2165
|
-
try {
|
|
2166
|
-
if (onGithub(options)) {
|
|
2167
|
-
await request(`https://uploads.github.com/${assetsPath}`, { method: "POST", headers: { ...headers, "content-type": "application/octet-stream" }, body: file });
|
|
2168
|
-
} else {
|
|
2169
|
-
const form = new FormData;
|
|
2170
|
-
form.append("attachment", file, fileName);
|
|
2171
|
-
await request(`https://${options.baseUrlApi}/${assetsPath}`, { method: "POST", headers, body: form });
|
|
2172
|
-
}
|
|
2173
|
-
console.log(out().green(`Uploaded ${fileName} successfully.`));
|
|
2174
|
-
} catch (error) {
|
|
2175
|
-
console.error(err().red(`Failed to upload ${fileName}: ${String(error)}`));
|
|
2176
|
-
failed++;
|
|
2177
|
-
}
|
|
2178
|
-
}
|
|
2179
|
-
return failed;
|
|
2180
|
-
}
|
|
2181
|
-
|
|
2182
|
-
// src/config.ts
|
|
2183
|
-
import { join as join6 } from "path";
|
|
2184
|
-
var {$: $2 } = globalThis.Bun;
|
|
2185
|
-
|
|
2186
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-4yevg2zv.js
|
|
2187
|
-
var o2 = /^(\d+)\.(\d+)\.(\d+)$/;
|
|
2188
|
-
function wn(r) {
|
|
2189
|
-
return o2.test(r);
|
|
2190
|
-
}
|
|
2191
|
-
function Z(r) {
|
|
2192
|
-
let n = o2.exec(r);
|
|
2193
|
-
if (!n)
|
|
2194
|
-
throw Error(`Invalid semver: "${r}"`);
|
|
2195
|
-
return { major: Number(n[1]), minor: Number(n[2]), patch: Number(n[3]) };
|
|
2196
|
-
}
|
|
2197
|
-
|
|
2198
|
-
// src/git.ts
|
|
2199
|
-
var {$ } = globalThis.Bun;
|
|
2200
|
-
var gitSuffixRE = /\.git$/;
|
|
2201
|
-
var sshRegex = /(?:ssh:\/\/[^/]+\/|^(?:[^@/\s]+@)?[^:/\s]+:)(\w[\w.-]*)\/(\w[\w.-]*)$/i;
|
|
2202
|
-
var regexSpecialRE = /[.*+?^${}()|[\]\\]/g;
|
|
2203
|
-
var httpsRegex = /https?:\/\/[^/]+\/(\w[\w.-]*)\/(\w[\w.-]*)$/i;
|
|
2204
|
-
var releaseVersionRE = /^[^.]*(?:\.[\d.]*|\d)$/;
|
|
2205
|
-
var TAG_DECORATION = /tag: ([^,\n]+)/g;
|
|
2206
|
-
var ORIGIN_HOST = /^(?:[a-z][a-z\d+.-]*:\/\/)?(?:[^@/]+@)?([^:/]+)/i;
|
|
2207
|
-
async function getOriginHost() {
|
|
2208
|
-
const url = (await $`git config --get remote.origin.url`.quiet().nothrow().text()).trim();
|
|
2209
|
-
return ORIGIN_HOST.exec(url)?.[1];
|
|
2210
|
-
}
|
|
2211
|
-
async function getGiteaRepo() {
|
|
2212
|
-
const url = await execCommand("git", ["config", "--get", "remote.origin.url"]);
|
|
2213
|
-
const cleanUrl = url.replace(gitSuffixRE, "");
|
|
2214
|
-
let match = sshRegex.exec(cleanUrl);
|
|
2215
|
-
match ||= httpsRegex.exec(cleanUrl);
|
|
2216
|
-
if (!match)
|
|
2217
|
-
throw new Error(`Can not parse Gitea repo from url ${url}`);
|
|
2218
|
-
return `${match[1]}/${match[2]}`;
|
|
2219
|
-
}
|
|
2220
|
-
async function getCurrentGitBranch() {
|
|
2221
|
-
const [tag] = (await execCommand("git", ["tag", "--points-at", "HEAD", "--sort=-v:refname"])).split(`
|
|
2222
|
-
`);
|
|
2223
|
-
return tag !== undefined && tag !== "" ? tag : execCommand("git", ["rev-parse", "--abbrev-ref", "HEAD"]);
|
|
2224
|
-
}
|
|
2225
|
-
async function isRepoShallow() {
|
|
2226
|
-
return (await execCommand("git", ["rev-parse", "--is-shallow-repository"])).trim() === "true";
|
|
2227
|
-
}
|
|
2228
|
-
function getSafeTagTemplate(template) {
|
|
2229
|
-
return template.includes("%s") ? template : `${template}%s`;
|
|
2230
|
-
}
|
|
2231
|
-
function getVersionString(template, tag) {
|
|
2232
|
-
const pattern = template.split("%s").map((part) => part.replace(regexSpecialRE, "\\$&")).join("(.+)");
|
|
2233
|
-
const regex = new RegExp(`^${pattern}$`);
|
|
2234
|
-
const match = regex.exec(tag);
|
|
2235
|
-
return match?.[1] ?? tag;
|
|
2236
|
-
}
|
|
2237
|
-
async function tipOf(to) {
|
|
2238
|
-
return (await $`git rev-parse --verify -q ${`${to}^{commit}`}`.quiet().nothrow()).exitCode === 0 ? to : "HEAD";
|
|
2239
|
-
}
|
|
2240
|
-
async function getGitTags(firstParent = false, to = "HEAD") {
|
|
2241
|
-
const output = await execCommand("git", ["log", ...firstParent ? ["--first-parent"] : [], "--decorate-refs=refs/tags/", "--format=%D", await tipOf(to), "--"]);
|
|
2242
|
-
return [...output.matchAll(TAG_DECORATION)].map((match) => match[1]?.trim() ?? "").filter((tag) => tag !== "");
|
|
2243
|
-
}
|
|
2244
|
-
async function getLastMatchingTag(inputTag, tagFilter, tagTemplate, rollup = {}, firstParent = false) {
|
|
2245
|
-
const inputVersionString = getVersionString(tagTemplate, inputTag);
|
|
2246
|
-
const isStableVersion = wn(inputVersionString);
|
|
2247
|
-
const tags = await getGitTags(firstParent, inputTag);
|
|
2248
|
-
const filteredTags = tags.filter(tagFilter);
|
|
2249
|
-
let tag;
|
|
2250
|
-
if (isStableVersion) {
|
|
2251
|
-
const input = Z(inputVersionString);
|
|
2252
|
-
const isMajor = input.minor === 0 && input.patch === 0;
|
|
2253
|
-
const isMinor = !isMajor && input.patch === 0;
|
|
2254
|
-
let boundary;
|
|
2255
|
-
if (isMajor && rollup.major)
|
|
2256
|
-
boundary = (v) => v.minor === 0 && v.patch === 0;
|
|
2257
|
-
else if (isMinor && rollup.minor)
|
|
2258
|
-
boundary = (v) => v.patch === 0;
|
|
2259
|
-
tag = filteredTags.find((tag) => {
|
|
2260
|
-
const versionString = getVersionString(tagTemplate, tag);
|
|
2261
|
-
if (versionString === inputVersionString || !wn(versionString))
|
|
2262
|
-
return false;
|
|
2263
|
-
return boundary ? boundary(Z(versionString)) : true;
|
|
2264
|
-
});
|
|
2265
|
-
}
|
|
2266
|
-
tag ||= filteredTags.find((tag) => tag !== inputTag);
|
|
2267
|
-
return tag;
|
|
2268
|
-
}
|
|
2269
|
-
async function isRefGitTag(to) {
|
|
2270
|
-
const ref = `refs/tags/${to}`;
|
|
2271
|
-
try {
|
|
2272
|
-
await $`git show-ref --verify ${ref}`.quiet();
|
|
2273
|
-
return true;
|
|
2274
|
-
} catch {
|
|
2275
|
-
return false;
|
|
2276
|
-
}
|
|
2277
|
-
}
|
|
2278
|
-
async function getFirstGitCommit(firstParent = false, to = "HEAD") {
|
|
2279
|
-
return (await execCommand("git", ["rev-list", "--max-parents=0", ...firstParent ? ["--first-parent"] : [], await tipOf(to), "--"])).split(`
|
|
2280
|
-
`).at(-1) ?? "";
|
|
2281
|
-
}
|
|
2282
|
-
async function deleteLocalTag(tag) {
|
|
2283
|
-
await $`git tag -d ${tag}`.quiet();
|
|
2284
|
-
}
|
|
2285
|
-
async function hasRemoteGitTag(tag, remote = "origin") {
|
|
2286
|
-
return (await execCommand("git", ["ls-remote", "--tags", remote, `refs/tags/${tag}`])).length > 0;
|
|
2287
|
-
}
|
|
2288
|
-
async function deleteRemoteGitTag(tag, remote = "origin") {
|
|
2289
|
-
await $`git push ${remote} --delete ${tag}`.quiet();
|
|
2290
|
-
}
|
|
2291
|
-
async function getTagCommit(tag) {
|
|
2292
|
-
return execCommand("git", ["rev-list", "-n", "1", tag]);
|
|
2293
|
-
}
|
|
2294
|
-
async function getHeadCommit() {
|
|
2295
|
-
return execCommand("git", ["rev-parse", "HEAD"]);
|
|
2296
|
-
}
|
|
2297
|
-
async function getCommitSubject(ref) {
|
|
2298
|
-
return execCommand("git", ["log", "-1", "--format=%s", ref]);
|
|
2299
|
-
}
|
|
2300
|
-
async function softResetLastCommit() {
|
|
2301
|
-
await $`git reset --soft HEAD~1`.quiet();
|
|
2302
|
-
}
|
|
2303
|
-
function isPrerelease(version) {
|
|
2304
|
-
return !releaseVersionRE.test(version);
|
|
2305
|
-
}
|
|
2306
|
-
async function execCommand(cmd, args) {
|
|
2307
|
-
return (await $`${cmd} ${args}`.quiet().text()).trim();
|
|
2308
|
-
}
|
|
2309
|
-
|
|
2310
|
-
// src/config.ts
|
|
2311
|
-
var GITHUB = "github.com";
|
|
2312
|
-
function forgeName(config) {
|
|
2313
|
-
return config.provider === "github" ? "GitHub" : "Forgejo";
|
|
2314
|
-
}
|
|
2315
|
-
var configFiles = ["ts", "mts", "js", "mjs", "json"].map((ext) => `changelog.config.${ext}`);
|
|
2316
|
-
var defaultConfig = {
|
|
2317
|
-
scopeMap: {},
|
|
2318
|
-
types: {
|
|
2319
|
-
feat: { title: "\u2728 New" },
|
|
2320
|
-
fix: { title: "\uD83D\uDD27 Fixed" },
|
|
2321
|
-
perf: { title: "\u26A1 Faster" },
|
|
2322
|
-
refactor: { title: "refactor", folded: true },
|
|
2323
|
-
docs: { title: "docs", folded: true },
|
|
2324
|
-
build: { title: "build", folded: true },
|
|
2325
|
-
types: { title: "types", folded: true },
|
|
2326
|
-
test: { title: "test", folded: true },
|
|
2327
|
-
style: { title: "style", folded: true },
|
|
2328
|
-
ci: { title: "ci", folded: true }
|
|
2329
|
-
},
|
|
2330
|
-
titles: {
|
|
2331
|
-
breakingChanges: "\u26A0\uFE0F Breaking",
|
|
2332
|
-
highlights: "\uD83C\uDF1F Highlights",
|
|
2333
|
-
maintenance: "\uD83E\uDDF9 Maintenance"
|
|
2334
|
-
},
|
|
2335
|
-
contributors: true,
|
|
2336
|
-
capitalize: true,
|
|
2337
|
-
group: true,
|
|
2338
|
-
emoji: true,
|
|
2339
|
-
firstParent: false,
|
|
2340
|
-
tag: "v%s"
|
|
2341
|
-
};
|
|
2342
|
-
function isPlainObject(value) {
|
|
2343
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2344
|
-
}
|
|
2345
|
-
function mergeLayers(...layers) {
|
|
2346
|
-
const merged = {};
|
|
2347
|
-
for (const layer of layers) {
|
|
2348
|
-
for (const [key, value] of Object.entries(layer)) {
|
|
2349
|
-
if (value === undefined)
|
|
2350
|
-
continue;
|
|
2351
|
-
merged[key] = isPlainObject(value) && isPlainObject(merged[key]) ? mergeLayers(merged[key], value) : value;
|
|
2352
|
-
}
|
|
2353
|
-
}
|
|
2354
|
-
return merged;
|
|
2355
|
-
}
|
|
2356
|
-
async function loadConfigFile(cwd) {
|
|
2357
|
-
for (const name of configFiles) {
|
|
2358
|
-
const path = join6(cwd, name);
|
|
2359
|
-
if (await Bun.file(path).exists())
|
|
2360
|
-
return (await import(path)).default ?? {};
|
|
2361
|
-
}
|
|
2362
|
-
return {};
|
|
2363
|
-
}
|
|
2364
|
-
async function ghToken() {
|
|
2365
|
-
if (Bun.which("gh") === null)
|
|
2366
|
-
return;
|
|
2367
|
-
const answer = await $2`gh auth token`.quiet().nothrow();
|
|
2368
|
-
return answer.exitCode === 0 && answer.text().trim() !== "" ? answer.text().trim() : undefined;
|
|
2369
|
-
}
|
|
2370
|
-
async function loadPackageConfig(cwd) {
|
|
2371
|
-
const file = Bun.file(join6(cwd, "package.json"));
|
|
2372
|
-
return !await file.exists() ? {} : (await file.json()).changelog ?? {};
|
|
2373
|
-
}
|
|
2374
|
-
async function loadConfig(options, cwd = process.cwd()) {
|
|
2375
|
-
const [packageConfig, fileConfig] = await Promise.all([loadPackageConfig(cwd), loadConfigFile(cwd)]);
|
|
2376
|
-
return mergeLayers(defaultConfig, packageConfig, fileConfig, options);
|
|
2377
|
-
}
|
|
2378
|
-
async function resolveConfig(options) {
|
|
2379
|
-
const config = await loadConfig(options);
|
|
2380
|
-
const origin = config.baseUrl === undefined ? await getOriginHost() : undefined;
|
|
2381
|
-
const baseUrl = config.baseUrl ?? (origin === GITHUB ? origin : configuredForge()?.host ?? origin);
|
|
2382
|
-
if (baseUrl === undefined || baseUrl === "")
|
|
2383
|
-
throw new Error("no forge to link the notes to: set baseUrl in the changelog config, forge in ~/.config/kaynooo-cli/config.json, or an origin remote");
|
|
2384
|
-
config.baseUrl = baseUrl;
|
|
2385
|
-
config.provider ??= baseUrl === GITHUB ? "github" : "gitea";
|
|
2386
|
-
config.baseUrlApi ??= config.provider === "github" ? "api.github.com" : `${baseUrl}/api/v1`;
|
|
2387
|
-
const token = config.provider === "github" && (config.token ?? "") === "" ? await ghToken() : undefined;
|
|
2388
|
-
if (token !== undefined)
|
|
2389
|
-
config.token = token;
|
|
2390
|
-
config.to ||= await getCurrentGitBranch();
|
|
2391
|
-
config.tagFilter ??= () => true;
|
|
2392
|
-
config.tag = getSafeTagTemplate(config.tag ?? defaultConfig.tag);
|
|
2393
|
-
config.rollup ??= {};
|
|
2394
|
-
config.fromRoot = false;
|
|
2395
|
-
if (config.from === undefined || config.from === "") {
|
|
2396
|
-
const tag = await getLastMatchingTag(config.to, config.tagFilter, config.tag, config.rollup, config.firstParent);
|
|
2397
|
-
config.fromRoot = tag === undefined;
|
|
2398
|
-
config.from = tag ?? await getFirstGitCommit(config.firstParent, config.to);
|
|
2399
|
-
}
|
|
2400
|
-
const legacy = config;
|
|
2401
|
-
config.repo ||= legacy.gitea ?? await getGiteaRepo();
|
|
2402
|
-
config.releaseRepo ||= legacy.releaseGithub ?? config.repo;
|
|
2403
|
-
config.prerelease ??= isPrerelease(config.to);
|
|
2404
|
-
config.discordWebhook ??= process.env.DISCORD_WEBHOOK ?? "";
|
|
2405
|
-
if (typeof config.repo !== "string")
|
|
2406
|
-
throw new TypeError(`Invalid repository, expected a string but got ${JSON.stringify(config.repo)}`);
|
|
2407
|
-
return config;
|
|
2408
|
-
}
|
|
2409
|
-
|
|
2410
|
-
// ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-m6zaxxzm.js
|
|
2411
|
-
function p2(n) {
|
|
2412
|
-
return n !== null && n !== undefined;
|
|
2413
|
-
}
|
|
2414
|
-
function m2(n, e, t) {
|
|
2415
|
-
Object.defineProperty(n, e, { value: t, enumerable: true, writable: true, configurable: true });
|
|
2416
|
-
}
|
|
2417
|
-
function Fr(n, e) {
|
|
2418
|
-
let t = {};
|
|
2419
|
-
for (let o of n) {
|
|
2420
|
-
let u = e(o);
|
|
2421
|
-
if (Object.hasOwn(t, u))
|
|
2422
|
-
t[u].push(o);
|
|
2423
|
-
else
|
|
2424
|
-
m2(t, u, [o]);
|
|
2425
|
-
}
|
|
2426
|
-
return t;
|
|
2427
|
-
}
|
|
2428
|
-
|
|
2429
|
-
// src/markdown.ts
|
|
2430
|
-
init_text();
|
|
2431
|
-
var emojiRE = /\p{Extended_Pictographic}\uFE0F?/gu;
|
|
2432
|
-
var fullHashRE = /^[\da-f]{40}$/;
|
|
2433
|
-
var IDENTIFIER_START = /^(?:`|[a-z]+[A-Z]|\S*\d|\S*[._/]\w)/;
|
|
2434
|
-
function groupCommits(commits, options) {
|
|
2435
|
-
const breaking = commits.filter((c) => c.isBreaking);
|
|
2436
|
-
const byType = Fr(commits.filter((c) => !c.isBreaking), (c) => c.type);
|
|
2437
|
-
const sections = breaking.length ? [{ title: options.titles.breakingChanges, commits: breaking }] : [];
|
|
2438
|
-
const folded = [];
|
|
2439
|
-
for (const [type, config] of Object.entries(options.types)) {
|
|
2440
|
-
const typed = byType[type] ?? [];
|
|
2441
|
-
if (typeof config === "boolean" || typed.length === 0)
|
|
2442
|
-
continue;
|
|
2443
|
-
const target = config.folded === true ? folded : sections;
|
|
2444
|
-
target.push({ title: config.title, commits: typed });
|
|
2445
|
-
}
|
|
2446
|
-
return { sections, folded };
|
|
2447
|
-
}
|
|
2448
|
-
function formatTitle(title, options) {
|
|
2449
|
-
return (options.emoji ? title : title.replace(emojiRE, "")).trim();
|
|
2450
|
-
}
|
|
2451
|
-
function shortRef(ref) {
|
|
2452
|
-
return fullHashRE.test(ref) ? ref.slice(0, 7) : ref;
|
|
2453
|
-
}
|
|
2454
|
-
function repoUrl(options) {
|
|
2455
|
-
return `https://${options.baseUrl}/${options.repo}`;
|
|
2456
|
-
}
|
|
2457
|
-
function compareUrl(options) {
|
|
2458
|
-
return `${repoUrl(options)}/compare/${options.from}...${options.to}`;
|
|
2459
|
-
}
|
|
2460
|
-
function releaseUrl(options) {
|
|
2461
|
-
return `https://${options.baseUrl}/${options.releaseRepo}/releases/tag/${encodeURIComponent(options.to)}`;
|
|
2462
|
-
}
|
|
2463
|
-
function userUrl(login, options) {
|
|
2464
|
-
return `https://${options.baseUrl}/${login}`;
|
|
2465
|
-
}
|
|
2466
|
-
function formatIssue(ref, options, withTitle) {
|
|
2467
|
-
const text = withTitle && ref.title !== undefined ? `${ref.value} ${ref.title}` : ref.value;
|
|
2468
|
-
return `[${text}](${repoUrl(options)}/issues/${ref.value.slice(1)})`;
|
|
2469
|
-
}
|
|
2470
|
-
function capitalized(description) {
|
|
2471
|
-
return IDENTIFIER_START.test(description) ? description : d(description);
|
|
2472
|
-
}
|
|
2473
|
-
function formatLine(commit, options, prefix = "", issueTitles = false) {
|
|
2474
|
-
const description = options.capitalize ? capitalized(commit.description) : commit.description;
|
|
2475
|
-
const hash = `[\`${commit.shortHash.slice(0, 7)}\`](${repoUrl(options)}/commit/${commit.shortHash})`;
|
|
2476
|
-
const issues = commit.references.filter((ref) => ref.type !== "hash").map((ref) => formatIssue(ref, options, issueTitles));
|
|
2477
|
-
return [`${prefix}${description}`, hash, ...issues].join(" \xB7 ");
|
|
2478
|
-
}
|
|
2479
|
-
function foldedPrefix(commit) {
|
|
2480
|
-
return `**${commit.scope ? `${commit.type}(${commit.scope})` : commit.type}**: `;
|
|
2481
|
-
}
|
|
2482
|
-
function foldedCounts(folded, options) {
|
|
2483
|
-
return folded.map((section) => `${section.commits.length} ${formatTitle(section.title, options)}`).join(", ");
|
|
2484
|
-
}
|
|
2485
|
-
function formatAuthors(contributors, options) {
|
|
2486
|
-
return join7(contributors.map((c) => c.login !== undefined ? `[@${c.login}](${userUrl(c.login, options)})` : `**${c.name}**`));
|
|
2487
|
-
}
|
|
2488
|
-
function summaryLabel(title) {
|
|
2489
|
-
return title.replace(emojiRE, "").trim().toLowerCase();
|
|
2490
|
-
}
|
|
2491
|
-
function formatSummary({ sections, folded }, contributors, options) {
|
|
2492
|
-
const counts = sections.map((section) => `${section.commits.length} ${summaryLabel(section.title)}`);
|
|
2493
|
-
if (folded.length) {
|
|
2494
|
-
const total = folded.reduce((sum, section) => sum + section.commits.length, 0);
|
|
2495
|
-
counts.push(`${total} ${summaryLabel(options.titles.maintenance)}`);
|
|
2496
|
-
}
|
|
2497
|
-
const authors = formatAuthors(contributors, options);
|
|
2498
|
-
const parts = [
|
|
2499
|
-
counts.length ? `**${counts.join(" \xB7 ")}**` : "",
|
|
2500
|
-
authors && `by ${authors}`,
|
|
2501
|
-
`\`${shortRef(options.from)}\` \u2192 \`${shortRef(options.to)}\``
|
|
2502
|
-
];
|
|
2503
|
-
return `> ${parts.filter(Boolean).join(" \xB7 ")}`;
|
|
2504
|
-
}
|
|
2505
|
-
function formatSection(section, options) {
|
|
2506
|
-
const lines = ["", `### ${formatTitle(section.title, options)}`, ""];
|
|
2507
|
-
const scopes = Fr(section.commits, (c) => c.scope);
|
|
2508
|
-
const nestable = Object.entries(scopes).some(([scope, commits]) => scope !== "" && commits.length > 1);
|
|
2509
|
-
for (const [scope, commits] of Object.entries(scopes).sort(([a], [b]) => a.localeCompare(b))) {
|
|
2510
|
-
const scopeText = `**${scope}**`;
|
|
2511
|
-
const nested = nestable && scope !== "" && (options.group === true || options.group === "multiple" && commits.length > 1);
|
|
2512
|
-
const prefix = scope !== "" && !nested ? `${scopeText}: ` : "";
|
|
2513
|
-
const padding = nested ? " " : "";
|
|
2514
|
-
if (nested)
|
|
2515
|
-
lines.push(`- ${scopeText}:`);
|
|
2516
|
-
for (const commit of commits.toReversed()) {
|
|
2517
|
-
lines.push(`${padding}- ${formatLine(commit, options, prefix)}`);
|
|
2518
|
-
if (commit.breakingNote !== undefined)
|
|
2519
|
-
lines.push(`${padding} - ${commit.breakingNote}`);
|
|
2520
|
-
}
|
|
2521
|
-
}
|
|
2522
|
-
return lines;
|
|
2523
|
-
}
|
|
2524
|
-
function formatAvatars(contributors, options) {
|
|
2525
|
-
return contributors.filter((c) => c.login !== undefined && c.avatar !== undefined).map((c) => `<a href="${userUrl(c.login, options)}"><img src="${c.avatar}" width="28" height="28" alt="@${c.login}"></a>`).join(" ");
|
|
2526
|
-
}
|
|
2527
|
-
function generateMarkdown(commits, options, contributors = [], highlights) {
|
|
2528
|
-
const grouped = groupCommits(commits, options);
|
|
2529
|
-
const { sections, folded } = grouped;
|
|
2530
|
-
const lines = [formatSummary(grouped, contributors, options)];
|
|
2531
|
-
if (highlights)
|
|
2532
|
-
lines.push("", `### ${formatTitle(options.titles.highlights, options)}`, "", ...highlights.lines, "", `[Read more](${highlights.link})`);
|
|
2533
|
-
for (const section of sections)
|
|
2534
|
-
lines.push(...formatSection(section, options));
|
|
2535
|
-
if (folded.length) {
|
|
2536
|
-
lines.push("", "<details>", `<summary><b>${formatTitle(options.titles.maintenance, options)}</b> \xB7 ${foldedCounts(folded, options)}</summary>`, "", ...folded.flatMap((section) => section.commits.toReversed().map((commit) => `- ${formatLine(commit, options, foldedPrefix(commit))}`)), "", "</details>");
|
|
2537
|
-
}
|
|
2538
|
-
if (!sections.length && !folded.length)
|
|
2539
|
-
lines.push("", "*No significant changes*");
|
|
2540
|
-
lines.push("", "---", "");
|
|
2541
|
-
const avatars = formatAvatars(contributors, options);
|
|
2542
|
-
if (avatars)
|
|
2543
|
-
lines.push(avatars, "");
|
|
2544
|
-
lines.push(`<sub>[Full diff \`${shortRef(options.from)}...${shortRef(options.to)}\`](${compareUrl(options)}) \xB7 generated by cli-changelog</sub>`);
|
|
2545
|
-
return lines.join(`
|
|
2546
|
-
`);
|
|
2547
|
-
}
|
|
2548
|
-
function join7(array, glue = ", ", finalGlue = " and ") {
|
|
2549
|
-
return array.length <= 2 ? array.join(finalGlue) : `${array.slice(0, -1).join(glue)}${finalGlue}${array.at(-1)}`;
|
|
2550
|
-
}
|
|
2551
|
-
|
|
2552
|
-
// src/discord.ts
|
|
2553
|
-
var descriptionLimit = 4096;
|
|
2554
|
-
var color = 16486972;
|
|
2555
|
-
var breakingColor = 15548997;
|
|
2556
|
-
var fenceRE = /^\s*(`{3,}|~{3,})/;
|
|
2557
|
-
var headingRE = /^#{1,6}(?:\s(.*))?$/;
|
|
2558
|
-
var strongRE = /\*\*|__/g;
|
|
2559
|
-
var isCommitLine = (line) => line.startsWith("- ");
|
|
2560
|
-
function fitCommits(head, lines, tail) {
|
|
2561
|
-
const total = lines.filter(isCommitLine).length;
|
|
2562
|
-
for (let kept = lines.length;kept >= 0; kept--) {
|
|
2563
|
-
const shown = lines.slice(0, kept);
|
|
2564
|
-
while (shown.length && kept < lines.length && !isCommitLine(shown.at(-1)))
|
|
2565
|
-
shown.pop();
|
|
2566
|
-
const more = total - shown.filter(isCommitLine).length;
|
|
2567
|
-
const text = [...head, ...shown, ...more ? ["", `*\u2026and ${more} more*`] : [], "", tail].join(`
|
|
2568
|
-
`).trim();
|
|
2569
|
-
if (text.length <= descriptionLimit)
|
|
2570
|
-
return text;
|
|
2571
|
-
}
|
|
2572
|
-
return;
|
|
2573
|
-
}
|
|
2574
|
-
function fitDescription(head, lines, tail) {
|
|
2575
|
-
const fitted = fitCommits(head, lines, tail);
|
|
2576
|
-
if (fitted !== undefined || !head.length)
|
|
2577
|
-
return fitted ?? tail.slice(0, descriptionLimit);
|
|
2578
|
-
for (let kept = head.length - 2;kept >= 1; kept--) {
|
|
2579
|
-
const shown = head.slice(0, kept);
|
|
2580
|
-
const open = openFence(shown);
|
|
2581
|
-
if (open !== undefined)
|
|
2582
|
-
shown.push(open);
|
|
2583
|
-
const text = fitCommits([...shown, "\u2026", head.at(-1)], lines, tail);
|
|
2584
|
-
if (text !== undefined)
|
|
2585
|
-
return text;
|
|
2586
|
-
}
|
|
2587
|
-
return tail.slice(0, descriptionLimit);
|
|
2588
|
-
}
|
|
2589
|
-
function openFence(lines) {
|
|
2590
|
-
let open;
|
|
2591
|
-
for (const line of lines) {
|
|
2592
|
-
const marker = fenceRE.exec(line)?.[1];
|
|
2593
|
-
if (marker !== undefined)
|
|
2594
|
-
open = open !== undefined && marker.startsWith(open) ? undefined : open ?? marker;
|
|
2595
|
-
}
|
|
2596
|
-
return open;
|
|
2597
|
-
}
|
|
2598
|
-
var tableRowRE = /^\s*\|.*\|\s*$/;
|
|
2599
|
-
var tableRuleRE = /^\s*\|(?:\s*:?-+:?\s*\|)+\s*$/;
|
|
2600
|
-
var cellSplitRE = /(?<!\\)\|(?=(?:[^`]*`[^`]*`)*[^`]*$)/;
|
|
2601
|
-
function bulletedTables(lines) {
|
|
2602
|
-
let fenced = false;
|
|
2603
|
-
const out = [];
|
|
2604
|
-
for (const [index, line] of lines.entries()) {
|
|
2605
|
-
if (fenceRE.test(line))
|
|
2606
|
-
fenced = !fenced;
|
|
2607
|
-
if (fenced || !tableRowRE.test(line)) {
|
|
2608
|
-
out.push(line);
|
|
2609
|
-
continue;
|
|
2610
|
-
}
|
|
2611
|
-
if (tableRuleRE.test(line) || tableRuleRE.test(lines[index + 1] ?? ""))
|
|
2612
|
-
continue;
|
|
2613
|
-
const [first = "", ...rest] = line.trim().slice(1, -1).split(cellSplitRE).map((cell) => cell.trim());
|
|
2614
|
-
out.push(`- **${first}**${rest.length ? `: ${rest.join(" \xB7 ")}` : ""}`);
|
|
2615
|
-
}
|
|
2616
|
-
return out;
|
|
2617
|
-
}
|
|
2618
|
-
function highlightLines(highlights, options) {
|
|
2619
|
-
let fenced = false;
|
|
2620
|
-
const lines = bulletedTables(highlights.lines).flatMap((line) => {
|
|
2621
|
-
if (fenceRE.test(line))
|
|
2622
|
-
fenced = !fenced;
|
|
2623
|
-
const heading = fenced ? null : headingRE.exec(line);
|
|
2624
|
-
if (!heading)
|
|
2625
|
-
return [line];
|
|
2626
|
-
const text = (heading[1] ?? "").replace(strongRE, "").trim();
|
|
2627
|
-
return text ? [`**${text}**`] : [];
|
|
2628
|
-
});
|
|
2629
|
-
return [`**${formatTitle(options.titles.highlights, options)}**`, ...lines, `[Read more](${highlights.link})`];
|
|
2630
|
-
}
|
|
2631
|
-
function generateDiscordPayload(commits, options, contributors = [], highlights) {
|
|
2632
|
-
const { sections, folded } = groupCommits(commits, options);
|
|
2633
|
-
const lines = [];
|
|
2634
|
-
for (const section of sections) {
|
|
2635
|
-
lines.push("", `**${formatTitle(section.title, options)}**`);
|
|
2636
|
-
for (const commit of section.commits.toReversed())
|
|
2637
|
-
lines.push(`- ${formatLine(commit, options, commit.scope ? `**${commit.scope}**: ` : "", true)}`);
|
|
2638
|
-
}
|
|
2639
|
-
if (!sections.length && !folded.length)
|
|
2640
|
-
lines.push("*No significant changes*");
|
|
2641
|
-
const links = `[full notes](${releaseUrl(options)}) \xB7 [diff](${compareUrl(options)})`;
|
|
2642
|
-
const tail = folded.length ? `${formatTitle(options.titles.maintenance, options)} *${foldedCounts(folded, options)}* \xB7 ${links}` : links;
|
|
2643
|
-
const authors = contributors.map((c) => c.login ?? c.name).join(", ");
|
|
2644
|
-
const range = `${shortRef(options.from)} \u2192 ${shortRef(options.to)}`;
|
|
2645
|
-
const avatar = contributors.find((c) => c.avatar !== undefined)?.avatar;
|
|
2646
|
-
return {
|
|
2647
|
-
embeds: [{
|
|
2648
|
-
title: `${String(options.releaseRepo).split("/").at(-1)} ${options.name || options.to}`.slice(0, 256),
|
|
2649
|
-
url: releaseUrl(options),
|
|
2650
|
-
color: commits.some((c) => c.isBreaking) ? breakingColor : color,
|
|
2651
|
-
description: fitDescription(highlights ? highlightLines(highlights, options) : [], lines, tail),
|
|
2652
|
-
footer: { text: authors ? `${authors} \xB7 ${range}` : range, ...avatar === undefined ? {} : { icon_url: avatar } },
|
|
2653
|
-
timestamp: new Date().toISOString()
|
|
2654
|
-
}]
|
|
2655
|
-
};
|
|
2656
|
-
}
|
|
2657
|
-
|
|
2658
|
-
// src/changelog.ts
|
|
2659
|
-
var {$: $3 } = globalThis.Bun;
|
|
2660
|
-
var ConventionalCommitRegex = /^(?::.+:|\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F\uDE80-\uDEFF]|[\u2600-\u2B55])? *(?<type>[a-z]+)(?:\((?<scope>[^()\n]+)\))?(?<breaking>!)?: (?<description>.+)/i;
|
|
2661
|
-
var CoAuthoredByRegex = /co-authored-by:\s*(?<name>\S[^<]*)<(?<email>[^>]+)>/gi;
|
|
2662
|
-
var PullRequestRE = /\([ a-z]*(#\d+)\s*\)/g;
|
|
2663
|
-
var IssueRE = /(#\d+)/g;
|
|
2664
|
-
var BreakingBodyRE = /^BREAKING[ -]CHANGE:[ \t]*(.*(?:\n(?![ \t]*$|[\w-]+(?:: | #)).+)*)/m;
|
|
2665
|
-
var TicketLineRE = /^(#\d+) - (.+)$/gm;
|
|
2666
|
-
async function getGitDiff(from, to = "HEAD", firstParent = false) {
|
|
2667
|
-
const range = `${from !== undefined && from !== "" ? `${from}..` : ""}${to}`;
|
|
2668
|
-
const pretty = "%x1e%s%x00%h%x00%an%x00%ae%x00%b";
|
|
2669
|
-
const flags = firstParent ? ["--first-parent"] : [];
|
|
2670
|
-
const output = await $3`git --no-pager log ${range} ${flags} --pretty=${pretty}`.quiet().text();
|
|
2671
|
-
return output.split("\x1E").slice(1).map((record) => {
|
|
2672
|
-
const [message = "", shortHash = "", authorName = "", authorEmail = "", body = ""] = record.split("\x00");
|
|
2673
|
-
return {
|
|
2674
|
-
message,
|
|
2675
|
-
shortHash,
|
|
2676
|
-
author: { name: authorName, email: authorEmail },
|
|
2677
|
-
body: body.trim()
|
|
2678
|
-
};
|
|
2679
|
-
});
|
|
2680
|
-
}
|
|
2681
|
-
function parseGitCommit(commit, config) {
|
|
2682
|
-
const match = commit.message.match(ConventionalCommitRegex);
|
|
2683
|
-
if (!match?.groups)
|
|
2684
|
-
return null;
|
|
2685
|
-
const type = (match.groups.type ?? "").toLowerCase();
|
|
2686
|
-
const breakingBody = BreakingBodyRE.exec(commit.body);
|
|
2687
|
-
const breakingNote = breakingBody?.[1]?.replaceAll(/\s+/g, " ").trim();
|
|
2688
|
-
const rawScope = match.groups.scope ?? "";
|
|
2689
|
-
const scope = Object.hasOwn(config.scopeMap, rawScope) ? config.scopeMap[rawScope] : rawScope;
|
|
2690
|
-
const isBreaking = match.groups.breaking !== undefined || breakingBody !== null;
|
|
2691
|
-
let description = match.groups.description ?? "";
|
|
2692
|
-
const references = [];
|
|
2693
|
-
for (const m of description.matchAll(PullRequestRE))
|
|
2694
|
-
references.push({ type: "pull-request", value: m[1] });
|
|
2695
|
-
for (const m of description.matchAll(IssueRE)) {
|
|
2696
|
-
if (!references.some((i) => i.value === m[1]))
|
|
2697
|
-
references.push({ type: "issue", value: m[1] });
|
|
2698
|
-
}
|
|
2699
|
-
for (const m of commit.body.matchAll(TicketLineRE)) {
|
|
2700
|
-
const known = references.find((i) => i.value === m[1]);
|
|
2701
|
-
if (known)
|
|
2702
|
-
known.title = m[2].trim();
|
|
2703
|
-
else
|
|
2704
|
-
references.push({ type: "issue", value: m[1], title: m[2].trim() });
|
|
2705
|
-
}
|
|
2706
|
-
references.push({ value: commit.shortHash, type: "hash" });
|
|
2707
|
-
description = description.replace(PullRequestRE, "").trim();
|
|
2708
|
-
const authors = [commit.author];
|
|
2709
|
-
for (const m of commit.body.matchAll(CoAuthoredByRegex)) {
|
|
2710
|
-
authors.push({
|
|
2711
|
-
name: (m.groups?.name ?? "").trim(),
|
|
2712
|
-
email: (m.groups?.email ?? "").trim()
|
|
2713
|
-
});
|
|
2714
|
-
}
|
|
2715
|
-
return {
|
|
2716
|
-
...commit,
|
|
2717
|
-
authors,
|
|
2718
|
-
description,
|
|
2719
|
-
type,
|
|
2720
|
-
scope,
|
|
2721
|
-
references,
|
|
2722
|
-
isBreaking,
|
|
2723
|
-
...breakingNote === undefined || breakingNote === "" ? {} : { breakingNote }
|
|
2724
|
-
};
|
|
2725
|
-
}
|
|
2726
|
-
|
|
2727
|
-
// src/highlights.ts
|
|
2728
|
-
import { isAbsolute as isAbsolute2, join as join8 } from "path";
|
|
2729
|
-
var fenceRE2 = /^\s*(`{3,}|~{3,})/;
|
|
2730
|
-
var headingRE2 = /^(#{1,6})(\s.*)$/;
|
|
2731
|
-
var schemeRE = /^[a-z][a-z\d+.-]*:/i;
|
|
2732
|
-
var inlineLinkRE = /(\]\(\s*<?)((?:[^\s<>()]|\([^\s<>()]*\))+)/g;
|
|
2733
|
-
var definitionRE = /^(\s{0,3}\[[^\]]+\]:\s*<?)([^\s<>]+)(>?(?:\s.*)?)$/;
|
|
2734
|
-
var newlineRE = /\r?\n/;
|
|
2735
|
-
var codeSpanRE = /(`+)[\s\S]*?\1/;
|
|
2736
|
-
function headingAnchor(text) {
|
|
2737
|
-
return text.trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, "").replace(/\s/g, "-");
|
|
2738
|
-
}
|
|
2739
|
-
function resolveTarget(written, base, link) {
|
|
2740
|
-
const target = link?.(written) ?? written;
|
|
2741
|
-
if (schemeRE.test(target) || target.startsWith("//"))
|
|
2742
|
-
return target;
|
|
2743
|
-
try {
|
|
2744
|
-
return new URL(target, base).href;
|
|
2745
|
-
} catch {
|
|
2746
|
-
return target;
|
|
2747
|
-
}
|
|
2748
|
-
}
|
|
2749
|
-
function resolveLinks(line, base, link) {
|
|
2750
|
-
const definition = definitionRE.exec(line);
|
|
2751
|
-
if (definition)
|
|
2752
|
-
return `${definition[1]}${resolveTarget(definition[2], base, link)}${definition[3]}`;
|
|
2753
|
-
let rest = line;
|
|
2754
|
-
let out = "";
|
|
2755
|
-
while (rest) {
|
|
2756
|
-
const code = codeSpanRE.exec(rest);
|
|
2757
|
-
const text = code ? rest.slice(0, code.index) : rest;
|
|
2758
|
-
out += text.replace(inlineLinkRE, (_, open, target) => `${open}${resolveTarget(target, base, link)}`);
|
|
2759
|
-
if (!code)
|
|
2760
|
-
break;
|
|
2761
|
-
out += code[0];
|
|
2762
|
-
rest = rest.slice(code.index + code[0].length);
|
|
2763
|
-
}
|
|
2764
|
-
return out;
|
|
2765
|
-
}
|
|
2766
|
-
function withoutAnchor(url) {
|
|
2767
|
-
const hash = url.indexOf("#");
|
|
2768
|
-
return hash === -1 ? url : url.slice(0, hash);
|
|
2769
|
-
}
|
|
2770
|
-
function withoutFrontmatter(lines) {
|
|
2771
|
-
if (lines[0]?.trim() !== "---")
|
|
2772
|
-
return lines;
|
|
2773
|
-
const end = lines.findIndex((line, index) => index > 0 && line.trim() === "---");
|
|
2774
|
-
return end === -1 ? lines : lines.slice(end + 1);
|
|
2775
|
-
}
|
|
2776
|
-
function parseHighlights(source, version, url, link) {
|
|
2777
|
-
const lines = withoutFrontmatter(source.split(newlineRE));
|
|
2778
|
-
const section = [];
|
|
2779
|
-
let fence;
|
|
2780
|
-
let inside = false;
|
|
2781
|
-
for (const line of lines) {
|
|
2782
|
-
const marker = fenceRE2.exec(line)?.[1];
|
|
2783
|
-
if (fence === undefined && marker === undefined) {
|
|
2784
|
-
const heading = headingRE2.exec(line);
|
|
2785
|
-
if (heading?.[1] === "##") {
|
|
2786
|
-
if (inside)
|
|
2787
|
-
break;
|
|
2788
|
-
inside = heading[2].trim() === version;
|
|
2789
|
-
continue;
|
|
2790
|
-
}
|
|
2791
|
-
if (inside && heading) {
|
|
2792
|
-
section.push(`${"#".repeat(Math.min(heading[1].length + 1, 6))}${heading[2]}`);
|
|
2793
|
-
continue;
|
|
2794
|
-
}
|
|
2795
|
-
}
|
|
2796
|
-
if (marker !== undefined)
|
|
2797
|
-
fence = fence !== undefined && marker.startsWith(fence) ? undefined : fence ?? marker;
|
|
2798
|
-
if (inside)
|
|
2799
|
-
section.push(fence !== undefined || marker !== undefined ? line : resolveLinks(line, url, link));
|
|
2800
|
-
}
|
|
2801
|
-
while (section.length && !section[0].trim())
|
|
2802
|
-
section.shift();
|
|
2803
|
-
while (section.length && !section.at(-1).trim())
|
|
2804
|
-
section.pop();
|
|
2805
|
-
return !section.length ? undefined : { lines: section, link: `${withoutAnchor(url)}#${headingAnchor(version)}` };
|
|
2806
|
-
}
|
|
2807
|
-
async function readHighlights(options, cwd = process.cwd()) {
|
|
2808
|
-
const highlights = options.highlights;
|
|
2809
|
-
if (highlights === undefined)
|
|
2810
|
-
return;
|
|
2811
|
-
const { file, url, link } = highlights;
|
|
2812
|
-
const source = Bun.file(isAbsolute2(file) ? file : join8(cwd, file));
|
|
2813
|
-
if (!await source.exists())
|
|
2814
|
-
return;
|
|
2815
|
-
return parseHighlights(await source.text(), getVersionString(options.tag, options.to), url, link);
|
|
2816
|
-
}
|
|
2817
|
-
|
|
2818
|
-
// src/parse.ts
|
|
2819
|
-
function parseCommits(commits, config) {
|
|
2820
|
-
return commits.map((commit) => parseGitCommit(commit, config)).filter(p2);
|
|
2821
|
-
}
|
|
2822
|
-
|
|
2823
|
-
// src/generate.ts
|
|
2824
|
-
async function generate(options) {
|
|
2825
|
-
const resolved = await resolveConfig(options);
|
|
2826
|
-
const rawCommits = await getGitDiff(resolved.fromRoot === true ? undefined : resolved.from, resolved.to, resolved.firstParent);
|
|
2827
|
-
const commits = parseCommits(rawCommits, resolved);
|
|
2828
|
-
const contributors = resolved.contributors ? await resolveAuthors(commits, resolved) : [];
|
|
2829
|
-
const highlights = await readHighlights(resolved);
|
|
2830
|
-
const md = generateMarkdown(commits, resolved, contributors, highlights);
|
|
2831
|
-
const discord = generateDiscordPayload(commits, resolved, contributors, highlights);
|
|
2832
|
-
return { config: resolved, md, discord, commits, contributors };
|
|
2833
|
-
}
|
|
2834
|
-
|
|
2835
|
-
// src/cli.ts
|
|
2836
|
-
async function reporting(argv, run) {
|
|
2837
|
-
const end = argv.indexOf("--");
|
|
2838
|
-
const json = (end === -1 ? argv : argv.slice(0, end)).includes("--json");
|
|
2839
|
-
const reports = [];
|
|
2840
|
-
const code = await stdoutToStderr(json, async () => run(argv, (value) => reports.push(value)));
|
|
2841
|
-
if (json && reports[0] !== undefined)
|
|
2842
|
-
printJson(reports[0]);
|
|
2843
|
-
return code;
|
|
2844
|
-
}
|
|
2845
|
-
function failed(e, debug) {
|
|
2846
|
-
if (e instanceof Exit)
|
|
2847
|
-
throw e;
|
|
2848
|
-
if (debug === true && e instanceof Error && e.stack !== undefined)
|
|
2849
|
-
console.error(err().dim(e.stack.split(`
|
|
68
|
+
`}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_text2();import{appendFileSync,mkdirSync,readFileSync as readFileSync4,renameSync,statSync as statSync2,writeFileSync}from"fs";import{homedir as homedir3}from"os";import{dirname as dirname2,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,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)}}}function trimUsage(path,maxBytes){let info=statSync2(path,{throwIfNoEntry:!1});if(info===void 0||info.size<=maxBytes)return;let lines=readFileSync4(path,"utf8").split(`
|
|
69
|
+
`).filter(Boolean),kept=`${lines.slice(Math.floor(lines.length/2)).join(`
|
|
70
|
+
`)}
|
|
71
|
+
`,temp=`${path}.${process13.pid}.tmp`;writeFileSync(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);mkdirSync(dirname2(path),{recursive:!0,mode:448}),appendFileSync(path,`${JSON.stringify(entry)}
|
|
72
|
+
`,{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"}};async function commandRows(all,colors){let commands=shown(all),width=Math.max(0,...Object.keys(commands).map((name)=>name.length)),groups=new Map([["Commands:",[]]]),summaries=await Promise.all(Object.values(commands).map(async({summary})=>resolveSummary(summary)));for(let[index,[name,{group}]]of Object.entries(commands).entries()){let heading=group===void 0?"Commands:":`${group}:`,rows=groups.get(heading)??[];rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`),groups.set(heading,rows)}return[...groups].filter(([,rows])=>rows.length>0).flatMap(([heading,rows],index)=>[...index===0?[]:[""],colors.bold(heading),...rows])}function shown(commands){return Object.fromEntries(Object.entries(commands).filter(([,{hidden}])=>hidden!==!0))}function takeOutputFlags(argv){let index=0;for(;index<argv.length;index++){let word=argv[index];if(word==="--plain")applyOutput(void 0,!0);else if(word.startsWith("--color="))applyOutput(word.slice(8),void 0);else if(word==="--color"&&argv[index+1]!==void 0)applyOutput(argv[++index],void 0);else break}return argv.slice(index)}async function resolveSummary(summary){return typeof summary==="string"?summary:summary()}function lookup({commands,aliases},word){let name=aliases!==void 0&&Object.hasOwn(aliases,word)?aliases[word]??word:word;return Object.hasOwn(commands,name)?commands[name]:void 0}function scopeOf(commands,extra,aliases){return{commands:typeof commands==="function"?{}:commands,lazy:[...typeof commands==="function"?[commands]:[],...extra===void 0?[]:[extra]],aliases}}async function expand(scope,words){if(scope.lazy.length===0)return scope;let commands={...scope.commands};for(let added of await Promise.all(scope.lazy.map(async(lazy)=>lazy(words))))for(let[name,command]of Object.entries(added))commands[name]??=command;return{...scope,commands,lazy:[]}}async function help2({path,header,summary:lazySummary,commands,defaultCommand,examples,replaces},stream){let colors=paint(stream),prefix=path.join(" "),summary=await resolveSummary(lazySummary);if(wantsHelpJson())return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`,{examples,replaces}));let columns=takesControlCodes(stream)?stream.columns:void 0,fallback=defaultCommand===void 0?void 0:commands[defaultCommand],options=fallback!==void 0&&"run"in fallback?await optionsOf(fallback.run):void 0,own=Object.entries(options??{}).filter(([name])=>!(name in TOP_OPTIONS));return[header(colors,summary),"",usageLine(`${prefix} ${defaultCommand===void 0?colors.cyan("<command>"):`[${colors.cyan("<command>")}]`} [options]`,colors),"",...await commandRows(commands,colors),...own.length===0?[]:["",`${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`,...optionRows(Object.fromEntries(own),colors,columns)],"",colors.bold("Options:"),...optionRows(path.length===1?TOP_OPTIONS:LEVEL_OPTIONS,colors,columns),...exampleRows(examples??[],colors),"",`${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`].join(`
|
|
73
|
+
`)}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?"":`
|
|
74
|
+
${styled?tint(label):`${label}:`} ${text}`;console.error(`${head} ${message}${under("cause",cause,colors.dim)}${under("hint",hint,colors.yellow)}`)}function printJsonError(message,hint,cause){console.error(JSON.stringify({error:message,...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 help=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?printJsonError:(message,hint,causeText)=>printError(prefix,message,hint,causeText))(redact(named??(error instanceof Error?error.message:String(error))),error instanceof Exit?error.hint??help:void 0,cause),error instanceof Exit?error.code:1}async function dispatch(level,typed,{version,redact}){let prefix=level.path.join(" "),argv;try{argv=takeOutputFlags(typed)}catch(error){return{code:reportThrown(prefix,error),meta:!1}}let[name,...args]=argv,fallback=level.defaultCommand===void 0?void 0:level.commands[level.defaultCommand];if(name===void 0&&level.runBare&&fallback!==void 0&&"run"in fallback)try{return{code:await fallback.run([]),meta:!1}}catch(error){return{code:reportThrown(`${prefix} ${level.defaultCommand}`,error,redact,!1),meta:error instanceof HelpShown}}if(name===void 0&&level.path.length>1)return console.error(await help2(await expand(level,[...level.path.slice(1),...argv]),process14.stderr)),{code:2,meta:!0};if(name==="help"&&args.length>0)return dispatch(level,[...args,"--help"],{version,redact});if(name===void 0||name==="help"||name==="--help"||name==="-h")return console.log(await help2(await expand(level,[...level.path.slice(1),...argv]),process14.stdout)),{code:0,meta:!0};if(level.path.length===1&&(name==="--version"||name==="-v"))return console.log(version()),{code:0,meta:!0};let command=lookup(level,name),rest=args,ran=name;if(command===void 0&&level.lazy.length>0)level=await expand(level,[...level.path.slice(1),...argv]),command=lookup(level,name);if(command===void 0&&level.defaultCommand!==void 0)command=level.commands[level.defaultCommand],rest=argv,ran=level.defaultCommand;if(command===void 0){let meant=closest(name,Object.keys(shown(level.commands)));return printError(prefix,`no command ${name}`,meant===void 0?`run ${prefix} --help for its commands`:`did you mean ${meant}?`),{code:2,meta:!1}}if("commands"in command){let{summary}=command;return dispatch({path:[...level.path,name],header:(colors,text)=>`${colors.bold(`${prefix} ${name}`)} ${text}`,summary,...scopeOf(command.commands,command.extraCommands,command.aliases),defaultCommand:void 0,runBare:!1,examples:command.examples,replaces:void 0},rest,{version,redact})}try{return{code:await command.run(rest),meta:!1}}catch(error){return{code:reportThrown(`${prefix} ${ran}`,error,redact,wantsJson(rest)),meta:error instanceof HelpShown}}}var COMPLETE="__complete",FILES="__files__";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({})}async function optionsOf(run){return(await completingOf(run)).options}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)}async function candidates(scope,defaultCommand,words,before=[]){let[word="",...rest]=words,listing=rest.length===0&&!word.startsWith("-"),{commands}=scope,command=lookup(scope,word);if(listing||command===void 0){let expanded=await expand(scope,[...before,...words]);commands=expanded.commands,command=lookup(expanded,word)}if(listing){let own=await Promise.all(Object.entries(shown(commands)).map(async([name,{summary}])=>`${name} ${await resolveSummary(summary)}`)),fallback=defaultCommand===void 0?void 0:commands[defaultCommand],values=fallback!==void 0&&"run"in fallback?await leafCandidates(fallback.run,[word]):[],valueOf=(line)=>line.slice(0,line.includes("\t")?line.indexOf("\t"):void 0);return[...own,...values.filter((line)=>line!==FILES&&!Object.hasOwn(commands,valueOf(line)))]}if(command===void 0){let fallback=defaultCommand===void 0?void 0:commands[defaultCommand];return fallback!==void 0&&"run"in fallback?leafCandidates(fallback.run,words):[]}return"commands"in command?candidates(scopeOf(command.commands,command.extraCommands,command.aliases),void 0,rest,[...before,word]):leafCandidates(command.run,rest)}var COMPLETIONS="--completions";function flagValue([flag="",...rest]){return flag.includes("=")?[flag.slice(flag.indexOf("=")+1),...rest]:rest}function printCompletionScript(name,args){let shell=COMPLETION_SHELLS.find((each)=>each===args[0]);if(shell===void 0||args.length!==1)return printError(name,`${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`,`${name} ${COMPLETIONS} fish`),2;return console.log(completionScript(shell,[name]).trimEnd()),0}async function printCandidates(found){for(let line of await found)console.log(line);return 0}function packageVersion(entry=Bun.main){let resolved=entry;try{resolved=realpathSync2(entry)}catch{}for(let dir=dirname3(resolved);;dir=dirname3(dir)){try{let{version}=JSON.parse(readFileSync5(join5(dir,"package.json"),"utf8"));if(typeof version==="string")return version}catch{}if(dirname3(dir)===dir)return"0.0.0"}}async function runCli(cli,argv=scriptArgs()){let answered=await askpassClient(argv);if(answered!==void 0)return answered;if(argv[0]===COMPLETE)return printCandidates(candidates(scopeOf(cli.commands,cli.extraCommands,cli.aliases),cli.defaultCommand,argv.slice(1)));if(argv[0]===COMPLETIONS||argv[0]?.startsWith(`${COMPLETIONS}=`)===!0)return printCompletionScript(cli.name,flagValue(argv));let version=()=>cli.version??packageVersion(),started=performance.now(),{code,meta}=await dispatch({path:[cli.name],header:(colors,about)=>`${colors.bold(cli.name)} ${colors.dim(version())} ${about}`,summary:cli.about,...scopeOf(cli.commands,cli.extraCommands,cli.aliases),defaultCommand:cli.defaultCommand,runBare:cli.runBare===!0,examples:cli.examples,replaces:cli.replaces},argv,{version,redact:cli.redact}),command=commandPath(scopeOf(cli.commands,cli.extraCommands,cli.aliases),argv);if(notifyEnd(command===void 0?cli.name:`${cli.name} ${command}`,code,performance.now()-started),cli.usage!==!1&&!meta)try{recordUsage(usageEntry(cli.name,command,argv,code,{ms:performance.now()-started}))}catch{}return code}function commandPath(scope,argv){let path=[],level=scope;for(let word of argv.filter((each)=>!each.startsWith("-"))){let command=lookup(level,word);if(command===void 0)break;if(path.push(word),!("commands"in command))break;level=scopeOf(command.commands,command.extraCommands,command.aliases)}return path.length===0?void 0:path.join(" ")}init_config();init_text2();init_folders();init_format();init_args();init_args();init_mode();init_style();init_text2();var{Glob}=globalThis.Bun;var SESSION_FILES=new Glob("*.json"),ACCOUNT_DIRS=new Glob("*/sessions");init_style();init_text2();init_theme();init_user_config();init_args();init_input();init_style();init_user_config();init_prompt();init_chunk_yfkscv18();var W=1000,ht=60*W,Ue=60*ht,S=24*Ue,ei=7*S;var Y=[[n.y,"year"],[n.M,"month"],[n.w,"week"],[n.d,"day"],[n.h,"hour"],[n.m,"minute"],[n.s,"second"]];var T=15*W;function l(e,n){if(n===void 0)return e??void 0;let t=AbortSignal.timeout(n);return e?AbortSignal.any([e,t]):t}function w(e){if(typeof e!=="object"||e===null)return!1;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function J(e,{signal:n}={}){return new Promise((t,o)=>{if(n?.aborted)return o(n.reason);let r=setTimeout(()=>{n?.removeEventListener("abort",s),t()},e);function s(){clearTimeout(r),o(n.reason)}n?.addEventListener("abort",s,{once:!0})})}init_chunk_rkhsft4a();async function ae(r,{attempts:t=3,delay:s=1000,backoff:m=2,maxDelay:o=1/0,jitter:i=!1,shouldRetry:a,onRetry:u,signal:l}={}){let c=i===!0?1:Number(i),e;for(let n=0;n<t+1;n++){l?.throwIfAborted();try{return await r(n)}catch(f){if(e=f,a&&!a(f,n))throw f;if(n<t){let p=Math.min(s*m**n,o)*(1-c*Math.random());u?.(f,n,p),await J(p,{signal:l})}}}throw Error(`Failed after ${t} ${G("retry",t)}`,{cause:e})}function s(...e){let r=new Headers;for(let n of e){if(!n)continue;let i;if(n instanceof Headers)i=[...n];else i=Array.isArray(n)?n:Object.entries(n);for(let[a,t]of i)if(t!==void 0)r.set(a,t)}return r}function T2(e){return w(e)||Array.isArray(e)}function J2(e){return typeof e==="string"||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||e instanceof FormData||e instanceof URLSearchParams||e instanceof ReadableStream||typeof Blob<"u"&&e instanceof Blob}var b2="http://relative.invalid";function I(e){try{return{parsed:new URL(e),relative:!1}}catch{return{parsed:new URL(e,b2),relative:!0}}}function B2(e,r){if(!r)return e;let{parsed:n,relative:i}=I(e);for(let[t,o]of Object.entries(r))for(let u of Array.isArray(o)?o:[o])if(u!==void 0)n.searchParams.append(t,String(u));if(!i)return n.href;let a=`${n.pathname}${n.search}${n.hash}`;return n.origin===b2?a:`//${n.host}${a}`}function E(e){if(!e)return;try{return JSON.parse(e)}catch{return}}function v(e){if(!w(e))return;for(let r of["error","message","detail"])if(typeof e[r]==="string"&&e[r])return e[r];return}class ie extends Error{status;statusText;url;body;data;said;constructor(e,r,n,i,a){let t=v(a),o=t??i;super(`HTTP ${e} ${r} - ${n}${o?` - ${o}`:""}`);this.status=e,this.statusText=r,this.url=n,this.body=i,this.data=a,this.name="FetchError",this.said=t}}async function x(e,r){let n;try{n=await e.text()}catch{n=""}return new ie(e.status,e.statusText,e.url||r,n||void 0,E(n))}class _e extends Error{url;body;constructor(e,r,n){super(`Invalid JSON response from ${e} - ${r.slice(0,200)}`,{cause:n});this.url=e,this.body=r,this.name="FetchParseError"}}function q(e){if(e instanceof ie)return e.status===408||e.status===429||e.status>=500;return e instanceof TypeError||e instanceof DOMException&&e.name==="TimeoutError"}async function c(e,r={}){let{retry:n,onError:i,...a}=r,{signal:t}=a;try{let o=H2(e,a);if(!n)return await m(o);let{attempts:u=3,shouldRetry:d=q,...f}=typeof n==="number"?{attempts:n}:n;return await ae(()=>m(o),{...f,attempts:u,signal:t??void 0,shouldRetry:(p,y)=>y<u&&!t?.aborted&&d(p,y)})}catch(o){throw i?.(o),o}}function A(e,r,n){if(e===void 0||e===null)return null;return r?n(e):e}function H2(e,r){let{baseUrl:n,token:i,query:a,body:t,headers:o,timeout:u,signal:d,onResponse:f,fetch:p=fetch,parse:y=JSON.parse,serialize:R=JSON.stringify,...k}=r,g=B2(n?new URL(e,n).href:e,a),h=T2(t);if(t!==void 0&&t!==null&&!h&&!J2(t))throw TypeError(`Unsupported body type for ${g}: ${Object.getPrototypeOf(t)?.constructor?.name??typeof t}`);let O=s({Accept:"application/json","Content-Type":h?"application/json":void 0,Authorization:i?`Bearer ${i}`:void 0},o);return{fullUrl:g,init:{...k,headers:O,body:A(t,h,R)},fetcher:p,parse:y,onResponse:f,timeout:u,signal:d}}async function m({fullUrl:e,init:r,fetcher:n,parse:i,onResponse:a,timeout:t,signal:o}){let u=l(o,t),d=await n(e,{...r,...u?{signal:u}:{}});if(a?.(d),!d.ok)throw await x(d,e);let f=await d.text();if(!f)return null;try{return i(f)}catch(p){throw new _e(d.url||e,f,p)}}async function cr(r,t,o=[],s={}){let n=new FormData;n.append("payload_json",JSON.stringify(t));for(let e=0;e<o.length;++e){let i=o[e],p=new Blob([new Uint8Array(i.buffer)],{type:i.contentType??"image/png"});n.append(`files[${e}]`,p,i.filename)}return await c(r,{...s,timeout:s.timeout??T,method:"POST",body:n})}var version="2.4.2";var shared={token:{type:"string",description:"The forge's token, defaults to GITHUB_TOKEN, then on GitHub to gh's login"},from:{type:"string",description:"From tag"},to:{type:"string",description:"To tag"},repo:{type:"string",short:"r",description:"Repository, e.g. kaynooo/cli, origin's by default (--gitea is kept as an alias)"},"release-repo":{type:"string",description:"Release repository, defaults to --repo (--release-gitea is kept as an alias)"},name:{type:"string",description:"Name of the release"},contributors:{type:"boolean",description:"Show contributors"},prerelease:{type:"boolean",description:"Mark release as prerelease"},draft:{type:"boolean",short:"d",description:"Mark release as draft"},output:{type:"string",description:"Output to file instead of sending to the forge"},capitalize:{type:"boolean",description:"Capitalize each commit message"},emoji:{type:"boolean",description:"Use emojis in section titles, --no-emoji to drop them"},group:{type:"boolean",description:"Nest commit messages under their scopes"},"first-parent":{type:"boolean",description:"Walk only the first parent of each merge"},"discord-webhook":{type:"string",description:"Discord webhook to post the release to, defaults to DISCORD_WEBHOOK"},"dry-run":{type:"boolean",description:"Dry run (--dry is kept as an alias)"},assets:{type:"string",multiple:!0,description:"Files to upload as assets to the release, repeatable or comma separated; quote globs, e.g. --assets 'dist/*.js'"},json:jsonOption("release: {command, status, from, to, commits, notes, url, output, assetsFailed, discord}; undo: {command, status, tag, releaseNote, remoteTag, localTag, commitReset}. Progress goes to stderr"),debug:{type:"boolean",description:"Print the stack of an unexpected error"}},undoFlags={...shared,note:{type:"boolean",description:"Also delete the release note on the forge (skips the question)"},yes:{type:"boolean",description:"Skip confirmation prompts"}},ALIASES={"--dry":"--dry-run","--gitea":"--repo","--release-gitea":"--release-repo"};function aliasFlags(argv){let end=argv.indexOf("--");return[...(end===-1?argv:argv.slice(0,end)).map((word)=>{let[name="",...value]=word.split("="),current=ALIASES[name];return current===void 0?word:[current,...value].join("=")}),...end===-1?[]:argv.slice(end)]}function defined(values){return Object.fromEntries(Object.entries(values).filter(([,value])=>value!==void 0))}function toOptions(args){return defined({token:args.token,from:args.from,to:args.to,repo:args.repo,releaseRepo:args["release-repo"],name:args.name,contributors:args.contributors,prerelease:args.prerelease,draft:args.draft,output:args.output,capitalize:args.capitalize,emoji:args.emoji,group:args.group,firstParent:args["first-parent"],discordWebhook:args["discord-webhook"],dry:args["dry-run"],assets:args.assets})}function withToken(options){let token=[options.token,process.env.GITHUB_TOKEN].find((value)=>value!==void 0&&value!=="");return token===void 0?options:{...options,token}}function shouldAskNote({release,note,yes,dry}){return Boolean(release)&¬e!==!0&&yes!==!0&&dry!==!0}import path from"path";var out=()=>paint(process.stdout),err=()=>paint(process.stderr);async function stdoutToStderr(active,body){let log=console.log;if(active)console.log=(...args)=>console.error(...args.length===0?[""]:args);try{return await body()}finally{console.log=log}}var REQUEST_MS=60000;function onGithub(options){return options.provider==="github"}function tagPath(options,repo,tag,write=!1){return onGithub(options)?`repos/${repo}/git/${write?"refs":"ref"}/tags/${encodeURIComponent(tag)}`:`repos/${repo}/tags/${encodeURIComponent(tag)}`}async function request(url,init){let res=await fetch(url,{...init,signal:AbortSignal.timeout(REQUEST_MS)});if(!res.ok)throw Error(`${res.status} ${res.statusText}: ${await res.text()}`);return res}async function api(url,init){return await(await request(url,init)).json()}async function sendRelease(options,content){let headers=getHeaders(options),url=`https://${options.baseUrlApi}/repos/${options.releaseRepo}/releases`,method="POST";try{let exists=await api(`https://${options.baseUrlApi}/repos/${options.releaseRepo}/releases/tags/${encodeURIComponent(options.to??"")}`,{headers});if(exists.url)url=exists.url,method="PATCH"}catch{}let body={body:content,draft:options.draft||!1,name:options.name??options.to,prerelease:options.prerelease,tag_name:options.to};console.log(out().cyan(method==="POST"?"Creating release notes...":"Updating release notes..."));let res=await api(url,{method,body:JSON.stringify(body),headers:{...headers,"content-type":"application/json"}});return console.log(out().green(`Released on ${res.html_url}`)),res.html_url}async function getRelease(options,tag){try{return await api(`https://${options.baseUrlApi}/repos/${options.releaseRepo}/releases/tags/${encodeURIComponent(tag)}`,{headers:getHeaders(options)})}catch{return null}}async function deleteRelease(options,releaseId){await request(`https://${options.baseUrlApi}/repos/${options.releaseRepo}/releases/${releaseId}`,{method:"DELETE",headers:getHeaders(options)})}async function hasRemoteTag(options,tag){try{return await api(`https://${options.baseUrlApi}/${tagPath(options,options.releaseRepo,tag)}`,{headers:getHeaders(options)}),!0}catch{return!1}}async function deleteRemoteTag(options,tag){await request(`https://${options.baseUrlApi}/${tagPath(options,options.releaseRepo,tag,!0)}`,{method:"DELETE",headers:getHeaders(options)})}function getHeaders(options){if(onGithub(options))return{accept:"application/vnd.github+json",authorization:`Bearer ${options.token}`,"x-github-api-version":"2022-11-28"};return{accept:"application/vnd.gitea.v3+json",authorization:`token ${options.token}`}}var excludeAuthors=[/\[bot\]/i,/dependabot/i,/\(bot\)/i];async function resolveAuthorInfo(options,info){if((info.login??"")!=="")return info;if((options.token??"")==="")return info;if(info.commits.length)try{let data=await api(`https://${options.baseUrlApi}/repos/${options.repo}/${onGithub(options)?"commits":"git/commits"}/${info.commits[0]}`,{headers:getHeaders(options)});if(data.author!==null)info.login=data.author.login,info.avatar=data.author.avatar_url}catch{}if((info.login??"")!==""||onGithub(options))return info;try{let user=(await api(`https://${options.baseUrlApi}/users/search?q=${encodeURIComponent(info.email)}`,{headers:getHeaders(options)})).data.find((user)=>user.email.toLowerCase()===info.email.toLowerCase());if(user!==void 0){if(info.login=user.login,user.avatar_url!==void 0)info.avatar=user.avatar_url}}catch{}return info}async function resolveAuthors(commits,options){let map=new Map;for(let commit of commits)for(let[idx,author]of commit.authors.entries()){if(!author.email||!author.name||excludeAuthors.some((re)=>re.test(author.name)))continue;if(!map.has(author.email))map.set(author.email,{commits:[],name:author.name,email:author.email});if(idx===0)map.get(author.email).commits.push(commit.shortHash)}let authors=Array.from(map.values()),resolved=await Promise.all(authors.map(async(info)=>resolveAuthorInfo(options,info))),loginSet=new Set,nameSet=new Set;return resolved.sort((a,b)=>(a.login??a.name).localeCompare(b.login??b.name)).filter((i)=>{if(i.login!==void 0&&loginSet.has(i.login))return!1;if(i.login!==void 0)loginSet.add(i.login);else{if(nameSet.has(i.name))return!1;nameSet.add(i.name)}return!0})}async function hasTagOnGitea(tag,options){try{let url=`https://${options.baseUrlApi}/${tagPath(options,options.repo,tag)}`;return console.log(`checking if tag exists on ${url}`),await api(url,{headers:getHeaders(options)}),!0}catch{return!1}}async function uploadAssets(options,assets){let headers=getHeaders(options),assetList=[];if(typeof assets==="string")assetList=assets.split(",").map((s)=>s.trim()).filter(Boolean);else if(Array.isArray(assets))assetList=assets.flatMap((item)=>typeof item==="string"?item.split(",").map((s)=>s.trim()):[]).filter(Boolean);let expandedAssets=[];for(let pattern of assetList)try{let glob=new Bun.Glob(pattern),matches=Array.from(glob.scanSync());if(matches.length)expandedAssets.push(...matches);else expandedAssets.push(pattern)}catch(error){console.error(err().red(`Failed to process glob pattern "${pattern}": ${String(error)}`)),expandedAssets.push(pattern)}let release=await api(`https://${options.baseUrlApi}/repos/${options.releaseRepo}/releases/tags/${encodeURIComponent(options.to??"")}`,{headers}),failed=0;for(let asset of expandedAssets){let filePath=path.resolve(asset),file=Bun.file(filePath);if(!await file.exists()){console.error(err().red(`Failed to read file ${filePath}: file does not exist`)),failed++;continue}let fileName=path.basename(filePath),assetsPath=`repos/${options.releaseRepo}/releases/${release.id}/assets?name=${encodeURIComponent(fileName)}`;console.log(out().cyan(`Uploading ${fileName}...`));try{if(onGithub(options))await request(`https://uploads.github.com/${assetsPath}`,{method:"POST",headers:{...headers,"content-type":"application/octet-stream"},body:file});else{let form=new FormData;form.append("attachment",file,fileName),await request(`https://${options.baseUrlApi}/${assetsPath}`,{method:"POST",headers,body:form})}console.log(out().green(`Uploaded ${fileName} successfully.`))}catch(error){console.error(err().red(`Failed to upload ${fileName}: ${String(error)}`)),failed++}}return failed}import{join as join6}from"path";var{$:$2}=globalThis.Bun;var o2=/^(\d+)\.(\d+)\.(\d+)$/;function wn(r){return o2.test(r)}function Z(r){let n=o2.exec(r);if(!n)throw Error(`Invalid semver: "${r}"`);return{major:Number(n[1]),minor:Number(n[2]),patch:Number(n[3])}}var{$}=globalThis.Bun;var gitSuffixRE=/\.git$/,sshRegex=/(?:ssh:\/\/[^/]+\/|^(?:[^@/\s]+@)?[^:/\s]+:)(\w[\w.-]*)\/(\w[\w.-]*)$/i,regexSpecialRE=/[.*+?^${}()|[\]\\]/g,httpsRegex=/https?:\/\/[^/]+\/(\w[\w.-]*)\/(\w[\w.-]*)$/i,releaseVersionRE=/^[^.]*(?:\.[\d.]*|\d)$/,TAG_DECORATION=/tag: ([^,\n]+)/g,ORIGIN_HOST=/^(?:[a-z][a-z\d+.-]*:\/\/)?(?:[^@/]+@)?([^:/]+)/i;async function getOriginHost(){let url=(await $`git config --get remote.origin.url`.quiet().nothrow().text()).trim();return ORIGIN_HOST.exec(url)?.[1]}async function getGiteaRepo(){let url=await execCommand("git",["config","--get","remote.origin.url"]),cleanUrl=url.replace(gitSuffixRE,""),match=sshRegex.exec(cleanUrl);if(match||=httpsRegex.exec(cleanUrl),!match)throw Error(`Can not parse Gitea repo from url ${url}`);return`${match[1]}/${match[2]}`}async function getCurrentGitBranch(){let[tag]=(await execCommand("git",["tag","--points-at","HEAD","--sort=-v:refname"])).split(`
|
|
75
|
+
`);return tag!==void 0&&tag!==""?tag:execCommand("git",["rev-parse","--abbrev-ref","HEAD"])}async function isRepoShallow(){return(await execCommand("git",["rev-parse","--is-shallow-repository"])).trim()==="true"}function getSafeTagTemplate(template){return template.includes("%s")?template:`${template}%s`}function getVersionString(template,tag){let pattern=template.split("%s").map((part)=>part.replace(regexSpecialRE,"\\$&")).join("(.+)");return new RegExp(`^${pattern}$`).exec(tag)?.[1]??tag}async function tipOf(to){return(await $`git rev-parse --verify -q ${`${to}^{commit}`}`.quiet().nothrow()).exitCode===0?to:"HEAD"}async function getGitTags(firstParent=!1,to="HEAD"){return[...(await execCommand("git",["log",...firstParent?["--first-parent"]:[],"--decorate-refs=refs/tags/","--format=%D",await tipOf(to),"--"])).matchAll(TAG_DECORATION)].map((match)=>match[1]?.trim()??"").filter((tag)=>tag!=="")}async function getLastMatchingTag(inputTag,tagFilter,tagTemplate,rollup={},firstParent=!1){let inputVersionString=getVersionString(tagTemplate,inputTag),isStableVersion=wn(inputVersionString),filteredTags=(await getGitTags(firstParent,inputTag)).filter(tagFilter),tag;if(isStableVersion){let input=Z(inputVersionString),isMajor=input.minor===0&&input.patch===0,isMinor=!isMajor&&input.patch===0,boundary;if(isMajor&&rollup.major)boundary=(v)=>v.minor===0&&v.patch===0;else if(isMinor&&rollup.minor)boundary=(v)=>v.patch===0;tag=filteredTags.find((tag)=>{let versionString=getVersionString(tagTemplate,tag);if(versionString===inputVersionString||!wn(versionString))return!1;return boundary?boundary(Z(versionString)):!0})}return tag||=filteredTags.find((tag)=>tag!==inputTag),tag}async function isRefGitTag(to){let ref=`refs/tags/${to}`;try{return await $`git show-ref --verify ${ref}`.quiet(),!0}catch{return!1}}async function getFirstGitCommit(firstParent=!1,to="HEAD"){return(await execCommand("git",["rev-list","--max-parents=0",...firstParent?["--first-parent"]:[],await tipOf(to),"--"])).split(`
|
|
76
|
+
`).at(-1)??""}async function deleteLocalTag(tag){await $`git tag -d ${tag}`.quiet()}async function hasRemoteGitTag(tag,remote="origin"){return(await execCommand("git",["ls-remote","--tags",remote,`refs/tags/${tag}`])).length>0}async function deleteRemoteGitTag(tag,remote="origin"){await $`git push ${remote} --delete ${tag}`.quiet()}async function getTagCommit(tag){return execCommand("git",["rev-list","-n","1",tag])}async function getHeadCommit(){return execCommand("git",["rev-parse","HEAD"])}async function getCommitSubject(ref){return execCommand("git",["log","-1","--format=%s",ref])}async function softResetLastCommit(){await $`git reset --soft HEAD~1`.quiet()}function isPrerelease(version){return!releaseVersionRE.test(version)}async function execCommand(cmd,args){return(await $`${cmd} ${args}`.quiet().text()).trim()}var GITHUB="github.com";function forgeName(config){return config.provider==="github"?"GitHub":"Forgejo"}var configFiles=["ts","mts","js","mjs","json"].map((ext)=>`changelog.config.${ext}`),defaultConfig={scopeMap:{},types:{feat:{title:"\u2728 New"},fix:{title:"\uD83D\uDD27 Fixed"},perf:{title:"\u26A1 Faster"},refactor:{title:"refactor",folded:!0},docs:{title:"docs",folded:!0},build:{title:"build",folded:!0},types:{title:"types",folded:!0},test:{title:"test",folded:!0},style:{title:"style",folded:!0},ci:{title:"ci",folded:!0}},titles:{breakingChanges:"\u26A0\uFE0F Breaking",highlights:"\uD83C\uDF1F Highlights",maintenance:"\uD83E\uDDF9 Maintenance"},contributors:!0,capitalize:!0,group:!0,emoji:!0,firstParent:!1,tag:"v%s"};function isPlainObject(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function mergeLayers(...layers){let merged={};for(let layer of layers)for(let[key,value]of Object.entries(layer)){if(value===void 0)continue;merged[key]=isPlainObject(value)&&isPlainObject(merged[key])?mergeLayers(merged[key],value):value}return merged}async function loadConfigFile(cwd){for(let name of configFiles){let path=join6(cwd,name);if(await Bun.file(path).exists())return(await import(path)).default??{}}return{}}async function ghToken(){if(Bun.which("gh")===null)return;let answer=await $2`gh auth token`.quiet().nothrow();return answer.exitCode===0&&answer.text().trim()!==""?answer.text().trim():void 0}async function loadPackageConfig(cwd){let file=Bun.file(join6(cwd,"package.json"));return!await file.exists()?{}:(await file.json()).changelog??{}}async function loadConfig(options,cwd=process.cwd()){let[packageConfig,fileConfig]=await Promise.all([loadPackageConfig(cwd),loadConfigFile(cwd)]);return mergeLayers(defaultConfig,packageConfig,fileConfig,options)}async function resolveConfig(options){let config=await loadConfig(options),origin=config.baseUrl===void 0?await getOriginHost():void 0,baseUrl=config.baseUrl??(origin===GITHUB?origin:configuredForge()?.host??origin);if(baseUrl===void 0||baseUrl==="")throw Error("no forge to link the notes to: set baseUrl in the changelog config, forge in ~/.config/kaynooo-cli/config.json, or an origin remote");config.baseUrl=baseUrl,config.provider??=baseUrl===GITHUB?"github":"gitea",config.baseUrlApi??=config.provider==="github"?"api.github.com":`${baseUrl}/api/v1`;let token=config.provider==="github"&&(config.token??"")===""?await ghToken():void 0;if(token!==void 0)config.token=token;if(config.to||=await getCurrentGitBranch(),config.tagFilter??=()=>!0,config.tag=getSafeTagTemplate(config.tag??defaultConfig.tag),config.rollup??={},config.fromRoot=!1,config.from===void 0||config.from===""){let tag=await getLastMatchingTag(config.to,config.tagFilter,config.tag,config.rollup,config.firstParent);config.fromRoot=tag===void 0,config.from=tag??await getFirstGitCommit(config.firstParent,config.to)}let legacy=config;if(config.repo||=legacy.gitea??await getGiteaRepo(),config.releaseRepo||=legacy.releaseGithub??config.repo,config.prerelease??=isPrerelease(config.to),config.discordWebhook??=process.env.DISCORD_WEBHOOK??"",typeof config.repo!=="string")throw TypeError(`Invalid repository, expected a string but got ${JSON.stringify(config.repo)}`);return config}function p(n){return n!==null&&n!==void 0}function m2(n,e,t){Object.defineProperty(n,e,{value:t,enumerable:!0,writable:!0,configurable:!0})}function Fr(n,e){let t={};for(let o of n){let u=e(o);if(Object.hasOwn(t,u))t[u].push(o);else m2(t,u,[o])}return t}init_text();var emojiRE=/\p{Extended_Pictographic}\uFE0F?/gu,fullHashRE=/^[\da-f]{40}$/,IDENTIFIER_START=/^(?:`|[a-z]+[A-Z]|\S*\d|\S*[._/]\w)/;function groupCommits(commits,options){let breaking=commits.filter((c)=>c.isBreaking),byType=Fr(commits.filter((c)=>!c.isBreaking),(c)=>c.type),sections=breaking.length?[{title:options.titles.breakingChanges,commits:breaking}]:[],folded=[];for(let[type,config]of Object.entries(options.types)){let typed=byType[type]??[];if(typeof config==="boolean"||typed.length===0)continue;(config.folded===!0?folded:sections).push({title:config.title,commits:typed})}return{sections,folded}}function formatTitle(title,options){return(options.emoji?title:title.replace(emojiRE,"")).trim()}function shortRef(ref){return fullHashRE.test(ref)?ref.slice(0,7):ref}function repoUrl(options){return`https://${options.baseUrl}/${options.repo}`}function compareUrl(options){return`${repoUrl(options)}/compare/${options.from}...${options.to}`}function releaseUrl(options){return`https://${options.baseUrl}/${options.releaseRepo}/releases/tag/${encodeURIComponent(options.to)}`}function userUrl(login,options){return`https://${options.baseUrl}/${login}`}function formatIssue(ref,options,withTitle){return`[${withTitle&&ref.title!==void 0?`${ref.value} ${ref.title}`:ref.value}](${repoUrl(options)}/issues/${ref.value.slice(1)})`}function capitalized(description){return IDENTIFIER_START.test(description)?description:d(description)}function formatLine(commit,options,prefix="",issueTitles=!1){let description=options.capitalize?capitalized(commit.description):commit.description,hash=`[\`${commit.shortHash.slice(0,7)}\`](${repoUrl(options)}/commit/${commit.shortHash})`,issues=commit.references.filter((ref)=>ref.type!=="hash").map((ref)=>formatIssue(ref,options,issueTitles));return[`${prefix}${description}`,hash,...issues].join(" \xB7 ")}function foldedPrefix(commit){return`**${commit.scope?`${commit.type}(${commit.scope})`:commit.type}**: `}function foldedCounts(folded,options){return folded.map((section)=>`${section.commits.length} ${formatTitle(section.title,options)}`).join(", ")}function formatAuthors(contributors,options){return join7(contributors.map((c)=>c.login!==void 0?`[@${c.login}](${userUrl(c.login,options)})`:`**${c.name}**`))}function summaryLabel(title){return title.replace(emojiRE,"").trim().toLowerCase()}function formatSummary({sections,folded},contributors,options){let counts=sections.map((section)=>`${section.commits.length} ${summaryLabel(section.title)}`);if(folded.length){let total=folded.reduce((sum,section)=>sum+section.commits.length,0);counts.push(`${total} ${summaryLabel(options.titles.maintenance)}`)}let authors=formatAuthors(contributors,options);return`> ${[counts.length?`**${counts.join(" \xB7 ")}**`:"",authors&&`by ${authors}`,`\`${shortRef(options.from)}\` \u2192 \`${shortRef(options.to)}\``].filter(Boolean).join(" \xB7 ")}`}function formatSection(section,options){let lines=["",`### ${formatTitle(section.title,options)}`,""],scopes=Fr(section.commits,(c)=>c.scope),nestable=Object.entries(scopes).some(([scope,commits])=>scope!==""&&commits.length>1);for(let[scope,commits]of Object.entries(scopes).sort(([a],[b])=>a.localeCompare(b))){let scopeText=`**${scope}**`,nested=nestable&&scope!==""&&(options.group===!0||options.group==="multiple"&&commits.length>1),prefix=scope!==""&&!nested?`${scopeText}: `:"",padding=nested?" ":"";if(nested)lines.push(`- ${scopeText}:`);for(let commit of commits.toReversed())if(lines.push(`${padding}- ${formatLine(commit,options,prefix)}`),commit.breakingNote!==void 0)lines.push(`${padding} - ${commit.breakingNote}`)}return lines}function formatAvatars(contributors,options){return contributors.filter((c)=>c.login!==void 0&&c.avatar!==void 0).map((c)=>`<a href="${userUrl(c.login,options)}"><img src="${c.avatar}" width="28" height="28" alt="@${c.login}"></a>`).join(" ")}function generateMarkdown(commits,options,contributors=[],highlights){let grouped=groupCommits(commits,options),{sections,folded}=grouped,lines=[formatSummary(grouped,contributors,options)];if(highlights)lines.push("",`### ${formatTitle(options.titles.highlights,options)}`,"",...highlights.lines,"",`[Read more](${highlights.link})`);for(let section of sections)lines.push(...formatSection(section,options));if(folded.length)lines.push("","<details>",`<summary><b>${formatTitle(options.titles.maintenance,options)}</b> \xB7 ${foldedCounts(folded,options)}</summary>`,"",...folded.flatMap((section)=>section.commits.toReversed().map((commit)=>`- ${formatLine(commit,options,foldedPrefix(commit))}`)),"","</details>");if(!sections.length&&!folded.length)lines.push("","*No significant changes*");lines.push("","---","");let avatars=formatAvatars(contributors,options);if(avatars)lines.push(avatars,"");return lines.push(`<sub>[Full diff \`${shortRef(options.from)}...${shortRef(options.to)}\`](${compareUrl(options)}) \xB7 generated by cli-changelog</sub>`),lines.join(`
|
|
77
|
+
`)}function join7(array,glue=", ",finalGlue=" and "){return array.length<=2?array.join(finalGlue):`${array.slice(0,-1).join(glue)}${finalGlue}${array.at(-1)}`}var descriptionLimit=4096,color=16486972,breakingColor=15548997,fenceRE=/^\s*(`{3,}|~{3,})/,headingRE=/^#{1,6}(?:\s(.*))?$/,strongRE=/\*\*|__/g,isCommitLine=(line)=>line.startsWith("- ");function fitCommits(head,lines,tail){let total=lines.filter(isCommitLine).length;for(let kept=lines.length;kept>=0;kept--){let shown=lines.slice(0,kept);while(shown.length&&kept<lines.length&&!isCommitLine(shown.at(-1)))shown.pop();let more=total-shown.filter(isCommitLine).length,text=[...head,...shown,...more?["",`*\u2026and ${more} more*`]:[],"",tail].join(`
|
|
78
|
+
`).trim();if(text.length<=descriptionLimit)return text}return}function fitDescription(head,lines,tail){let fitted=fitCommits(head,lines,tail);if(fitted!==void 0||!head.length)return fitted??tail.slice(0,descriptionLimit);for(let kept=head.length-2;kept>=1;kept--){let shown=head.slice(0,kept),open=openFence(shown);if(open!==void 0)shown.push(open);let text=fitCommits([...shown,"\u2026",head.at(-1)],lines,tail);if(text!==void 0)return text}return tail.slice(0,descriptionLimit)}function openFence(lines){let open;for(let line of lines){let marker=fenceRE.exec(line)?.[1];if(marker!==void 0)open=open!==void 0&&marker.startsWith(open)?void 0:open??marker}return open}var tableRowRE=/^\s*\|.*\|\s*$/,tableRuleRE=/^\s*\|(?:\s*:?-+:?\s*\|)+\s*$/,cellSplitRE=/(?<!\\)\|(?=(?:[^`]*`[^`]*`)*[^`]*$)/;function bulletedTables(lines){let fenced=!1,out=[];for(let[index,line]of lines.entries()){if(fenceRE.test(line))fenced=!fenced;if(fenced||!tableRowRE.test(line)){out.push(line);continue}if(tableRuleRE.test(line)||tableRuleRE.test(lines[index+1]??""))continue;let[first="",...rest]=line.trim().slice(1,-1).split(cellSplitRE).map((cell)=>cell.trim());out.push(`- **${first}**${rest.length?`: ${rest.join(" \xB7 ")}`:""}`)}return out}function highlightLines(highlights,options){let fenced=!1,lines=bulletedTables(highlights.lines).flatMap((line)=>{if(fenceRE.test(line))fenced=!fenced;let heading=fenced?null:headingRE.exec(line);if(!heading)return[line];let text=(heading[1]??"").replace(strongRE,"").trim();return text?[`**${text}**`]:[]});return[`**${formatTitle(options.titles.highlights,options)}**`,...lines,`[Read more](${highlights.link})`]}function generateDiscordPayload(commits,options,contributors=[],highlights){let{sections,folded}=groupCommits(commits,options),lines=[];for(let section of sections){lines.push("",`**${formatTitle(section.title,options)}**`);for(let commit of section.commits.toReversed())lines.push(`- ${formatLine(commit,options,commit.scope?`**${commit.scope}**: `:"",!0)}`)}if(!sections.length&&!folded.length)lines.push("*No significant changes*");let links=`[full notes](${releaseUrl(options)}) \xB7 [diff](${compareUrl(options)})`,tail=folded.length?`${formatTitle(options.titles.maintenance,options)} *${foldedCounts(folded,options)}* \xB7 ${links}`:links,authors=contributors.map((c)=>c.login??c.name).join(", "),range=`${shortRef(options.from)} \u2192 ${shortRef(options.to)}`,avatar=contributors.find((c)=>c.avatar!==void 0)?.avatar;return{embeds:[{title:`${String(options.releaseRepo).split("/").at(-1)} ${options.name||options.to}`.slice(0,256),url:releaseUrl(options),color:commits.some((c)=>c.isBreaking)?breakingColor:color,description:fitDescription(highlights?highlightLines(highlights,options):[],lines,tail),footer:{text:authors?`${authors} \xB7 ${range}`:range,...avatar===void 0?{}:{icon_url:avatar}},timestamp:new Date().toISOString()}]}}var{$:$3}=globalThis.Bun;var ConventionalCommitRegex=/^(?::.+:|\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F\uDE80-\uDEFF]|[\u2600-\u2B55])? *(?<type>[a-z]+)(?:\((?<scope>[^()\n]+)\))?(?<breaking>!)?: (?<description>.+)/i,CoAuthoredByRegex=/co-authored-by:\s*(?<name>\S[^<]*)<(?<email>[^>]+)>/gi,PullRequestRE=/\([ a-z]*(#\d+)\s*\)/g,IssueRE=/(#\d+)/g,BreakingBodyRE=/^BREAKING[ -]CHANGE:[ \t]*(.*(?:\n(?![ \t]*$|[\w-]+(?:: | #)).+)*)/m,TicketLineRE=/^(#\d+) - (.+)$/gm;async function getGitDiff(from,to="HEAD",firstParent=!1){let range=`${from!==void 0&&from!==""?`${from}..`:""}${to}`,pretty="%x1e%s%x00%h%x00%an%x00%ae%x00%b";return(await $3`git --no-pager log ${range} ${firstParent?["--first-parent"]:[]} --pretty=${"%x1e%s%x00%h%x00%an%x00%ae%x00%b"}`.quiet().text()).split("\x1E").slice(1).map((record)=>{let[message="",shortHash="",authorName="",authorEmail="",body=""]=record.split("\x00");return{message,shortHash,author:{name:authorName,email:authorEmail},body:body.trim()}})}function parseGitCommit(commit,config){let match=commit.message.match(ConventionalCommitRegex);if(!match?.groups)return null;let type=(match.groups.type??"").toLowerCase(),breakingBody=BreakingBodyRE.exec(commit.body),breakingNote=breakingBody?.[1]?.replaceAll(/\s+/g," ").trim(),rawScope=match.groups.scope??"",scope=Object.hasOwn(config.scopeMap,rawScope)?config.scopeMap[rawScope]:rawScope,isBreaking=match.groups.breaking!==void 0||breakingBody!==null,description=match.groups.description??"",references=[];for(let m of description.matchAll(PullRequestRE))references.push({type:"pull-request",value:m[1]});for(let m of description.matchAll(IssueRE))if(!references.some((i)=>i.value===m[1]))references.push({type:"issue",value:m[1]});for(let m of commit.body.matchAll(TicketLineRE)){let known=references.find((i)=>i.value===m[1]);if(known)known.title=m[2].trim();else references.push({type:"issue",value:m[1],title:m[2].trim()})}references.push({value:commit.shortHash,type:"hash"}),description=description.replace(PullRequestRE,"").trim();let authors=[commit.author];for(let m of commit.body.matchAll(CoAuthoredByRegex))authors.push({name:(m.groups?.name??"").trim(),email:(m.groups?.email??"").trim()});return{...commit,authors,description,type,scope,references,isBreaking,...breakingNote===void 0||breakingNote===""?{}:{breakingNote}}}import{isAbsolute as isAbsolute2,join as join8}from"path";var fenceRE2=/^\s*(`{3,}|~{3,})/,headingRE2=/^(#{1,6})(\s.*)$/,schemeRE=/^[a-z][a-z\d+.-]*:/i,inlineLinkRE=/(\]\(\s*<?)((?:[^\s<>()]|\([^\s<>()]*\))+)/g,definitionRE=/^(\s{0,3}\[[^\]]+\]:\s*<?)([^\s<>]+)(>?(?:\s.*)?)$/,newlineRE=/\r?\n/,codeSpanRE=/(`+)[\s\S]*?\1/;function headingAnchor(text){return text.trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu,"").replace(/\s/g,"-")}function resolveTarget(written,base,link){let target=link?.(written)??written;if(schemeRE.test(target)||target.startsWith("//"))return target;try{return new URL(target,base).href}catch{return target}}function resolveLinks(line,base,link){let definition=definitionRE.exec(line);if(definition)return`${definition[1]}${resolveTarget(definition[2],base,link)}${definition[3]}`;let rest=line,out="";while(rest){let code=codeSpanRE.exec(rest),text=code?rest.slice(0,code.index):rest;if(out+=text.replace(inlineLinkRE,(_,open,target)=>`${open}${resolveTarget(target,base,link)}`),!code)break;out+=code[0],rest=rest.slice(code.index+code[0].length)}return out}function withoutAnchor(url){let hash=url.indexOf("#");return hash===-1?url:url.slice(0,hash)}function withoutFrontmatter(lines){if(lines[0]?.trim()!=="---")return lines;let end=lines.findIndex((line,index)=>index>0&&line.trim()==="---");return end===-1?lines:lines.slice(end+1)}function parseHighlights(source,version,url,link){let lines=withoutFrontmatter(source.split(newlineRE)),section=[],fence,inside=!1;for(let line of lines){let marker=fenceRE2.exec(line)?.[1];if(fence===void 0&&marker===void 0){let heading=headingRE2.exec(line);if(heading?.[1]==="##"){if(inside)break;inside=heading[2].trim()===version;continue}if(inside&&heading){section.push(`${"#".repeat(Math.min(heading[1].length+1,6))}${heading[2]}`);continue}}if(marker!==void 0)fence=fence!==void 0&&marker.startsWith(fence)?void 0:fence??marker;if(inside)section.push(fence!==void 0||marker!==void 0?line:resolveLinks(line,url,link))}while(section.length&&!section[0].trim())section.shift();while(section.length&&!section.at(-1).trim())section.pop();return!section.length?void 0:{lines:section,link:`${withoutAnchor(url)}#${headingAnchor(version)}`}}async function readHighlights(options,cwd=process.cwd()){let highlights=options.highlights;if(highlights===void 0)return;let{file,url,link}=highlights,source=Bun.file(isAbsolute2(file)?file:join8(cwd,file));if(!await source.exists())return;return parseHighlights(await source.text(),getVersionString(options.tag,options.to),url,link)}function parseCommits(commits,config){return commits.map((commit)=>parseGitCommit(commit,config)).filter(p)}async function generate(options){let resolved=await resolveConfig(options),rawCommits=await getGitDiff(resolved.fromRoot===!0?void 0:resolved.from,resolved.to,resolved.firstParent),commits=parseCommits(rawCommits,resolved),contributors=resolved.contributors?await resolveAuthors(commits,resolved):[],highlights=await readHighlights(resolved),md=generateMarkdown(commits,resolved,contributors,highlights),discord=generateDiscordPayload(commits,resolved,contributors,highlights);return{config:resolved,md,discord,commits,contributors}}async function reporting(argv,run){let end=argv.indexOf("--"),json=(end===-1?argv:argv.slice(0,end)).includes("--json"),reports=[],code=await stdoutToStderr(json,async()=>run(argv,(value)=>reports.push(value)));if(json&&reports[0]!==void 0)printJson(reports[0]);return code}function failed(e,debug){if(e instanceof Exit)throw e;if(debug===!0&&e instanceof Error&&e.stack!==void 0)console.error(err().dim(e.stack.split(`
|
|
2850
79
|
`).slice(1).join(`
|
|
2851
|
-
`)));
|
|
2852
|
-
return fail(e instanceof Error ? e.message : String(e), 1);
|
|
2853
|
-
}
|
|
2854
|
-
async function ask2(question) {
|
|
2855
|
-
return await confirm(question, { default: false, hint: "pass --yes to skip the questions" }) === true;
|
|
2856
|
-
}
|
|
2857
|
-
async function printManualRelease(config, md, heading) {
|
|
2858
|
-
const file = join9(tmpdir(), `changelog-${config.to.replaceAll("/", "-")}.md`);
|
|
2859
|
-
await Bun.write(file, md);
|
|
2860
|
-
console.log();
|
|
2861
|
-
console.error(err().yellow(heading));
|
|
2862
|
-
console.error(err().yellow(` https://${config.baseUrl}/${config.releaseRepo}/releases/new?tag=${encodeURIComponent(config.to)}`));
|
|
2863
|
-
console.error(err().yellow(` pasting the notes saved to ${file}`));
|
|
2864
|
-
console.log();
|
|
2865
|
-
}
|
|
2866
|
-
var RELEASE_EXITS = [[0, "it released, wrote --output or showed --dry-run"], [1, "the release could not be made (no token, the tag not on the forge, a shallow clone, an API error), an asset upload or the Discord post failed"], [2, "a usage error"]];
|
|
2867
|
-
async function release(argv, report) {
|
|
2868
|
-
const parsed = parse(argv, `usage: changelog release [options]
|
|
80
|
+
`)));return fail(e instanceof Error?e.message:String(e),1)}async function ask2(question){return await confirm(question,{default:!1,hint:"pass --yes to skip the questions"})===!0}async function printManualRelease(config,md,heading){let file=join9(tmpdir(),`changelog-${config.to.replaceAll("/","-")}.md`);await Bun.write(file,md),console.log(),console.error(err().yellow(heading)),console.error(err().yellow(` https://${config.baseUrl}/${config.releaseRepo}/releases/new?tag=${encodeURIComponent(config.to)}`)),console.error(err().yellow(` pasting the notes saved to ${file}`)),console.log()}var RELEASE_EXITS=[[0,"it released, wrote --output or showed --dry-run"],[1,"the release could not be made (no token, the tag not on the forge, a shallow clone, an API error), an asset upload or the Discord post failed"],[2,"a usage error"]];async function release(argv,report){let parsed=parse(argv,`usage: changelog release [options]
|
|
2869
81
|
|
|
2870
|
-
--json prints {command, status (released, dry-run or saved), from, to, commits, notes, url, output, assetsFailed, discord (posted, failed or null)} on stdout and the progress on stderr; a failure is {error} on stderr.`,
|
|
2871
|
-
const options = withToken(toOptions(parsed.values));
|
|
2872
|
-
let generated;
|
|
2873
|
-
let code = 0;
|
|
2874
|
-
try {
|
|
2875
|
-
console.log();
|
|
2876
|
-
console.log(out().dim(`changelog v${version}`));
|
|
2877
|
-
const { config, md, discord, commits } = await generate(options);
|
|
2878
|
-
const result = { command: "release", status: "released", from: config.from, to: config.to, commits: commits.length, notes: md, url: null, output: null, assetsFailed: 0, discord: null };
|
|
2879
|
-
generated = { config, md };
|
|
2880
|
-
console.log(role("accent", process.stdout)(config.from) + out().dim(" -> ") + role("path", process.stdout)(config.to) + out().dim(` (${commits.length} commits)`));
|
|
2881
|
-
console.log(out().dim("--------------"));
|
|
2882
|
-
console.log();
|
|
2883
|
-
console.log(md.replace(/ /g, ""));
|
|
2884
|
-
console.log();
|
|
2885
|
-
console.log(out().dim("--------------"));
|
|
2886
|
-
if (config.dry) {
|
|
2887
|
-
console.log(out().yellow(config.discordWebhook ? "Dry run. Release and Discord post skipped." : "Dry run. Release skipped."));
|
|
2888
|
-
await printManualRelease(config, md, "Create it manually at");
|
|
2889
|
-
report({ ...result, status: "dry-run" });
|
|
2890
|
-
return 0;
|
|
2891
|
-
}
|
|
2892
|
-
if (typeof config.output === "string") {
|
|
2893
|
-
await Bun.write(config.output, md);
|
|
2894
|
-
console.log(out().yellow(`Saved to ${config.output}`));
|
|
2895
|
-
report({ ...result, status: "saved", output: config.output });
|
|
2896
|
-
return 0;
|
|
2897
|
-
}
|
|
2898
|
-
if (!config.token) {
|
|
2899
|
-
await printManualRelease(config, md, "Create it manually at");
|
|
2900
|
-
fail(`no ${forgeName(config)} token found, pass --token or set GITHUB_TOKEN${config.provider === "github" ? ", or log in with gh auth login" : ""}, release skipped`, 1);
|
|
2901
|
-
}
|
|
2902
|
-
if (!await hasTagOnGitea(config.to, config)) {
|
|
2903
|
-
await printManualRelease(config, md, "Create it manually at");
|
|
2904
|
-
fail(`the ref "${config.to}" is not available as a tag on ${forgeName(config)}, release skipped`, 1);
|
|
2905
|
-
}
|
|
2906
|
-
if (!commits.length && await isRepoShallow()) {
|
|
2907
|
-
await printManualRelease(config, md, "Create it manually at");
|
|
2908
|
-
fail("the repo seems to be cloned shallowly, which makes changelog fail to generate, specify `fetch-depth: 0` in your CI config", 1);
|
|
2909
|
-
}
|
|
2910
|
-
result.url = await sendRelease(config, md);
|
|
2911
|
-
if (config.assets?.length) {
|
|
2912
|
-
result.assetsFailed = await uploadAssets(config, config.assets);
|
|
2913
|
-
if (result.assetsFailed > 0)
|
|
2914
|
-
code = 1;
|
|
2915
|
-
}
|
|
2916
|
-
if (config.discordWebhook) {
|
|
2917
|
-
try {
|
|
2918
|
-
await cr(config.discordWebhook, discord);
|
|
2919
|
-
console.log(out().green("Posted to Discord"));
|
|
2920
|
-
result.discord = "posted";
|
|
2921
|
-
} catch (e) {
|
|
2922
|
-
console.error(err().red(`Released, but the Discord post failed: ${String(e)}`));
|
|
2923
|
-
result.discord = "failed";
|
|
2924
|
-
code = 1;
|
|
2925
|
-
}
|
|
2926
|
-
}
|
|
2927
|
-
report(result);
|
|
2928
|
-
return code;
|
|
2929
|
-
} catch (e) {
|
|
2930
|
-
if (generated && !(e instanceof Exit))
|
|
2931
|
-
await printManualRelease(generated.config, generated.md, "Failed to create the release. Create it manually at");
|
|
2932
|
-
return failed(e, parsed.values.debug);
|
|
2933
|
-
}
|
|
2934
|
-
}
|
|
2935
|
-
var UNDO_EXITS = [[0, "it undid it, had nothing to undo, ran --dry-run or the question was declined"], [1, "a step fails"], [2, "a usage error"]];
|
|
2936
|
-
async function undo(argv, report) {
|
|
2937
|
-
const { values: args, positionals } = parse(argv, `usage: changelog undo [tag] [options]
|
|
82
|
+
--json prints {command, status (released, dry-run or saved), from, to, commits, notes, url, output, assetsFailed, discord (posted, failed or null)} on stdout and the progress on stderr; a failure is {error} on stderr.`,shared,{allowNegative:!0,positionals:[],exits:RELEASE_EXITS}),options=withToken(toOptions(parsed.values)),generated,code=0;try{console.log(),console.log(out().dim(`changelog v${version}`));let{config,md,discord,commits}=await generate(options),result={command:"release",status:"released",from:config.from,to:config.to,commits:commits.length,notes:md,url:null,output:null,assetsFailed:0,discord:null};if(generated={config,md},console.log(role("accent",process.stdout)(config.from)+out().dim(" -> ")+role("path",process.stdout)(config.to)+out().dim(` (${commits.length} commits)`)),console.log(out().dim("--------------")),console.log(),console.log(md.replace(/ /g,"")),console.log(),console.log(out().dim("--------------")),config.dry)return console.log(out().yellow(config.discordWebhook?"Dry run. Release and Discord post skipped.":"Dry run. Release skipped.")),await printManualRelease(config,md,"Create it manually at"),report({...result,status:"dry-run"}),0;if(typeof config.output==="string")return await Bun.write(config.output,md),console.log(out().yellow(`Saved to ${config.output}`)),report({...result,status:"saved",output:config.output}),0;if(!config.token)await printManualRelease(config,md,"Create it manually at"),fail(`no ${forgeName(config)} token found, pass --token or set GITHUB_TOKEN${config.provider==="github"?", or log in with gh auth login":""}, release skipped`,1);if(!await hasTagOnGitea(config.to,config))await printManualRelease(config,md,"Create it manually at"),fail(`the ref "${config.to}" is not available as a tag on ${forgeName(config)}, release skipped`,1);if(!commits.length&&await isRepoShallow())await printManualRelease(config,md,"Create it manually at"),fail("the repo seems to be cloned shallowly, which makes changelog fail to generate, specify `fetch-depth: 0` in your CI config",1);if(result.url=await sendRelease(config,md),config.assets?.length){if(result.assetsFailed=await uploadAssets(config,config.assets),result.assetsFailed>0)code=1}if(config.discordWebhook)try{await cr(config.discordWebhook,discord),console.log(out().green("Posted to Discord")),result.discord="posted"}catch(e){console.error(err().red(`Released, but the Discord post failed: ${String(e)}`)),result.discord="failed",code=1}return report(result),code}catch(e){if(generated&&!(e instanceof Exit))await printManualRelease(generated.config,generated.md,"Failed to create the release. Create it manually at");return failed(e,parsed.values.debug)}}var UNDO_EXITS=[[0,"it undid it, had nothing to undo, ran --dry-run or the question was declined"],[1,"a step fails"],[2,"a usage error"]];async function undo(argv,report){let{values:args,positionals}=parse(argv,`usage: changelog undo [tag] [options]
|
|
2938
83
|
|
|
2939
|
-
--json prints {command, status (undone, nothing, dry-run or declined), tag, releaseNote, remoteTag, localTag, commitReset: {hash, subject} or null} on stdout and the progress on stderr, each flag true when that step is (or, on a dry run, would be) taken. It asks no question: the release note is deleted with --note only, and anything to remove needs --yes or --dry-run (exit 2 otherwise).`,
|
|
2940
|
-
const json = args.json === true;
|
|
2941
|
-
let tag = positionals[0];
|
|
2942
|
-
const options = withToken(toOptions(args));
|
|
2943
|
-
try {
|
|
2944
|
-
console.log();
|
|
2945
|
-
console.log(out().dim(`changelog v${version}`));
|
|
2946
|
-
if (tag === undefined || tag === "") {
|
|
2947
|
-
tag = (await getGitTags())[0];
|
|
2948
|
-
if (tag === undefined) {
|
|
2949
|
-
console.log(out().yellow("No tags found, nothing to undo."));
|
|
2950
|
-
report({ command: "undo", status: "nothing", tag: null, releaseNote: false, remoteTag: false, localTag: false, commitReset: null });
|
|
2951
|
-
return 0;
|
|
2952
|
-
}
|
|
2953
|
-
console.log(out().yellow(`No tag specified, using the latest tag "${out().bold(tag)}".`));
|
|
2954
|
-
}
|
|
2955
|
-
const config = await resolveConfig({ ...options, to: tag });
|
|
2956
|
-
let originRepo;
|
|
2957
|
-
try {
|
|
2958
|
-
originRepo = await getGiteaRepo();
|
|
2959
|
-
} catch {}
|
|
2960
|
-
const remoteViaGit = Boolean(originRepo) && String(config.releaseRepo) === originRepo;
|
|
2961
|
-
const release = config.token ? await getRelease(config, tag) : null;
|
|
2962
|
-
const remoteTag = remoteViaGit ? await hasRemoteGitTag(tag) : Boolean(config.token) && await hasRemoteTag(config, tag);
|
|
2963
|
-
const localTag = await isRefGitTag(tag);
|
|
2964
|
-
let commitToReset;
|
|
2965
|
-
if (localTag && await getTagCommit(tag) === await getHeadCommit()) {
|
|
2966
|
-
commitToReset = { hash: await getHeadCommit(), subject: await getCommitSubject("HEAD") };
|
|
2967
|
-
}
|
|
2968
|
-
const deleteNote = release !== null && (args.note === true || !json && shouldAskNote({ release, note: args.note, yes: args.yes, dry: args["dry-run"] }) && await ask2(`Also delete the ${forgeName(config)} release note "${release.name || tag}"?`));
|
|
2969
|
-
const actions = [];
|
|
2970
|
-
if (deleteNote)
|
|
2971
|
-
actions.push(`${out().red("release note")} ${tag}`);
|
|
2972
|
-
if (remoteTag)
|
|
2973
|
-
actions.push(`${out().red("remote tag")} ${tag}`);
|
|
2974
|
-
if (localTag)
|
|
2975
|
-
actions.push(`${out().red("local tag")} ${tag}`);
|
|
2976
|
-
if (commitToReset)
|
|
2977
|
-
actions.push(`${out().red("commit")} reset --soft (${commitToReset.hash.slice(0, 7)} "${commitToReset.subject}")`);
|
|
2978
|
-
else if (localTag)
|
|
2979
|
-
actions.push(out().dim(`commit skipped (${tag} is not HEAD)`));
|
|
2980
|
-
const result = { command: "undo", status: "undone", tag, releaseNote: deleteNote, remoteTag, localTag, commitReset: commitToReset === undefined ? null : { hash: commitToReset.hash, subject: commitToReset.subject } };
|
|
2981
|
-
if (!actions.length) {
|
|
2982
|
-
console.log(out().yellow(`Nothing to undo for "${tag}".`));
|
|
2983
|
-
report({ ...result, status: "nothing" });
|
|
2984
|
-
return 0;
|
|
2985
|
-
}
|
|
2986
|
-
if (json && args.yes !== true && args["dry-run"] !== true)
|
|
2987
|
-
fail("--json asks no question, so removing needs --yes (or --dry-run to preview)");
|
|
2988
|
-
console.log();
|
|
2989
|
-
console.log(`About to remove on ${out().bold(String(config.releaseRepo))}:`);
|
|
2990
|
-
for (const action of actions)
|
|
2991
|
-
console.log(` - ${action}`);
|
|
2992
|
-
console.log();
|
|
2993
|
-
if (args["dry-run"]) {
|
|
2994
|
-
console.log(out().yellow("Dry run. Nothing removed."));
|
|
2995
|
-
report({ ...result, status: "dry-run" });
|
|
2996
|
-
return 0;
|
|
2997
|
-
}
|
|
2998
|
-
if (!args.yes && !await ask2("Proceed?")) {
|
|
2999
|
-
console.log(out().yellow("Aborted."));
|
|
3000
|
-
report({ ...result, status: "declined", releaseNote: false, remoteTag: false, localTag: false, commitReset: null });
|
|
3001
|
-
return 0;
|
|
3002
|
-
}
|
|
3003
|
-
if (deleteNote) {
|
|
3004
|
-
await deleteRelease(config, release.id);
|
|
3005
|
-
console.log(out().green(`Deleted release note ${tag}`));
|
|
3006
|
-
}
|
|
3007
|
-
if (remoteTag) {
|
|
3008
|
-
if (remoteViaGit)
|
|
3009
|
-
await deleteRemoteGitTag(tag);
|
|
3010
|
-
else
|
|
3011
|
-
await deleteRemoteTag(config, tag);
|
|
3012
|
-
console.log(out().green(`Deleted remote tag ${tag}`));
|
|
3013
|
-
}
|
|
3014
|
-
if (localTag) {
|
|
3015
|
-
await deleteLocalTag(tag);
|
|
3016
|
-
console.log(out().green(`Deleted local tag ${tag}`));
|
|
3017
|
-
}
|
|
3018
|
-
if (commitToReset) {
|
|
3019
|
-
await softResetLastCommit();
|
|
3020
|
-
console.log(out().green(`Reset commit ${commitToReset.hash.slice(0, 7)} (changes kept in working tree)`));
|
|
3021
|
-
}
|
|
3022
|
-
report(result);
|
|
3023
|
-
return 0;
|
|
3024
|
-
} catch (e) {
|
|
3025
|
-
return failed(e, args.debug);
|
|
3026
|
-
}
|
|
3027
|
-
}
|
|
3028
|
-
process.exitCode = await runCli({
|
|
3029
|
-
name: "changelog",
|
|
3030
|
-
about: "generate the release notes and publish them",
|
|
3031
|
-
replaces: "writing the release notes by hand and posting them through the Forgejo or GitHub UI",
|
|
3032
|
-
examples: [["changelog --dry-run", "the notes since the last tag, nothing published"], ["changelog undo v1.2.0 --dry-run", "what undoing that release would remove"]],
|
|
3033
|
-
commands: {
|
|
3034
|
-
release: { summary: "generate the release notes and publish them (the default)", run: async (argv) => reporting(aliasFlags(argv), release) },
|
|
3035
|
-
undo: { summary: "undo a release: delete the remote/local tag and reset the bump commit", run: async (argv) => reporting(aliasFlags(argv), undo) }
|
|
3036
|
-
},
|
|
3037
|
-
defaultCommand: "release"
|
|
3038
|
-
});
|
|
84
|
+
--json prints {command, status (undone, nothing, dry-run or declined), tag, releaseNote, remoteTag, localTag, commitReset: {hash, subject} or null} on stdout and the progress on stderr, each flag true when that step is (or, on a dry run, would be) taken. It asks no question: the release note is deleted with --note only, and anything to remove needs --yes or --dry-run (exit 2 otherwise).`,undoFlags,{positionals:["[tag]"],exits:UNDO_EXITS}),json=args.json===!0,tag=positionals[0],options=withToken(toOptions(args));try{if(console.log(),console.log(out().dim(`changelog v${version}`)),tag===void 0||tag===""){if(tag=(await getGitTags())[0],tag===void 0)return console.log(out().yellow("No tags found, nothing to undo.")),report({command:"undo",status:"nothing",tag:null,releaseNote:!1,remoteTag:!1,localTag:!1,commitReset:null}),0;console.log(out().yellow(`No tag specified, using the latest tag "${out().bold(tag)}".`))}let config=await resolveConfig({...options,to:tag}),originRepo;try{originRepo=await getGiteaRepo()}catch{}let remoteViaGit=Boolean(originRepo)&&String(config.releaseRepo)===originRepo,release=config.token?await getRelease(config,tag):null,remoteTag=remoteViaGit?await hasRemoteGitTag(tag):Boolean(config.token)&&await hasRemoteTag(config,tag),localTag=await isRefGitTag(tag),commitToReset;if(localTag&&await getTagCommit(tag)===await getHeadCommit())commitToReset={hash:await getHeadCommit(),subject:await getCommitSubject("HEAD")};let deleteNote=release!==null&&(args.note===!0||!json&&shouldAskNote({release,note:args.note,yes:args.yes,dry:args["dry-run"]})&&await ask2(`Also delete the ${forgeName(config)} release note "${release.name||tag}"?`)),actions=[];if(deleteNote)actions.push(`${out().red("release note")} ${tag}`);if(remoteTag)actions.push(`${out().red("remote tag")} ${tag}`);if(localTag)actions.push(`${out().red("local tag")} ${tag}`);if(commitToReset)actions.push(`${out().red("commit")} reset --soft (${commitToReset.hash.slice(0,7)} "${commitToReset.subject}")`);else if(localTag)actions.push(out().dim(`commit skipped (${tag} is not HEAD)`));let result={command:"undo",status:"undone",tag,releaseNote:deleteNote,remoteTag,localTag,commitReset:commitToReset===void 0?null:{hash:commitToReset.hash,subject:commitToReset.subject}};if(!actions.length)return console.log(out().yellow(`Nothing to undo for "${tag}".`)),report({...result,status:"nothing"}),0;if(json&&args.yes!==!0&&args["dry-run"]!==!0)fail("--json asks no question, so removing needs --yes (or --dry-run to preview)");console.log(),console.log(`About to remove on ${out().bold(String(config.releaseRepo))}:`);for(let action of actions)console.log(` - ${action}`);if(console.log(),args["dry-run"])return console.log(out().yellow("Dry run. Nothing removed.")),report({...result,status:"dry-run"}),0;if(!args.yes&&!await ask2("Proceed?"))return console.log(out().yellow("Aborted.")),report({...result,status:"declined",releaseNote:!1,remoteTag:!1,localTag:!1,commitReset:null}),0;if(deleteNote)await deleteRelease(config,release.id),console.log(out().green(`Deleted release note ${tag}`));if(remoteTag){if(remoteViaGit)await deleteRemoteGitTag(tag);else await deleteRemoteTag(config,tag);console.log(out().green(`Deleted remote tag ${tag}`))}if(localTag)await deleteLocalTag(tag),console.log(out().green(`Deleted local tag ${tag}`));if(commitToReset)await softResetLastCommit(),console.log(out().green(`Reset commit ${commitToReset.hash.slice(0,7)} (changes kept in working tree)`));return report(result),0}catch(e){return failed(e,args.debug)}}process.exitCode=await runCli({name:"changelog",about:"generate the release notes and publish them",replaces:"writing the release notes by hand and posting them through the Forgejo or GitHub UI",examples:[["changelog --dry-run","the notes since the last tag, nothing published"],["changelog undo v1.2.0 --dry-run","what undoing that release would remove"]],commands:{release:{summary:"generate the release notes and publish them (the default)",run:async(argv)=>reporting(aliasFlags(argv),release)},undo:{summary:"undo a release: delete the remote/local tag and reset the bump commit",run:async(argv)=>reporting(aliasFlags(argv),undo)}},defaultCommand:"release"});
|