@kaynooo/cli-stack 0.0.0-stage → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +31 -2
  3. package/dist/cli.js +1437 -0
  4. package/package.json +31 -4
package/dist/cli.js ADDED
@@ -0,0 +1,1437 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+
4
+ // src/cli.ts
5
+ import process10 from "process";
6
+
7
+ // ../kit/src/args.ts
8
+ import process3 from "process";
9
+ import { parseArgs } from "util";
10
+
11
+ // ../kit/src/style.ts
12
+ import process from "process";
13
+
14
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
15
+ function x(s) {
16
+ let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
17
+ if (!/^[a-f0-9]+$/.test(r))
18
+ return [0, 0, 0];
19
+ let t = r.length, n = (c) => Number.parseInt(c, 16);
20
+ if (t === 3 || t === 4) {
21
+ let c = n(r[0] + r[0]), u = n(r[1] + r[1]), h = n(r[2] + r[2]), g = t === 4 ? n(r[3] + r[3]) : undefined;
22
+ return g !== undefined ? [c, u, h, g] : [c, u, h];
23
+ }
24
+ if (t !== 6 && t !== 8)
25
+ throw Error(`Invalid hex color length: ${t}`);
26
+ let a = n(r.slice(0, 2)), b = n(r.slice(2, 4)), o = n(r.slice(4, 6)), y = t === 8 ? n(r.slice(6, 8)) : undefined;
27
+ if ([a, b, o].some(Number.isNaN) || y !== undefined && Number.isNaN(y))
28
+ throw Error(`Invalid hex color value: ${s}`);
29
+ return y !== undefined ? [a, b, o, y] : [a, b, o];
30
+ }
31
+ function A(s) {
32
+ let [r, t, n, a] = s;
33
+ if (a)
34
+ return `#${(r << 24 | t << 16 | n << 8 | Math.round((a ?? 1) * 255)).toString(16).padStart(8, "0").toUpperCase()}`;
35
+ return `#${(r << 16 | t << 8 | n).toString(16).padStart(6, "0").toUpperCase()}`;
36
+ }
37
+ function R(s, r, t) {
38
+ s = (s % 360 + 360) % 360, t /= 100;
39
+ let n = r * Math.min(t, 1 - t) / 100, a = (b) => {
40
+ let o = (b + s / 30) % 12, y = t - n * Math.max(Math.min(o - 3, 9 - o, 1), -1);
41
+ return Math.round(255 * y);
42
+ };
43
+ return [a(0), a(8), a(4)];
44
+ }
45
+ function k(s) {
46
+ let [r, t, n] = s;
47
+ r /= 255, t /= 255, n /= 255;
48
+ let a = Math.max(r, t, n), b = Math.min(r, t, n), o = 0, y = 0, c = (a + b) / 2;
49
+ if (a !== b) {
50
+ let u = a - b;
51
+ if (y = c > 0 && c < 1 ? u / (1 - Math.abs(2 * c - 1)) : 0, a === r)
52
+ o = (t - n) / u + (t < n ? 6 : 0);
53
+ else if (a === t)
54
+ o = (n - r) / u + 2;
55
+ else
56
+ o = (r - t) / u + 4;
57
+ o /= 6;
58
+ }
59
+ return [Math.round(o * 360), Math.round(y * 100), Math.round(c * 100)];
60
+ }
61
+ function H(s, r, t) {
62
+ s = (s % 360 + 360) % 360, r /= 100, t /= 100;
63
+ let n = (a) => {
64
+ let b = (a + s / 60) % 6, o = t - t * r * Math.max(Math.min(b, 4 - b, 1), 0);
65
+ return Math.round(255 * o);
66
+ };
67
+ return [n(5), n(3), n(1)];
68
+ }
69
+ function f(s) {
70
+ let [r, t, n] = s;
71
+ r /= 255, t /= 255, n /= 255;
72
+ let a = Math.max(r, t, n), b = Math.min(r, t, n), o = a - b, y = 0, c = a === 0 ? 0 : o / a, u = a;
73
+ if (o !== 0) {
74
+ if (a === r)
75
+ y = (t - n) / o + (t < n ? 6 : 0);
76
+ else if (a === t)
77
+ y = (n - r) / o + 2;
78
+ else
79
+ y = (r - t) / o + 4;
80
+ y /= 6;
81
+ }
82
+ return [Math.round(y * 360), Math.round(c * 100), Math.round(u * 100)];
83
+ }
84
+ function O(s) {
85
+ let r = s[0] / 255, t = s[1] / 255, n = s[2] / 255, a = 1 - Math.max(r, t, n);
86
+ if (a === 1)
87
+ return [0, 0, 0, 100];
88
+ let b = (1 - r - a) / (1 - a), o = (1 - t - a) / (1 - a), y = (1 - n - a) / (1 - a);
89
+ return [Math.round(b * 100), Math.round(o * 100), Math.round(y * 100), Math.round(a * 100)];
90
+ }
91
+ function v(s, r, t, n) {
92
+ return s /= 100, r /= 100, t /= 100, n /= 100, [Math.round(255 * (1 - s) * (1 - n)), Math.round(255 * (1 - r) * (1 - n)), Math.round(255 * (1 - t) * (1 - n))];
93
+ }
94
+ var m = (s) => s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
95
+ var p = (s) => s <= 0.0031308 ? 12.92 * s : 1.055 * s ** 0.4166666666666667 - 0.055;
96
+ var i = (s, r) => Math.round(s * 10 ** r) / 10 ** r;
97
+ function T(s) {
98
+ let r = m(s[0] / 255), t = m(s[1] / 255), n = m(s[2] / 255), a = Math.cbrt(0.4122214708 * r + 0.5363325363 * t + 0.0514459929 * n), b = Math.cbrt(0.2119034982 * r + 0.6806995451 * t + 0.1073969566 * n), o = Math.cbrt(0.0883024619 * r + 0.2817188376 * t + 0.6299787005 * n);
99
+ return [i(0.2104542553 * a + 0.793617785 * b - 0.0040720468 * o, 4), i(1.9779984951 * a - 2.428592205 * b + 0.4505937099 * o, 4), i(0.0259040371 * a + 0.7827717662 * b - 0.808675766 * o, 4)];
100
+ }
101
+ function M(s, r, t) {
102
+ let n = (s + 0.3963377774 * r + 0.2158037573 * t) ** 3, a = (s - 0.1055613458 * r - 0.0638541728 * t) ** 3, b = (s - 0.0894841775 * r - 1.291485548 * t) ** 3, o = p(4.0767416621 * n - 3.3077115913 * a + 0.2309699292 * b), y = p(-1.2684380046 * n + 2.6097574011 * a - 0.3413193965 * b), c = p(-0.0041960863 * n - 0.7034186147 * a + 1.707614701 * b), u = (h) => Math.min(255, Math.max(0, Math.round(h * 255)));
103
+ return [u(o), u(y), u(c)];
104
+ }
105
+ function d(s) {
106
+ let [r, t, n] = T(s), a = Math.sqrt(t * t + n * n), b = (Math.atan2(n, t) * 180 / Math.PI + 360) % 360;
107
+ return [i(r, 4), i(a, 4), i(b, 2)];
108
+ }
109
+ function C(s, r, t) {
110
+ let n = t * Math.PI / 180;
111
+ return M(s, r * Math.cos(n), r * Math.sin(n));
112
+ }
113
+ function l(s) {
114
+ let r = s / 255;
115
+ return r <= 0.03928 ? r / 12.92 : ((r + 0.055) / 1.055) ** 2.4;
116
+ }
117
+
118
+ class e {
119
+ r;
120
+ g;
121
+ b;
122
+ a;
123
+ constructor(s, r, t, n = 1) {
124
+ this.r = s, this.g = r, this.b = t, this.a = n;
125
+ }
126
+ static from(s, r) {
127
+ if (s === "hex") {
128
+ let [t, n, a, b] = x(r);
129
+ return new e(t, n, a, b);
130
+ }
131
+ if (s === "rgb") {
132
+ if (Array.isArray(r)) {
133
+ let [o, y, c, u] = r;
134
+ return new e(o, y, c, u);
135
+ }
136
+ let { r: t, g: n, b: a, a: b } = r;
137
+ return new e(t, n, a, b);
138
+ }
139
+ if (s === "hsl") {
140
+ let t, n, a, b;
141
+ if (Array.isArray(r))
142
+ [t, n, a, b] = r;
143
+ else
144
+ ({ h: t, s: n, l: a, a: b } = r);
145
+ let [o, y, c] = R(t, n, a);
146
+ return new e(o, y, c, b);
147
+ }
148
+ if (s === "hsv") {
149
+ let t, n, a, b;
150
+ if (Array.isArray(r))
151
+ [t, n, a, b] = r;
152
+ else
153
+ ({ h: t, s: n, v: a, a: b } = r);
154
+ let [o, y, c] = H(t, n, a);
155
+ return new e(o, y, c, b);
156
+ }
157
+ if (s === "cmyk") {
158
+ let t, n, a, b, o;
159
+ if (Array.isArray(r))
160
+ [t, n, a, b, o] = r;
161
+ else
162
+ ({ c: t, m: n, y: a, k: b, a: o } = r);
163
+ let [y, c, u] = v(t, n, a, b);
164
+ return new e(y, c, u, o);
165
+ }
166
+ if (s === "oklch") {
167
+ let t, n, a, b;
168
+ if (Array.isArray(r))
169
+ [t, n, a, b] = r;
170
+ else
171
+ ({ l: t, c: n, h: a, a: b } = r);
172
+ let [o, y, c] = C(t, n, a);
173
+ return new e(o, y, c, b);
174
+ }
175
+ if (s === "oklab") {
176
+ let t, n, a, b;
177
+ if (Array.isArray(r))
178
+ [t, n, a, b] = r;
179
+ else
180
+ ({ l: t, a: n, b: a, alpha: b } = r);
181
+ let [o, y, c] = M(t, n, a);
182
+ return new e(o, y, c, b);
183
+ }
184
+ throw Error("Invalid input");
185
+ }
186
+ to(s) {
187
+ switch (s) {
188
+ case "rgb":
189
+ return [this.r, this.g, this.b];
190
+ case "rgba":
191
+ return [this.r, this.g, this.b, this.a];
192
+ case "hex":
193
+ return A([this.r, this.g, this.b]);
194
+ case "hexa":
195
+ return A([this.r, this.g, this.b, this.a]);
196
+ case "hsl":
197
+ return k([this.r, this.g, this.b]);
198
+ case "hsla":
199
+ return [...k([this.r, this.g, this.b]), this.a];
200
+ case "hsv":
201
+ return f([this.r, this.g, this.b]);
202
+ case "hsva":
203
+ return [...f([this.r, this.g, this.b]), this.a];
204
+ case "cmyk":
205
+ return O([this.r, this.g, this.b]);
206
+ case "cmyka":
207
+ return [...O([this.r, this.g, this.b]), this.a];
208
+ case "oklch":
209
+ return d([this.r, this.g, this.b]);
210
+ case "oklcha":
211
+ return [...d([this.r, this.g, this.b]), this.a];
212
+ case "oklab":
213
+ return T([this.r, this.g, this.b]);
214
+ case "oklaba":
215
+ return [...T([this.r, this.g, this.b]), this.a];
216
+ default:
217
+ return [this.r, this.g, this.b];
218
+ }
219
+ }
220
+ getLuminance() {
221
+ let s = l(this.r), r = l(this.g), t = l(this.b);
222
+ return 0.2126 * s + 0.7152 * r + 0.0722 * t;
223
+ }
224
+ contrastRatio(s) {
225
+ let r = this.getLuminance(), t = s.getLuminance(), [n, a] = r >= t ? [r, t] : [t, r];
226
+ return (n + 0.05) / (a + 0.05);
227
+ }
228
+ bestContrastForeground() {
229
+ let s = new e(255, 255, 255, 1), r = new e(0, 0, 0, 1), t = this.contrastRatio(s), n = this.contrastRatio(r);
230
+ return t >= n ? s : r;
231
+ }
232
+ }
233
+
234
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
235
+ var r = 39;
236
+ var o = 49;
237
+ var f2 = "\x1B[";
238
+ var C2 = { 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, r], red: [31, r], green: [32, r], yellow: [33, r], blue: [34, r], magenta: [35, r], cyan: [36, r], white: [37, r], gray: [90, r], grey: [90, r], blackBright: [90, r], redBright: [91, r], greenBright: [92, r], yellowBright: [93, r], blueBright: [94, r], magentaBright: [95, r], cyanBright: [96, r], whiteBright: [97, r], bgBlack: [40, o], bgRed: [41, o], bgGreen: [42, o], bgYellow: [43, o], bgBlue: [44, o], bgMagenta: [45, o], bgCyan: [46, o], bgWhite: [47, o], bgBlackBright: [100, o], bgRedBright: [101, o], bgGreenBright: [102, o], bgYellowBright: [103, o], bgBlueBright: [104, o], bgMagentaBright: [105, o], bgCyanBright: [106, o], bgWhiteBright: [107, o], rgb: (i, n, a, l = "fg") => [`${l === "fg" ? 38 : 48};2;${i};${n};${a}`, l === "fg" ? r : o], hex: (i, n = "fg") => {
239
+ let [a, l, s] = e.from("hex", i).to("rgb");
240
+ return [`${n === "fg" ? 38 : 48};2;${a};${l};${s}`, n === "fg" ? r : o];
241
+ }, ansi256: (i, n = "fg") => [`${n === "fg" ? 38 : 48};5;${i}`, n === "fg" ? r : o] };
242
+ var b = new Set(["", "1", "2", "3", "true"]);
243
+ function h(i, n = globalThis.process?.env ?? {}) {
244
+ if (n.FORCE_COLOR !== undefined)
245
+ return b.has(n.FORCE_COLOR);
246
+ if (n.NO_COLOR !== undefined || n.NODE_DISABLE_COLORS !== undefined || n.TERM === "dumb")
247
+ return false;
248
+ return i?.isTTY === true;
249
+ }
250
+ function d2(i, n, a) {
251
+ if (!h(a.stream ?? globalThis.process?.stdout, a.env))
252
+ return n;
253
+ let l = "", s = "";
254
+ for (let g = 0, y = i.length;g < y; g++) {
255
+ let [c, p] = i[g];
256
+ l += `${f2}${c}m`, s = `${f2}${p}m${s}`;
257
+ }
258
+ return l + n + s;
259
+ }
260
+ function u(i, n = []) {
261
+ return new Proxy((l) => d2(n, l, i), { get(l, s) {
262
+ let g = C2[s];
263
+ if (Array.isArray(g))
264
+ return u(i, [...n, g]);
265
+ if (typeof g === "function")
266
+ return (...y) => u(i, [...n, g(...y)]);
267
+ throw Error(`Unknown style: ${String(s)}`);
268
+ } });
269
+ }
270
+ function le(i = {}) {
271
+ return u(i);
272
+ }
273
+ var t = le();
274
+
275
+ // ../kit/src/style.ts
276
+ var MARKS = {
277
+ ok: { symbol: "\u2713", word: "ok:", paint: (colors) => colors.green },
278
+ warn: { symbol: "!", word: "warning:", paint: (colors) => colors.yellow },
279
+ problem: { symbol: "\u2717", word: "error:", paint: (colors) => colors.red },
280
+ note: { symbol: "\xB7", word: "note:", paint: (colors) => colors.dim }
281
+ };
282
+ function takesControlCodes(stream, env = process.env) {
283
+ return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
284
+ }
285
+ function paint(stream, env = process.env) {
286
+ return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
287
+ }
288
+ function marked(mark, text, stream, detail, env = process.env) {
289
+ const colors = paint(stream, env);
290
+ const { symbol, word, paint: tint } = MARKS[mark];
291
+ const head = takesControlCodes(stream, env) ? tint(colors)(symbol) : word;
292
+ return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
293
+ }
294
+ var STATUSES = {
295
+ passed: { symbol: "\u2713", words: ["passed", "success", "succeeded", "ok"], paint: (colors) => colors.green },
296
+ failed: { symbol: "\u2717", words: ["failed", "failure", "error", "errored"], paint: (colors) => colors.red },
297
+ running: { symbol: "\u25CF", words: ["running", "in_progress", "started"], paint: (colors) => colors.cyan },
298
+ queued: { symbol: "\u25CB", words: ["queued", "waiting", "pending", "created", "blocked", "scheduled"], paint: (colors) => colors.yellow },
299
+ skipped: { symbol: "-", words: ["skipped", "cancelled", "canceled", "manual"], paint: (colors) => colors.dim }
300
+ };
301
+ var STATUS_OF = new Map(Object.entries(STATUSES).flatMap(([status, { words }]) => words.map((word) => [word, status])));
302
+
303
+ // ../kit/src/format.ts
304
+ function upTo(text, separator) {
305
+ const end = text.indexOf(separator);
306
+ return end === -1 ? text : text.slice(0, end);
307
+ }
308
+ var ESCAPE = String.fromCharCode(27);
309
+ function printJson(value) {
310
+ console.log(JSON.stringify(value, undefined, 2));
311
+ }
312
+
313
+ // ../kit/src/help.ts
314
+ import process2 from "process";
315
+ var OPTIONAL = /\[[^\]]+\]/g;
316
+ var USAGE_PREFIX = /^usage:\s*/i;
317
+ var FULL_STOP = /\.$/;
318
+ function usageLine(usage, colors = paint(process2.stdout)) {
319
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
320
+ }
321
+ function helpText(usage, options, colors = paint(process2.stdout), { examples = [], replaces } = {}) {
322
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
323
+ `);
324
+ }
325
+ function replacesRows(replaces, colors = paint(process2.stdout)) {
326
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
327
+ }
328
+ function wantsHelpJson(env = process2.env) {
329
+ return env.KIT_HELP === "json";
330
+ }
331
+ function description(usage, { examples = [], replaces } = {}) {
332
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
333
+ `);
334
+ const first = lines[0];
335
+ const colon = first.indexOf(": ");
336
+ const prose = lines[lines.indexOf("") + 1] ?? "";
337
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
338
+ return {
339
+ synopsis: colon === -1 ? first : first.slice(0, colon),
340
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
341
+ ...replaces === undefined ? {} : { replaces },
342
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
343
+ };
344
+ }
345
+ function exampleRows(examples, colors = paint(process2.stdout)) {
346
+ if (examples.length === 0)
347
+ return [];
348
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
349
+ }
350
+ function optionRows(options, colors = paint(process2.stdout)) {
351
+ const rows = Object.entries(options).map(([name, option]) => {
352
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
353
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
354
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
355
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
356
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
357
+ });
358
+ const width = Math.max(0, ...rows.map((row) => row.width));
359
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
360
+ }
361
+
362
+ // ../kit/src/text.ts
363
+ var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
364
+ function distance(a, b) {
365
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
366
+ for (const [i, left] of [...a].entries()) {
367
+ const current = [i + 1];
368
+ for (const [j, right] of [...b].entries())
369
+ current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
370
+ previous = current;
371
+ }
372
+ return previous[b.length] ?? 0;
373
+ }
374
+ function closest(name, names) {
375
+ const started = names.find((known) => known.startsWith(name));
376
+ if (started !== undefined)
377
+ return started;
378
+ const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
379
+ return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
380
+ }
381
+ // ../kit/src/input.ts
382
+ var WHOLE = /^\d+$/;
383
+ function wholeNumber(value, name, fallback, min = 1) {
384
+ if (value === undefined)
385
+ return fallback;
386
+ const number = Number(value);
387
+ if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
388
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
389
+ return number;
390
+ }
391
+
392
+ // ../kit/src/args.ts
393
+ var DASHES = /^-+/;
394
+ function jsonOption(holds) {
395
+ return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
396
+ }
397
+
398
+ class Exit extends Error {
399
+ code;
400
+ hint;
401
+ constructor(message, code, hint) {
402
+ super(message);
403
+ this.code = code;
404
+ this.hint = hint;
405
+ }
406
+ }
407
+ function fail(message, code = 2, hint) {
408
+ throw new Exit(message, code, hint);
409
+ }
410
+
411
+ class UsageError extends Exit {
412
+ constructor(message, hint) {
413
+ super(message, 2, hint);
414
+ }
415
+ }
416
+ function badUsage(message) {
417
+ throw new UsageError(message);
418
+ }
419
+
420
+ class HelpShown extends Exit {
421
+ constructor() {
422
+ super("help shown", 0);
423
+ }
424
+ }
425
+
426
+ class Completing {
427
+ options;
428
+ positionals;
429
+ candidates;
430
+ constructor(options, positionals = [], candidates = {}) {
431
+ this.options = options;
432
+ this.positionals = positionals;
433
+ this.candidates = candidates;
434
+ }
435
+ }
436
+ var completion = { active: false };
437
+ var OUTPUT_OPTIONS = {
438
+ color: { type: "string", description: "auto (on a terminal alone), always or never" },
439
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
440
+ };
441
+ function applyOutput(color, plain, env = process3.env) {
442
+ const when = plain === true ? "never" : color ?? "auto";
443
+ if (when === "auto")
444
+ return;
445
+ if (when !== "always" && when !== "never")
446
+ badUsage(`--color takes auto, always or never, not ${when}`);
447
+ if (when === "always") {
448
+ env.FORCE_COLOR = "1";
449
+ delete env.NO_COLOR;
450
+ } else {
451
+ env.NO_COLOR = "1";
452
+ delete env.FORCE_COLOR;
453
+ }
454
+ }
455
+ function parse(args, usage, options, settings = {}) {
456
+ const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
457
+ const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
458
+ const listing = listed(all, settings.allowNegative === true);
459
+ if (completion.active)
460
+ throw new Completing(listing, settings.positionals, settings.candidates);
461
+ const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
462
+ let parsed;
463
+ try {
464
+ parsed = parseArgs({ args: joinDashValues(withBare(own, all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
465
+ } catch (error) {
466
+ const message = parseError(error);
467
+ throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
468
+ }
469
+ const values = parsed.values;
470
+ applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
471
+ if (values.help === true) {
472
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
473
+ throw new HelpShown;
474
+ }
475
+ checkChoices(parsed.values, all);
476
+ checkConflicts(parsed.values, all);
477
+ if (settings.positionals !== undefined)
478
+ checkPositionals(parsed.positionals, settings.positionals);
479
+ return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
480
+ }
481
+ function splitRest(args, passes) {
482
+ const separator = passes ? args.indexOf("--") : -1;
483
+ return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
484
+ }
485
+ function splitTrailing(args, options, count) {
486
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
487
+ let seen = 0;
488
+ if (count === 0)
489
+ return { own: args, rest: undefined };
490
+ for (let at = 0;at < args.length; at++) {
491
+ const word = args[at];
492
+ if (word === "--")
493
+ break;
494
+ if (word.startsWith("-")) {
495
+ if (takesValue(word))
496
+ at++;
497
+ continue;
498
+ }
499
+ seen++;
500
+ if (seen === count)
501
+ return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
502
+ }
503
+ return { own: args, rest: undefined };
504
+ }
505
+ function listed(options, allowNegative) {
506
+ if (!allowNegative)
507
+ return options;
508
+ return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
509
+ if (option.type !== "boolean" || option.negative === undefined)
510
+ return [[name, option]];
511
+ return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
512
+ }));
513
+ }
514
+ function withBare(args, options) {
515
+ const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
516
+ if (bare.size === 0)
517
+ return args;
518
+ const separator = args.indexOf("--");
519
+ const own = separator === -1 ? args : args.slice(0, separator);
520
+ return [...own.flatMap((arg, index) => {
521
+ const optional = bare.get(arg);
522
+ const next = own[index + 1];
523
+ const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
524
+ return optional === undefined || value ? [arg] : [arg, optional.bare];
525
+ }), ...separator === -1 ? [] : args.slice(separator)];
526
+ }
527
+ function checkConflicts(values, options) {
528
+ const given = (name) => values[name] !== undefined && values[name] !== false;
529
+ for (const [name, { conflicts = [] }] of Object.entries(options)) {
530
+ const other = given(name) ? conflicts.find(given) : undefined;
531
+ if (other !== undefined)
532
+ badUsage(`--${name} cannot be used with --${other}`);
533
+ }
534
+ }
535
+ function checkChoices(values, options) {
536
+ for (const [name, option] of Object.entries(options)) {
537
+ if (option.choices === undefined)
538
+ continue;
539
+ const given = values[name];
540
+ for (const value of Array.isArray(given) ? given : [given]) {
541
+ if (typeof value === "string")
542
+ oneOf(value, name, option.choices);
543
+ }
544
+ }
545
+ }
546
+ function oneOf(value, name, choices) {
547
+ if (!choices.includes(value))
548
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
549
+ return value;
550
+ }
551
+ function checkPositionals(given, names) {
552
+ const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
553
+ const required = names.filter((name) => !name.startsWith("[")).length;
554
+ if (given.length < required)
555
+ badUsage(`missing ${names[given.length]}`);
556
+ if (!variadic && given.length > names.length)
557
+ badUsage(`unexpected argument ${given[names.length]}`);
558
+ }
559
+ function joinDashValues(args, options) {
560
+ const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
561
+ const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
562
+ const joined = [];
563
+ for (let i = 0;i < args.length; i++) {
564
+ const arg = args[i] ?? "";
565
+ if (arg === "--")
566
+ return [...joined, ...args.slice(i)];
567
+ const name = longOf.get(arg);
568
+ const next = args[i + 1];
569
+ if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
570
+ joined.push(`--${name}=${next}`);
571
+ i++;
572
+ } else {
573
+ joined.push(arg);
574
+ }
575
+ }
576
+ return joined;
577
+ }
578
+ function parseError(error) {
579
+ const message = upTo(error instanceof Error ? error.message : String(error), ". ");
580
+ return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
581
+ }
582
+ var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
583
+ function nearestOption(message, options, allowNegative) {
584
+ const typed = UNKNOWN_OPTION.exec(message)?.[1];
585
+ if (typed === undefined)
586
+ return;
587
+ const word = typed.replace(DASHES, "");
588
+ if (word.length < 2 && !typed.startsWith("--"))
589
+ return;
590
+ const known = Object.entries(options).flatMap(([name, option]) => [
591
+ ...option.short === undefined ? [] : [`-${option.short}`],
592
+ `--${name}`,
593
+ ...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
594
+ ]);
595
+ const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
596
+ return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
597
+ }
598
+ // ../kit/src/progress.ts
599
+ var ESC = String.fromCharCode(27);
600
+ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
601
+ var RESET_STYLE = `${ESC}[0m`;
602
+ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
603
+ // ../kit/src/cli.ts
604
+ import process5 from "process";
605
+
606
+ // ../kit/src/usage.ts
607
+ import { appendFileSync, mkdirSync } from "fs";
608
+ import { homedir } from "os";
609
+ import { dirname, isAbsolute, join } from "path";
610
+ import process4 from "process";
611
+
612
+ // ../kit/src/logs.ts
613
+ var DAY_MS = 24 * 60 * 60 * 1000;
614
+ var CLI_FOLDER = "kaynooo-cli";
615
+
616
+ // ../kit/src/usage.ts
617
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
618
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
619
+ var LONGEST_NAME = 40;
620
+ var usageError;
621
+ function noteUsageError(message) {
622
+ usageError = message;
623
+ }
624
+ function stateHome(env = process4.env) {
625
+ const dir = env.XDG_STATE_HOME;
626
+ return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
627
+ }
628
+ function usagePath(env = process4.env) {
629
+ return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
630
+ }
631
+ function usageRecorded(env = process4.env) {
632
+ const off = env.KAYNOOO_CLI_NO_USAGE;
633
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
634
+ }
635
+ function flagNames(argv) {
636
+ const end = argv.indexOf("--");
637
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
638
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
639
+ }
640
+ function usageEntry(bin, command, argv, code, now = new Date) {
641
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
642
+ usageError = undefined;
643
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
644
+ }
645
+ function recordUsage(entry, env = process4.env) {
646
+ if (!usageRecorded(env))
647
+ return;
648
+ try {
649
+ const path = usagePath(env);
650
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
651
+ appendFileSync(path, `${JSON.stringify(entry)}
652
+ `, { mode: 384 });
653
+ } catch {}
654
+ }
655
+
656
+ // ../kit/src/cli.ts
657
+ var LEVEL_OPTIONS = {
658
+ ...OUTPUT_OPTIONS,
659
+ help: { type: "boolean", short: "h", description: "show this help" }
660
+ };
661
+ var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
662
+ async function commandRows(all, colors) {
663
+ const commands = shown(all);
664
+ const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
665
+ const groups = new Map([["Commands:", []]]);
666
+ const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
667
+ for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
668
+ const heading = group === undefined ? "Commands:" : `${group}:`;
669
+ const rows = groups.get(heading) ?? [];
670
+ rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`);
671
+ groups.set(heading, rows);
672
+ }
673
+ return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
674
+ }
675
+ function shown(commands) {
676
+ return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
677
+ }
678
+ function takeOutputFlags(argv) {
679
+ let index = 0;
680
+ for (;index < argv.length; index++) {
681
+ const word = argv[index];
682
+ if (word === "--plain")
683
+ applyOutput(undefined, true);
684
+ else if (word.startsWith("--color="))
685
+ applyOutput(word.slice("--color=".length), undefined);
686
+ else if (word === "--color" && argv[index + 1] !== undefined)
687
+ applyOutput(argv[++index], undefined);
688
+ else
689
+ break;
690
+ }
691
+ return argv.slice(index);
692
+ }
693
+ async function resolveSummary(summary) {
694
+ return typeof summary === "string" ? summary : summary();
695
+ }
696
+ function scopeOf(commands, extra, aliases) {
697
+ return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
698
+ }
699
+ async function expand(scope, words) {
700
+ if (scope.lazy.length === 0)
701
+ return scope;
702
+ const commands = { ...scope.commands };
703
+ for (const added of await Promise.all(scope.lazy.map(async (lazy) => lazy(words)))) {
704
+ for (const [name, command] of Object.entries(added))
705
+ commands[name] ??= command;
706
+ }
707
+ return { ...scope, commands, lazy: [] };
708
+ }
709
+ async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
710
+ const colors = paint(stream);
711
+ const prefix = path.join(" ");
712
+ const summary = await resolveSummary(lazySummary);
713
+ if (wantsHelpJson())
714
+ return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`, { examples, replaces }));
715
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
716
+ const options = fallback !== undefined && "run" in fallback ? await optionsOf(fallback.run) : undefined;
717
+ const own = Object.entries(options ?? {}).filter(([name]) => !(name in TOP_OPTIONS));
718
+ return [
719
+ header(colors, summary),
720
+ "",
721
+ usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
722
+ ...replacesRows(replaces, colors),
723
+ "",
724
+ ...await commandRows(commands, colors),
725
+ ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
726
+ "",
727
+ colors.bold("Options:"),
728
+ ...optionRows(path.length === 1 ? TOP_OPTIONS : LEVEL_OPTIONS, colors),
729
+ ...exampleRows(examples ?? [], colors),
730
+ "",
731
+ `${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`
732
+ ].join(`
733
+ `);
734
+ }
735
+ function printError(prefix, message, hint, cause) {
736
+ const colors = paint(process5.stderr);
737
+ const styled = takesControlCodes(process5.stderr);
738
+ const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
739
+ const under = (label, text, tint) => text === undefined ? "" : `
740
+ ${styled ? tint(label) : `${label}:`} ${text}`;
741
+ console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
742
+ }
743
+ function printJsonError(message, hint, cause) {
744
+ console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
745
+ }
746
+ function wantsJson(argv) {
747
+ const end = argv.indexOf("--");
748
+ return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
749
+ }
750
+ function reportThrown(prefix, error, redact = (text) => text, json = false) {
751
+ if (error instanceof HelpShown)
752
+ return 0;
753
+ const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
754
+ const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
755
+ const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
756
+ if (error instanceof UsageError)
757
+ noteUsageError(error.message);
758
+ const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
759
+ report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
760
+ return error instanceof Exit ? error.code : 1;
761
+ }
762
+ async function dispatch(level, typed, { version, redact }) {
763
+ const prefix = level.path.join(" ");
764
+ let argv;
765
+ try {
766
+ argv = takeOutputFlags(typed);
767
+ } catch (error) {
768
+ return reportThrown(prefix, error);
769
+ }
770
+ const [name, ...args] = argv;
771
+ const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
772
+ if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
773
+ try {
774
+ return await fallback.run([]);
775
+ } catch (error) {
776
+ return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
777
+ }
778
+ }
779
+ if (name === undefined && level.path.length > 1) {
780
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process5.stderr));
781
+ return 2;
782
+ }
783
+ if (name === undefined || name === "help" || name === "--help" || name === "-h") {
784
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process5.stdout));
785
+ return 0;
786
+ }
787
+ if (level.path.length === 1 && (name === "--version" || name === "-v")) {
788
+ console.log(version);
789
+ return 0;
790
+ }
791
+ let command = level.commands[level.aliases?.[name] ?? name];
792
+ let rest = args;
793
+ let ran = name;
794
+ if (command === undefined && level.lazy.length > 0) {
795
+ level = await expand(level, [...level.path.slice(1), ...argv]);
796
+ command = level.commands[level.aliases?.[name] ?? name];
797
+ }
798
+ if (command === undefined && level.defaultCommand !== undefined) {
799
+ command = level.commands[level.defaultCommand];
800
+ rest = argv;
801
+ ran = level.defaultCommand;
802
+ }
803
+ if (command === undefined) {
804
+ const meant = closest(name, Object.keys(shown(level.commands)));
805
+ printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
806
+ return 2;
807
+ }
808
+ if ("commands" in command) {
809
+ const { summary } = command;
810
+ 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 });
811
+ }
812
+ try {
813
+ return await command.run(rest);
814
+ } catch (error) {
815
+ return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
816
+ }
817
+ }
818
+ var COMPLETE = "__complete";
819
+ var FILES = "__files__";
820
+ async function completingOf(run) {
821
+ completion.active = true;
822
+ try {
823
+ await run([]);
824
+ } catch (error) {
825
+ if (error instanceof Completing)
826
+ return error;
827
+ } finally {
828
+ completion.active = false;
829
+ }
830
+ return new Completing({});
831
+ }
832
+ async function optionsOf(run) {
833
+ return (await completingOf(run)).options;
834
+ }
835
+ function candidateLine(candidate) {
836
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
837
+ }
838
+ function positionalBeingTyped(before, { options, positionals }) {
839
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
840
+ let index = 0;
841
+ let at = 0;
842
+ while (at < before.length) {
843
+ const word = before[at];
844
+ if (word === "--") {
845
+ index += before.length - at - 1;
846
+ break;
847
+ }
848
+ if (!word.startsWith("-"))
849
+ index++;
850
+ else if (takesValue(word))
851
+ at++;
852
+ at++;
853
+ }
854
+ const last = positionals.at(-1);
855
+ if (index < positionals.length)
856
+ return positionals[index];
857
+ return last?.replace("]", "").endsWith("...") === true ? last : undefined;
858
+ }
859
+ async function leafCandidates(run, words) {
860
+ const completing = await completingOf(run);
861
+ if ((words.at(-1) ?? "").startsWith("-"))
862
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
863
+ const flag = words.at(-2);
864
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
865
+ if (option?.type === "string") {
866
+ const values = option.choices === undefined ? await option.candidates?.() : option.choices;
867
+ return values === undefined ? [FILES] : values.map(candidateLine);
868
+ }
869
+ const name = positionalBeingTyped(words.slice(0, -1), completing);
870
+ const values = name === undefined ? undefined : await completing.candidates[name]?.();
871
+ return values === undefined ? [FILES] : values.map(candidateLine);
872
+ }
873
+ async function candidates(scope, defaultCommand, words, before = []) {
874
+ const [word = "", ...rest] = words;
875
+ const listing = rest.length === 0 && !word.startsWith("-");
876
+ let { commands, aliases } = scope;
877
+ let command = commands[aliases?.[word] ?? word];
878
+ if (listing || command === undefined) {
879
+ ({ commands, aliases } = await expand(scope, [...before, ...words]));
880
+ command = commands[aliases?.[word] ?? word];
881
+ }
882
+ if (listing) {
883
+ const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
884
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
885
+ const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
886
+ const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
887
+ return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
888
+ }
889
+ if (command === undefined) {
890
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
891
+ return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
892
+ }
893
+ return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
894
+ }
895
+ async function printCandidates(found) {
896
+ for (const line of await found)
897
+ console.log(line);
898
+ return 0;
899
+ }
900
+ async function runCli(cli, argv = process5.argv.slice(2)) {
901
+ if (argv[0] === COMPLETE)
902
+ return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
903
+ const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(cli.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: cli.version, redact: cli.redact });
904
+ if (cli.usage !== false) {
905
+ try {
906
+ recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
907
+ } catch {}
908
+ }
909
+ return code;
910
+ }
911
+ function commandPath(scope, argv) {
912
+ const path = [];
913
+ let level = scope;
914
+ for (const word of argv.filter((each) => !each.startsWith("-"))) {
915
+ const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
916
+ const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
917
+ if (command === undefined)
918
+ break;
919
+ path.push(word);
920
+ if (!("commands" in command))
921
+ break;
922
+ level = scopeOf(command.commands, command.extraCommands, command.aliases);
923
+ }
924
+ return path.length === 0 ? undefined : path.join(" ");
925
+ }
926
+ // ../kit/src/limit.ts
927
+ function limitOptions(fallback) {
928
+ return {
929
+ limit: { type: "string", short: "n", description: `show at most this many rows, the rest counted (${fallback})` },
930
+ full: { type: "boolean", description: "show every row" }
931
+ };
932
+ }
933
+ function limitOf(values, fallback) {
934
+ if (values.full === true && values.limit !== undefined)
935
+ badUsage("--limit and --full exclude each other");
936
+ if (values.full === true || values.json === true && values.limit === undefined)
937
+ return Number.POSITIVE_INFINITY;
938
+ return wholeNumber(values.limit, "limit", fallback);
939
+ }
940
+ function moreFooter(more) {
941
+ return `${more} more, rerun with --full`;
942
+ }
943
+ function capped(rows, limit) {
944
+ const more = rows.length - limit;
945
+ return more > 0 ? { shown: rows.slice(0, limit), footer: moreFooter(more) } : { shown: [...rows], footer: undefined };
946
+ }
947
+ // ../kit/src/secrets.ts
948
+ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
949
+ // ../kit/src/sessions.ts
950
+ var {Glob } = globalThis.Bun;
951
+ var SESSION_FILES = new Glob("*.json");
952
+ var ACCOUNT_DIRS = new Glob("*/sessions");
953
+ // package.json
954
+ var version = "0.4.1";
955
+
956
+ // src/commands/audit.ts
957
+ import { homedir as homedir2 } from "os";
958
+ import { resolve as resolve2 } from "path";
959
+ import process9 from "process";
960
+
961
+ // src/audit/compose.ts
962
+ import { join as join2 } from "path";
963
+ import process7 from "process";
964
+ var dockerCompose = async (root, files) => {
965
+ const args = ["docker", "compose", "--project-directory", root, ...files.flatMap((file) => ["-f", join2(root, file)]), "config", "--no-interpolate", "--format", "json"];
966
+ const run = Bun.spawn(args, { stdout: "pipe", stderr: "pipe", env: { ...process7.env, COMPOSE_FILE: "" } });
967
+ const [out, err, code] = await Promise.all([run.stdout.text(), run.stderr.text(), run.exited]);
968
+ const last = err.trim().split(`
969
+ `).at(-1) ?? "";
970
+ if (code !== 0)
971
+ throw new Error(last !== "" ? last : `exited with ${code}`);
972
+ return JSON.parse(out);
973
+ };
974
+
975
+ // src/audit/render.ts
976
+ import { basename } from "path";
977
+ import process8 from "process";
978
+ var line = (finding) => ` ${marked(finding.level === "error" ? "problem" : "warn", `[${finding.check}] ${finding.message}`, process8.stdout)}`;
979
+ function errorsOf(result) {
980
+ return result.findings.filter((finding) => finding.level === "error");
981
+ }
982
+ function section(heading, findings, limit) {
983
+ const { shown, footer } = capped(findings, limit);
984
+ return findings.length === 0 ? [] : [heading, ...shown.map(line), ...footer === undefined ? [] : [` ${footer}`], ""];
985
+ }
986
+ function render(result, limit = Number.POSITIVE_INFINITY) {
987
+ const errors = errorsOf(result);
988
+ const warnings = result.findings.filter((finding) => finding.level === "warn");
989
+ if (result.findings.length === 0)
990
+ return marked("ok", `${basename(result.root)}: compose ${result.composeFiles.join(", ")} and release.config.ts agree.`, process8.stdout);
991
+ return [
992
+ ...section("Errors", errors, limit),
993
+ ...section("Warnings", warnings, limit),
994
+ `${errors.length} error(s), ${warnings.length} warning(s)`
995
+ ].join(`
996
+ `);
997
+ }
998
+
999
+ // src/audit/run.ts
1000
+ import { existsSync as existsSync3 } from "fs";
1001
+ import { join as join5 } from "path";
1002
+
1003
+ // src/audit/checks.ts
1004
+ import { existsSync, readFileSync } from "fs";
1005
+ import { isAbsolute as isAbsolute2, join as join3, relative, resolve } from "path";
1006
+ var ENV_REF = /(?<!\$)\$(?:\{([A-Z_]\w*)(\s*:?[-?+][^}]*)?\}|([A-Z_]\w*))/gi;
1007
+ var REQUIRED_OPERATOR = /^\s*:?\?/;
1008
+ var COMMENT_START = /(?:^|\s)#.*$/;
1009
+ var QUOTES = /['"]/g;
1010
+ var YAML_FILE = /\.ya?ml$/;
1011
+ var LEADING_DOT_SLASH = /^\.\//;
1012
+ var SERVICES_KEY = /^services:/m;
1013
+ var EXEC_SERVICE = /\{compose\}(?:\s+--\S+)*\s+(?:exec|run)\s+(?:-\S+\s+)*([\w-]+)/;
1014
+ var services = (model) => Object.entries(model?.services ?? {});
1015
+ function before(text, separator) {
1016
+ const at = text.indexOf(separator);
1017
+ return at < 0 ? text : text.slice(0, at);
1018
+ }
1019
+ var stripDotSlash = (file) => file.replace(LEADING_DOT_SLASH, "");
1020
+ function composeLayout(root, config) {
1021
+ const composeFiles = (config.deploySyncFiles ?? []).map(stripDotSlash).filter((file) => YAML_FILE.test(file) && existsSync(join3(root, file)));
1022
+ const [base] = composeFiles.toSorted((a, b) => a.length - b.length);
1023
+ return { composeFiles, base, overlays: composeFiles.filter((file) => file !== base) };
1024
+ }
1025
+ function syncFindings(root, config) {
1026
+ return (config.deploySyncFiles ?? []).filter((file) => !existsSync(join3(root, stripDotSlash(file)))).map((file) => ({ level: "error", check: "sync", message: `deploySyncFiles entry does not exist: ${file}` }));
1027
+ }
1028
+ function buildFindings(root, releases, env, home) {
1029
+ const findings = [];
1030
+ const missing = (release, key) => {
1031
+ const path = release[key];
1032
+ if (path !== undefined && path !== "" && !existsSync(join3(root, path)))
1033
+ findings.push({ level: "error", check: "build", message: `${release.slug}: ${key} does not exist: ${path}` });
1034
+ };
1035
+ for (const release of releases) {
1036
+ missing(release, "sourceDir");
1037
+ missing(release, "buildContext");
1038
+ missing(release, "dockerfile");
1039
+ for (const secret of release.buildSecrets ?? []) {
1040
+ if (secret.src !== undefined && secret.src !== "") {
1041
+ const path = secret.src.startsWith("~") ? join3(home, secret.src.slice(1)) : resolve(root, secret.src);
1042
+ if (!existsSync(path))
1043
+ findings.push({ level: "error", check: "build", message: `${release.slug}: buildSecret "${secret.id}" src does not exist: ${secret.src}` });
1044
+ }
1045
+ if (secret.env !== undefined && secret.env !== "" && (env[secret.env] ?? "") === "")
1046
+ findings.push({ level: "warn", check: "build", message: `${release.slug}: buildSecret "${secret.id}" reads $${secret.env}, unset in this shell` });
1047
+ }
1048
+ }
1049
+ return findings;
1050
+ }
1051
+ function withoutComment(line) {
1052
+ const comment = COMMENT_START.exec(line);
1053
+ if (comment === null || (line.slice(0, comment.index).match(QUOTES)?.length ?? 0) % 2 === 1)
1054
+ return line;
1055
+ return line.slice(0, comment.index);
1056
+ }
1057
+ function envRefs(root, composeFiles) {
1058
+ return composeFiles.flatMap((file) => {
1059
+ const text = readFileSync(join3(root, file), "utf8").split(`
1060
+ `).map(withoutComment).join(`
1061
+ `);
1062
+ return [...text.matchAll(ENV_REF)].map((match) => ({ name: match[1] ?? match[3], defaulted: match[2] !== undefined && !REQUIRED_OPERATOR.test(match[2]), file }));
1063
+ });
1064
+ }
1065
+ function envFindings(refs, required) {
1066
+ const findings = [];
1067
+ const level = required.length > 0 ? "error" : "warn";
1068
+ for (const name of new Set(refs.filter((ref) => !ref.defaulted).map((ref) => ref.name))) {
1069
+ if (!name.endsWith("_VERSION") && !required.includes(name))
1070
+ findings.push({ level, check: "env", message: `\${${name}} has no default in ${refs.find((ref) => ref.name === name)?.file} and is not in requiredServerEnv` });
1071
+ }
1072
+ for (const name of required) {
1073
+ if (!refs.some((ref) => ref.name === name))
1074
+ findings.push({ level: "warn", check: "env", message: `requiredServerEnv lists ${name}, which no compose file references` });
1075
+ }
1076
+ return findings;
1077
+ }
1078
+ function versionFindings(refs, releases) {
1079
+ const findings = [];
1080
+ const inCompose = new Set(refs.filter((ref) => ref.name.endsWith("_VERSION")).map((ref) => ref.name));
1081
+ const inConfig = new Set(releases.map((release) => release.versionEnv).filter((name) => typeof name === "string" && name !== ""));
1082
+ for (const name of inConfig) {
1083
+ if (!inCompose.has(name))
1084
+ findings.push({ level: "error", check: "version", message: `versionEnv ${name} is never interpolated by a compose file` });
1085
+ }
1086
+ for (const name of inCompose) {
1087
+ if (!inConfig.has(name))
1088
+ findings.push({ level: "error", check: "version", message: `compose interpolates \${${name}}, which no release declares as versionEnv` });
1089
+ }
1090
+ return findings;
1091
+ }
1092
+ function imageFindings(config, releases, model) {
1093
+ const registry = config.registry ?? "";
1094
+ if (registry === "")
1095
+ return [];
1096
+ const declared = new Set(releases.filter((release) => release.image !== undefined && release.image !== "").map((release) => `${registry}/${release.image}`));
1097
+ const findings = [];
1098
+ for (const [name, service] of services(model)) {
1099
+ const repo = service.image === undefined ? undefined : before(service.image, ":");
1100
+ if (repo !== undefined && repo.startsWith(registry) && !declared.has(repo))
1101
+ findings.push({ level: "warn", check: "image", message: `service "${name}" pulls ${repo}, which no release in this config builds` });
1102
+ }
1103
+ return findings;
1104
+ }
1105
+ function restartFindings(config, releases, model, base) {
1106
+ const known = new Set(Object.keys(model?.services ?? {}));
1107
+ const findings = [];
1108
+ for (const release of releases) {
1109
+ for (const service of release.restartServices ?? []) {
1110
+ if (!known.has(service))
1111
+ findings.push({ level: "error", check: "restart", message: `${release.slug}: restartServices names "${service}", absent from ${base}` });
1112
+ }
1113
+ }
1114
+ for (const server of config.servers ?? []) {
1115
+ for (const [slug, override] of Object.entries(server.releaseOverrides ?? {})) {
1116
+ for (const service of override.restartServices ?? []) {
1117
+ if (!known.has(service))
1118
+ findings.push({ level: "error", check: "restart", message: `server ${server.name}: releaseOverrides.${slug} names service "${service}", absent from ${base}` });
1119
+ }
1120
+ }
1121
+ }
1122
+ return findings;
1123
+ }
1124
+ function postDeployFindings(releases, model, base) {
1125
+ const known = new Set(Object.keys(model?.services ?? {}));
1126
+ const findings = [];
1127
+ for (const release of releases) {
1128
+ for (const command of release.postDeployCommands ?? []) {
1129
+ const target = EXEC_SERVICE.exec(command)?.[1];
1130
+ if (target !== undefined && !known.has(target))
1131
+ findings.push({ level: "warn", check: "post-deploy", message: `${release.slug}: post-deploy command targets service "${target}", absent from ${base}` });
1132
+ }
1133
+ }
1134
+ return findings;
1135
+ }
1136
+ var gatedServices = (releases) => new Set(releases.flatMap((release) => release.restartServices ?? []));
1137
+ function healthFindings(gated, model) {
1138
+ return [...gated].filter((name) => {
1139
+ const service = model?.services?.[name];
1140
+ return service !== undefined && (service.healthcheck === undefined || service.healthcheck === null);
1141
+ }).map((name) => ({ level: "warn", check: "health", message: `service "${name}" is restarted by a release but declares no healthcheck, so --wait will not gate it` }));
1142
+ }
1143
+ function routingFindings(config, gated, model, base, overlays) {
1144
+ if (overlays.length === 0)
1145
+ return [];
1146
+ const findings = [];
1147
+ for (const name of gated) {
1148
+ const service = model?.services?.[name];
1149
+ if (service === undefined)
1150
+ continue;
1151
+ if (service.ports !== undefined && service.ports.length > 0)
1152
+ findings.push({ level: "error", check: "routing", message: `service "${name}" publishes ports in ${base}; publishing belongs in an overlay` });
1153
+ if (Object.keys(service.labels ?? {}).some((key) => key.startsWith("traefik.")))
1154
+ findings.push({ level: "error", check: "routing", message: `service "${name}" carries traefik labels in ${base}; routing belongs in an overlay` });
1155
+ }
1156
+ const composeArgs = config.composeArgs ?? [];
1157
+ if (composeArgs.length > 0)
1158
+ findings.push({ level: "error", check: "routing", message: `composeArgs is set (${composeArgs.join(" ")}) while ${overlays.length} overlay(s) exist: -f overrides each server's COMPOSE_FILE and drops them` });
1159
+ for (const server of config.servers ?? []) {
1160
+ if (server.composeArgs !== undefined && server.composeArgs.length > 0)
1161
+ findings.push({ level: "warn", check: "routing", message: `server ${server.name} sets composeArgs; prefer its own COMPOSE_FILE` });
1162
+ }
1163
+ return findings;
1164
+ }
1165
+ function relativeSource(root, source) {
1166
+ if (source === undefined)
1167
+ return;
1168
+ if (source.startsWith("."))
1169
+ return source;
1170
+ const inRoot = relative(resolve(root), source);
1171
+ return isAbsolute2(source) && inRoot !== "" && !inRoot.startsWith("..") ? `./${inRoot}` : undefined;
1172
+ }
1173
+ function layoutFindings(root, base, model) {
1174
+ if (base === undefined)
1175
+ return [];
1176
+ const header = readFileSync(join3(root, base), "utf8").split(SERVICES_KEY)[0] ?? "";
1177
+ const findings = [];
1178
+ for (const [name, service] of services(model)) {
1179
+ for (const volume of service.volumes ?? []) {
1180
+ const source = relativeSource(root, typeof volume === "string" ? before(volume, ":") : volume.source);
1181
+ if (source !== undefined && !header.includes(stripDotSlash(source)))
1182
+ findings.push({ level: "warn", check: "layout", message: `service "${name}" bind-mounts ${source}, absent from the header's expected server layout` });
1183
+ }
1184
+ }
1185
+ return findings;
1186
+ }
1187
+ function gitignoreFindings(root) {
1188
+ const path = join3(root, ".gitignore");
1189
+ const text = existsSync(path) ? readFileSync(path, "utf8") : "";
1190
+ return [".release-logs", ".release-worktrees"].filter((entry) => !text.includes(entry)).map((entry) => ({ level: "warn", check: "gitignore", message: `${entry}/ is not in .gitignore` }));
1191
+ }
1192
+
1193
+ // src/audit/nuxt.ts
1194
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
1195
+ import { basename as basename2, join as join4 } from "path";
1196
+ var CAMEL_BOUNDARY = /([a-z0-9])([A-Z])/g;
1197
+ var KEY = /([A-Z_]\w*)\s*(?:\?\s*)?:/gi;
1198
+ var OPENS_BRACE = /^\s*\{/;
1199
+ var envVarFor = (key) => key.replace(CAMEL_BOUNDARY, "$1_$2").toUpperCase();
1200
+ function braceBody(text, from) {
1201
+ const open = text.indexOf("{", from);
1202
+ if (open < 0)
1203
+ return;
1204
+ let depth = 0;
1205
+ for (let i = open;i < text.length; i++) {
1206
+ if (text[i] === "{")
1207
+ depth++;
1208
+ else if (text[i] === "}" && --depth === 0)
1209
+ return { body: text.slice(open + 1, i), end: i };
1210
+ }
1211
+ return;
1212
+ }
1213
+ function leafPaths(body, prefix = []) {
1214
+ const paths = [];
1215
+ const key = new RegExp(KEY);
1216
+ for (let match = key.exec(body);match !== null; match = key.exec(body)) {
1217
+ const name = match[1];
1218
+ const after = match.index + match[0].length;
1219
+ if (OPENS_BRACE.test(body.slice(after))) {
1220
+ const inner = braceBody(body, after);
1221
+ if (inner === undefined)
1222
+ continue;
1223
+ paths.push(...leafPaths(inner.body, [...prefix, name]));
1224
+ key.lastIndex = inner.end + 1;
1225
+ } else {
1226
+ paths.push([...prefix, name]);
1227
+ }
1228
+ }
1229
+ return paths;
1230
+ }
1231
+ function schemaEnvNames(schema, iface, prefix) {
1232
+ const at = schema.indexOf(`interface ${iface}`);
1233
+ const body = at < 0 ? undefined : braceBody(schema, at);
1234
+ return body === undefined ? [] : leafPaths(body.body).map((path) => prefix + path.map(envVarFor).join("_"));
1235
+ }
1236
+ function nuxtFindings(root, releases, model) {
1237
+ const findings = [];
1238
+ const dirs = [...new Set(releases.map((release) => release.buildContext).filter((context) => context !== undefined && context !== ""))].map((dir) => join4(root, dir)).filter((dir) => existsSync2(join4(dir, "nuxt.config.ts")));
1239
+ for (const dir of dirs) {
1240
+ const schemaPath = [join4(dir, ".nuxt/types/schema.d.ts"), join4(dir, ".nuxt/types/runtime-config.d.ts")].find((path) => existsSync2(path));
1241
+ let allowed;
1242
+ let level = "error";
1243
+ let source;
1244
+ if (schemaPath !== undefined) {
1245
+ const schema = readFileSync2(schemaPath, "utf8");
1246
+ allowed = new Set([
1247
+ ...schemaEnvNames(schema, "SharedRuntimeConfig", "NUXT_"),
1248
+ ...schemaEnvNames(schema, "SharedPublicRuntimeConfig", "NUXT_PUBLIC_")
1249
+ ]);
1250
+ source = `${basename2(dir)}/${schemaPath.slice(dir.length + 1)}`;
1251
+ } else {
1252
+ const config = readFileSync2(join4(dir, "nuxt.config.ts"), "utf8");
1253
+ const at = config.indexOf("runtimeConfig:");
1254
+ const block = at < 0 ? undefined : braceBody(config, at);
1255
+ if (block === undefined)
1256
+ continue;
1257
+ allowed = new Set(leafPaths(block.body).map((path) => path[0] === "public" ? `NUXT_PUBLIC_${path.slice(1).map(envVarFor).join("_")}` : `NUXT_${path.map(envVarFor).join("_")}`));
1258
+ level = "warn";
1259
+ source = `${basename2(dir)}/nuxt.config.ts (run \`nuxt prepare\` in ${basename2(dir)} for the resolved config, modules included)`;
1260
+ }
1261
+ for (const [name, service] of Object.entries(model?.services ?? {})) {
1262
+ for (const key of Object.keys(service.environment ?? {})) {
1263
+ if (key.startsWith("NUXT_") && !allowed.has(key))
1264
+ findings.push({ level, check: "nuxt", message: `service "${name}" sets ${key}, which matches no runtimeConfig key in ${source}` });
1265
+ }
1266
+ }
1267
+ }
1268
+ return findings;
1269
+ }
1270
+
1271
+ // src/audit/run.ts
1272
+ var CONFIG_FILE = "release.config.ts";
1273
+ var DEFINE_CONFIG_IMPORT = /import\s*\{[^}]*\bdefineConfig\b[^}]*\}\s*from\s*['"]([^'"]+)['"]/;
1274
+ function installed(specifier, root) {
1275
+ try {
1276
+ Bun.resolveSync(specifier, root);
1277
+ return true;
1278
+ } catch {
1279
+ return false;
1280
+ }
1281
+ }
1282
+ async function loadConfig(root) {
1283
+ const specifier = DEFINE_CONFIG_IMPORT.exec(await Bun.file(join5(root, CONFIG_FILE)).text())?.[1];
1284
+ if (specifier !== undefined && !installed(specifier, root)) {
1285
+ Bun.plugin({
1286
+ name: "release-stand-in",
1287
+ setup(build) {
1288
+ build.module(specifier, () => ({ exports: { defineConfig: (config) => config }, loader: "object" }));
1289
+ }
1290
+ });
1291
+ }
1292
+ const config = (await import(join5(root, CONFIG_FILE))).default;
1293
+ if (config === undefined)
1294
+ fail(`${CONFIG_FILE} has no default export`);
1295
+ return config;
1296
+ }
1297
+ async function composeModels(options, base, overlays) {
1298
+ const findings = [];
1299
+ const load = async (files) => {
1300
+ try {
1301
+ return await options.loadCompose(options.root, files);
1302
+ } catch (error) {
1303
+ findings.push({ level: "error", check: "compose", message: `docker compose config failed for ${files.join(" + ")}: ${error instanceof Error ? error.message : String(error)}` });
1304
+ return;
1305
+ }
1306
+ };
1307
+ if (base === undefined) {
1308
+ findings.push({ level: "warn", check: "compose", message: "no compose file among deploySyncFiles, so every check that reads the compose model was skipped" });
1309
+ return { model: undefined, findings };
1310
+ }
1311
+ const model = await load([base]);
1312
+ for (const overlay of overlays)
1313
+ await load([base, overlay]);
1314
+ return { model, findings };
1315
+ }
1316
+ async function audit(config, options) {
1317
+ const { root } = options;
1318
+ const releases = config.releases ?? [];
1319
+ const required = config.requiredServerEnv ?? [];
1320
+ const { composeFiles, base, overlays } = composeLayout(root, config);
1321
+ const compose = await composeModels(options, base, overlays);
1322
+ const refs = envRefs(root, composeFiles);
1323
+ const gated = gatedServices(releases);
1324
+ const findings = [
1325
+ ...syncFindings(root, config),
1326
+ ...buildFindings(root, releases, options.env, options.home),
1327
+ ...compose.findings,
1328
+ ...envFindings(refs, required),
1329
+ ...versionFindings(refs, releases),
1330
+ ...imageFindings(config, releases, compose.model),
1331
+ ...restartFindings(config, releases, compose.model, base),
1332
+ ...postDeployFindings(releases, compose.model, base),
1333
+ ...healthFindings(gated, compose.model),
1334
+ ...routingFindings(config, gated, compose.model, base, overlays),
1335
+ ...layoutFindings(root, base, compose.model),
1336
+ ...nuxtFindings(root, releases, compose.model),
1337
+ ...gitignoreFindings(root)
1338
+ ];
1339
+ return { root, composeFiles, findings };
1340
+ }
1341
+ var hasConfig = (root) => existsSync3(join5(root, CONFIG_FILE));
1342
+
1343
+ // src/commands/audit.ts
1344
+ var usage2 = `stack audit [dir]
1345
+
1346
+ Cross-checks ${CONFIG_FILE} in dir (the current directory) against the compose files it syncs: sync files and build inputs exist, env variables are required or defaulted, versionEnv matches the compose interpolation, restart and post-deploy services exist, healthchecks, routing in overlays, bind mounts documented in the header, Nuxt runtimeConfig keys and .gitignore.
1347
+ Lists at most 25 errors and 25 warnings, the count of the rest after them (--limit <n>, --full for all); --json is never cut.
1348
+ Needs docker for \`docker compose config\`.
1349
+
1350
+ Exits 0 when it finds no error, 1 when it finds one, 2 when there is no ${CONFIG_FILE}.`;
1351
+ var AUDIT_LIMIT = 25;
1352
+ var options = {
1353
+ ...limitOptions(AUDIT_LIMIT),
1354
+ json: jsonOption("{ root, composeFiles, findings }")
1355
+ };
1356
+ async function audit2(args, overrides = {}) {
1357
+ const parsed = parse(args, usage2, options);
1358
+ const root = resolve2(parsed.positionals[0] ?? ".");
1359
+ if (!hasConfig(root)) {
1360
+ console.error(`no ${CONFIG_FILE} in ${root}`);
1361
+ return 2;
1362
+ }
1363
+ const result = await audit(await loadConfig(root), { root, loadCompose: dockerCompose, env: process9.env, home: homedir2(), ...overrides });
1364
+ if (parsed.values.json === true)
1365
+ printJson(result);
1366
+ else
1367
+ console.log(render(result, limitOf(parsed.values, AUDIT_LIMIT)));
1368
+ return errorsOf(result).length > 0 ? 1 : 0;
1369
+ }
1370
+
1371
+ // src/port.ts
1372
+ var MIN_PORT = 1024;
1373
+ var MAX_PORT = 65535;
1374
+ var DEFAULT_MAX_PORT = 32767;
1375
+ function stringToPort(name, min = MIN_PORT, max = DEFAULT_MAX_PORT) {
1376
+ let hash = 2166136261;
1377
+ for (let i = 0;i < name.length; i++) {
1378
+ hash ^= name.charCodeAt(i);
1379
+ hash = Math.imul(hash, 16777619) >>> 0;
1380
+ }
1381
+ return min + hash % (max - min + 1);
1382
+ }
1383
+ function isListening(port) {
1384
+ try {
1385
+ Bun.listen({ hostname: "0.0.0.0", port, socket: { data: () => {
1386
+ return;
1387
+ } } }).stop(true);
1388
+ return false;
1389
+ } catch (error) {
1390
+ return error.code === "EADDRINUSE";
1391
+ }
1392
+ }
1393
+
1394
+ // src/commands/port.ts
1395
+ var usage3 = `stack port <name>
1396
+
1397
+ Prints the port a name always hashes to (32-bit FNV-1a, ${MIN_PORT}-${DEFAULT_MAX_PORT} by default, below Linux's ephemeral range), so a service keeps the same port on every machine.
1398
+ Says on stderr when something already listens on it; the exit code stays 0.
1399
+
1400
+ Exits 0 when it printed the port, 2 on a usage error.`;
1401
+ var options2 = {
1402
+ min: { type: "string", description: `lowest port (${MIN_PORT}, nothing lower is allowed)` },
1403
+ max: { type: "string", description: `highest port (${DEFAULT_MAX_PORT}, up to ${MAX_PORT})` },
1404
+ json: jsonOption("{name, port, listening}")
1405
+ };
1406
+ async function port(args) {
1407
+ const parsed = parse(args, usage3, options2);
1408
+ const [name] = parsed.positionals;
1409
+ if (name === undefined)
1410
+ fail("a name is needed");
1411
+ const min = wholeNumber(parsed.values.min, "min", MIN_PORT, MIN_PORT);
1412
+ const max = wholeNumber(parsed.values.max, "max", DEFAULT_MAX_PORT, min);
1413
+ if (max > MAX_PORT)
1414
+ fail(`--max goes up to ${MAX_PORT}, not ${max}`);
1415
+ const number = stringToPort(name, min, max);
1416
+ if (parsed.values.json === true) {
1417
+ printJson({ name, port: number, listening: isListening(number) });
1418
+ return 0;
1419
+ }
1420
+ console.log(number);
1421
+ if (isListening(number))
1422
+ console.error(`port ${number} is already in use on this machine`);
1423
+ return 0;
1424
+ }
1425
+
1426
+ // src/cli.ts
1427
+ process10.exitCode = await runCli({
1428
+ name: "stack",
1429
+ version,
1430
+ about: "a stable port per service name, and a compose release audit",
1431
+ replaces: "picking a free host port by hand, and reading compose files against release.config.ts",
1432
+ examples: ["stack port api", ["stack audit", "this folder's release setup"]],
1433
+ commands: {
1434
+ port: { run: port, summary: "the port a name always hashes to, with a warning when something already listens on it" },
1435
+ audit: { run: audit2, summary: "cross-check release.config.ts against its compose files" }
1436
+ }
1437
+ });