@kaynooo/cli-wt 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js ADDED
@@ -0,0 +1,2768 @@
1
+ #!/usr/bin/env -S bun --no-env-file --config=/dev/null
2
+ // @bun
3
+
4
+ // src/cli.ts
5
+ import process11 from "process";
6
+ // ../kit/src/args.ts
7
+ import process5 from "process";
8
+ import { parseArgs } from "util";
9
+
10
+ // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rxztfxgv.js
11
+ var ot = /[.*+?^${}()|[\]\\]/g;
12
+ function B(t) {
13
+ return t.replace(ot, "\\$&");
14
+ }
15
+ var N = new Map;
16
+ var be = new Map(["\u20AC", "", "\u201A", "\u0192", "\u201E", "\u2026", "\u2020", "\u2021", "\u02C6", "\u2030", "\u0160", "\u2039", "\u0152", "", "\u017D", "", "", "\u2018", "\u2019", "\u201C", "\u201D", "\u2022", "\u2013", "\u2014", "\u02DC", "\u2122", "\u0161", "\u203A", "\u0153", "", "\u017E", "\u0178"].map((t, e) => [t, 128 + e]).filter(([t]) => t));
17
+ var z = new Map;
18
+
19
+ // ../kit/src/mode.ts
20
+ import process2 from "process";
21
+ var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
22
+ var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
23
+ function isSet(value) {
24
+ return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
25
+ }
26
+ function outputMode(stream = process2.stdout, env = process2.env) {
27
+ const chosen = env.KIT_MODE;
28
+ if (chosen !== undefined && MODES.has(chosen))
29
+ return chosen;
30
+ if (AGENT_VARIABLES.some((name) => isSet(env[name])))
31
+ return "agent";
32
+ if (stream.isTTY === true)
33
+ return "terminal";
34
+ return isSet(env.CI) ? "ci" : "pipe";
35
+ }
36
+
37
+ // ../kit/src/style.ts
38
+ import process3 from "process";
39
+
40
+ // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
41
+ var G2 = /^[a-f0-9]+$/i;
42
+ function b(r) {
43
+ let e = r.startsWith("#") ? r.slice(1) : r;
44
+ if (!G2.test(e))
45
+ return [0, 0, 0];
46
+ if (e.length === 3 || e.length === 4)
47
+ return [Number.parseInt(e[0] + e[0], 16), Number.parseInt(e[1] + e[1], 16), Number.parseInt(e[2] + e[2], 16)];
48
+ if (e.length !== 6 && e.length !== 8)
49
+ throw Error(`Invalid hex color length: ${e.length}`);
50
+ return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
51
+ }
52
+ var B2 = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], grey: [90, 39], blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], rgb: (r, e, l, n = "fg") => [`${n === "fg" ? 38 : 48};2;${r};${e};${l}`, n === "fg" ? 39 : 49], hex: (r, e = "fg") => {
53
+ let [l, n, c] = b(r);
54
+ return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
55
+ }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
56
+ var h = new Set(["", "1", "2", "3", "true"]);
57
+ function C(r, e = globalThis.process?.env ?? {}) {
58
+ if (e.FORCE_COLOR !== undefined)
59
+ return h.has(e.FORCE_COLOR);
60
+ if (e.NO_COLOR !== undefined || e.NODE_DISABLE_COLORS !== undefined || e.TERM === "dumb")
61
+ return false;
62
+ return r?.isTTY === true;
63
+ }
64
+ function f(r, e = []) {
65
+ let l = "", n = "";
66
+ for (let t = 0, i = e.length;t < i; t++)
67
+ l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
68
+ let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
69
+ return new Proxy(c, { get(t, i) {
70
+ let a = B2[i];
71
+ if (Array.isArray(a)) {
72
+ let s = g.get(i);
73
+ if (s === undefined)
74
+ s = f(r, [...e, a]), g.set(i, s);
75
+ return s;
76
+ }
77
+ if (typeof a === "function")
78
+ return (...s) => {
79
+ let y = `${i}:${s.join(",")}`, u = g.get(y);
80
+ if (u === undefined) {
81
+ if (g.size >= 64)
82
+ g.clear();
83
+ u = f(r, [...e, a(...s)]), g.set(y, u);
84
+ }
85
+ return u;
86
+ };
87
+ throw Error(`Unknown style: ${String(i)}`);
88
+ } });
89
+ }
90
+ function Fe(r = {}) {
91
+ return f(r);
92
+ }
93
+ var o = Fe();
94
+
95
+ // ../kit/src/theme.ts
96
+ var ENDS = new Map;
97
+ var STYLES = new Set(["bold", "dim", "italic", "underline", "inverse", "strikethrough", "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "gray", "grey", "blackBright", "redBright", "greenBright", "yellowBright", "blueBright", "magentaBright", "cyanBright", "whiteBright"]);
98
+ var MAX_FILE_BYTES = 64 * 1024;
99
+ var warned = new Set;
100
+
101
+ // ../kit/src/style.ts
102
+ function takesControlCodes(stream, env = process3.env) {
103
+ return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
104
+ }
105
+ function paint(stream, env = process3.env) {
106
+ return Fe({ stream: { isTTY: takesControlCodes(stream, env) }, env });
107
+ }
108
+ var STATUS_WORDS = {
109
+ passed: ["passed", "success", "succeeded", "ok"],
110
+ failed: ["failed", "failure", "error", "errored"],
111
+ running: ["running", "in_progress", "started", "holding"],
112
+ queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
113
+ skipped: ["skipped", "cancelled", "canceled", "manual"]
114
+ };
115
+ var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
116
+
117
+ // ../kit/src/format.ts
118
+ var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
119
+ function formatSeconds(total) {
120
+ let rest = Math.max(0, Math.round(total));
121
+ const amounts = UNITS.map(([unit, size]) => {
122
+ const amount = Math.floor(rest / size);
123
+ rest -= amount * size;
124
+ return `${amount}${unit}`;
125
+ });
126
+ const first = amounts.findIndex((amount) => !amount.startsWith("0"));
127
+ if (first === -1)
128
+ return "0s";
129
+ const next = amounts[first + 1];
130
+ return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
131
+ }
132
+ function formatDuration(ms) {
133
+ return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
134
+ }
135
+ function upTo(text, separator) {
136
+ const end = text.indexOf(separator);
137
+ return end === -1 ? text : text.slice(0, end);
138
+ }
139
+ var ESCAPE = String.fromCharCode(27);
140
+
141
+ // ../kit/src/help.ts
142
+ import process4 from "process";
143
+ var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
144
+ var USAGE_PREFIX = /^usage:\s*/i;
145
+ var FULL_STOP = /\.$/;
146
+ function usageLine(usage, colors = paint(process4.stdout)) {
147
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
148
+ }
149
+ function helpText(usage, options, colors = paint(process4.stdout), { examples = [], exits = [] } = {}) {
150
+ return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
151
+ `);
152
+ }
153
+ function exitRows(exits, colors = paint(process4.stdout)) {
154
+ if (exits.length === 0)
155
+ return [];
156
+ return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
157
+ }
158
+ function wantsHelpJson(env = process4.env) {
159
+ return env.KIT_HELP === "json";
160
+ }
161
+ function description(usage, { examples = [], replaces, exits } = {}, options) {
162
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
163
+ `);
164
+ const first = lines[0];
165
+ const colon = first.indexOf(": ");
166
+ const prose = lines[lines.indexOf("") + 1] ?? "";
167
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
168
+ return {
169
+ synopsis: colon === -1 ? first : first.slice(0, colon),
170
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
171
+ ...replaces === undefined ? {} : { replaces },
172
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
173
+ ...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
174
+ ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
175
+ };
176
+ }
177
+ function exampleRows(examples, colors = paint(process4.stdout)) {
178
+ if (examples.length === 0 || outputMode() === "agent")
179
+ return [];
180
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
181
+ }
182
+ var MAX_INLINE_CHOICES = 24;
183
+ function optionRows(options, colors = paint(process4.stdout)) {
184
+ const rows = Object.entries(options).map(([name, option]) => {
185
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
186
+ const choices = option.choices?.join("|");
187
+ const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
188
+ const named = inline ? `<${choices}>` : "<value>";
189
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
190
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
191
+ const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
192
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
193
+ });
194
+ const width = Math.max(0, ...rows.map((row) => row.width));
195
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
196
+ }
197
+
198
+ // ../kit/src/text.ts
199
+ function distance(a, b) {
200
+ const left = [...a];
201
+ const right = [...b];
202
+ let before = [];
203
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
204
+ for (const [i, x] of left.entries()) {
205
+ const current = [i + 1];
206
+ for (const [j, y] of right.entries()) {
207
+ let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
208
+ if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
209
+ cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
210
+ current.push(cost);
211
+ }
212
+ before = previous;
213
+ previous = current;
214
+ }
215
+ return previous[right.length] ?? 0;
216
+ }
217
+ function closest(name, names) {
218
+ const started = names.find((known) => known.startsWith(name));
219
+ if (started !== undefined)
220
+ return started;
221
+ const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
222
+ return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
223
+ }
224
+
225
+ // ../kit/src/args.ts
226
+ var DASHES = /^-+/;
227
+ class Exit extends Error {
228
+ code;
229
+ hint;
230
+ constructor(message, code, hint) {
231
+ super(message);
232
+ this.code = code;
233
+ this.hint = hint;
234
+ }
235
+ }
236
+ function fail(message, code = 2, hint) {
237
+ throw new Exit(message, code, hint);
238
+ }
239
+
240
+ class UsageError extends Exit {
241
+ constructor(message, hint) {
242
+ super(message, 2, hint);
243
+ }
244
+ }
245
+ function badUsage(message) {
246
+ throw new UsageError(message);
247
+ }
248
+
249
+ class HelpShown extends Exit {
250
+ constructor() {
251
+ super("help shown", 0);
252
+ }
253
+ }
254
+
255
+ class Completing {
256
+ options;
257
+ positionals;
258
+ candidates;
259
+ constructor(options, positionals = [], candidates = {}) {
260
+ this.options = options;
261
+ this.positionals = positionals;
262
+ this.candidates = candidates;
263
+ }
264
+ }
265
+ var completion = { active: false };
266
+ var OUTPUT_OPTIONS = {
267
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
268
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
269
+ };
270
+ function applyOutput(color, plain, env = process5.env) {
271
+ const when = plain === true ? "never" : color ?? "auto";
272
+ if (when === "auto")
273
+ return;
274
+ if (when !== "always" && when !== "never")
275
+ badUsage(`--color takes auto, always or never, not ${when}`);
276
+ if (when === "always") {
277
+ env.FORCE_COLOR = "1";
278
+ delete env.NO_COLOR;
279
+ } else {
280
+ env.NO_COLOR = "1";
281
+ delete env.FORCE_COLOR;
282
+ }
283
+ }
284
+ function parse(args, usage, options, settings = {}) {
285
+ const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
286
+ const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
287
+ const listing = listed(all, settings.allowNegative === true);
288
+ if (completion.active)
289
+ throw new Completing(listing, settings.positionals, settings.candidates);
290
+ const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
291
+ let parsed;
292
+ try {
293
+ parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
294
+ } catch (error) {
295
+ const message = parseError(error);
296
+ throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
297
+ }
298
+ const values = parsed.values;
299
+ applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
300
+ if (values.help === true) {
301
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
302
+ throw new HelpShown;
303
+ }
304
+ checkChoices(parsed.values, all);
305
+ checkConflicts(parsed.values, all);
306
+ if (settings.positionals !== undefined)
307
+ checkPositionals(parsed.positionals, settings.positionals);
308
+ return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
309
+ }
310
+ function splitRest(args, passes) {
311
+ const separator = passes ? args.indexOf("--") : -1;
312
+ return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
313
+ }
314
+ function splitTrailing(args, options, count) {
315
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
316
+ let seen = 0;
317
+ if (count === 0)
318
+ return { own: args, rest: undefined };
319
+ for (let at = 0;at < args.length; at++) {
320
+ const word = args[at];
321
+ if (word === "--")
322
+ break;
323
+ if (word.startsWith("-")) {
324
+ if (takesValue(word))
325
+ at++;
326
+ continue;
327
+ }
328
+ seen++;
329
+ if (seen === count)
330
+ return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
331
+ }
332
+ return { own: args, rest: undefined };
333
+ }
334
+ function listed(options, allowNegative) {
335
+ if (!allowNegative)
336
+ return options;
337
+ return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
338
+ if (option.type !== "boolean" || option.negative === undefined)
339
+ return [[name, option]];
340
+ return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
341
+ }));
342
+ }
343
+ function withAliases(args, options) {
344
+ const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
345
+ if (named.size === 0)
346
+ return args;
347
+ const separator = args.indexOf("--");
348
+ const own = separator === -1 ? args : args.slice(0, separator);
349
+ return [...own.map((arg) => {
350
+ const at = arg.indexOf("=");
351
+ const current = named.get(at === -1 ? arg : arg.slice(0, at));
352
+ return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
353
+ }), ...separator === -1 ? [] : args.slice(separator)];
354
+ }
355
+ function withBare(args, options) {
356
+ const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
357
+ if (bare.size === 0)
358
+ return args;
359
+ const separator = args.indexOf("--");
360
+ const own = separator === -1 ? args : args.slice(0, separator);
361
+ return [...own.flatMap((arg, index) => {
362
+ const optional = bare.get(arg);
363
+ const next = own[index + 1];
364
+ const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
365
+ return optional === undefined || value ? [arg] : [arg, optional.bare];
366
+ }), ...separator === -1 ? [] : args.slice(separator)];
367
+ }
368
+ function checkConflicts(values, options) {
369
+ const given = (name) => values[name] !== undefined && values[name] !== false;
370
+ for (const [name, { conflicts = [] }] of Object.entries(options)) {
371
+ const other = given(name) ? conflicts.find(given) : undefined;
372
+ if (other !== undefined)
373
+ badUsage(`--${name} cannot be used with --${other}`);
374
+ }
375
+ }
376
+ function checkChoices(values, options) {
377
+ for (const [name, option] of Object.entries(options)) {
378
+ if (option.choices === undefined)
379
+ continue;
380
+ const given = values[name];
381
+ for (const value of Array.isArray(given) ? given : [given]) {
382
+ if (typeof value === "string")
383
+ oneOf(value, name, option.choices);
384
+ }
385
+ }
386
+ }
387
+ function oneOf(value, name, choices) {
388
+ if (!choices.includes(value))
389
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
390
+ return value;
391
+ }
392
+ function checkPositionals(given, names) {
393
+ const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
394
+ const required = names.filter((name) => !name.startsWith("[")).length;
395
+ if (given.length < required)
396
+ badUsage(`missing ${names[given.length]}`);
397
+ if (!variadic && given.length > names.length)
398
+ badUsage(`unexpected argument ${given[names.length]}`);
399
+ }
400
+ function joinDashValues(args, options) {
401
+ const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
402
+ const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
403
+ const joined = [];
404
+ for (let i = 0;i < args.length; i++) {
405
+ const arg = args[i] ?? "";
406
+ if (arg === "--")
407
+ return [...joined, ...args.slice(i)];
408
+ const name = longOf.get(arg);
409
+ const next = args[i + 1];
410
+ if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
411
+ joined.push(`--${name}=${next}`);
412
+ i++;
413
+ } else {
414
+ joined.push(arg);
415
+ }
416
+ }
417
+ return joined;
418
+ }
419
+ function parseError(error) {
420
+ const message = upTo(error instanceof Error ? error.message : String(error), ". ");
421
+ return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
422
+ }
423
+ var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
424
+ function nearestOption(message, options, allowNegative) {
425
+ const typed = UNKNOWN_OPTION.exec(message)?.[1];
426
+ if (typed === undefined)
427
+ return;
428
+ const word = typed.replace(DASHES, "");
429
+ if (word.length < 2 && !typed.startsWith("--"))
430
+ return;
431
+ const known = Object.entries(options).flatMap(([name, option]) => [
432
+ ...option.short === undefined ? [] : [`-${option.short}`],
433
+ `--${name}`,
434
+ ...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
435
+ ]);
436
+ const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
437
+ return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
438
+ }
439
+ // ../kit/src/argv.ts
440
+ import { readFileSync, realpathSync } from "fs";
441
+ import { resolve } from "path";
442
+ import process6 from "process";
443
+ function commandLine() {
444
+ try {
445
+ return readFileSync("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
446
+ } catch {
447
+ return;
448
+ }
449
+ }
450
+ function realPath(word) {
451
+ try {
452
+ return realpathSync(resolve(word));
453
+ } catch {
454
+ return;
455
+ }
456
+ }
457
+ function scriptArgs(argv = process6.argv.slice(2), cmdline = commandLine(), script = process6.argv[1]) {
458
+ const target = script === undefined ? undefined : realPath(script) ?? script;
459
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve(word) === script || realPath(word) === target));
460
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
461
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
462
+ }
463
+ // ../kit/src/progress.ts
464
+ var ESC = String.fromCharCode(27);
465
+ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
466
+ var RESET_STYLE = `${ESC}[0m`;
467
+ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
468
+ // ../kit/src/cli.ts
469
+ import { readFileSync as readFileSync2, realpathSync as realpathSync2 } from "fs";
470
+ import { dirname as dirname2, join as join2 } from "path";
471
+ import process9 from "process";
472
+
473
+ // ../kit/src/completions.ts
474
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
475
+ 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'
476
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
477
+ set -l current (commandline -ct)
478
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
479
+ if test "$line" = __files__
480
+ __fish_complete_path $current
481
+ else
482
+ echo $line
483
+ end
484
+ end
485
+ end`;
486
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
487
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
488
+ local -a lines
489
+ COMPREPLY=()
490
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
491
+ for line in "\${lines[@]}"; do
492
+ if [[ $line == __files__ ]]; then
493
+ COMPREPLY+=($(compgen -f -- "$cur"))
494
+ else
495
+ words+="\${line%%$'\\t'*}"$'\\n'
496
+ fi
497
+ done
498
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
499
+ }`;
500
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
501
+ local line
502
+ local -a described plain
503
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
504
+ if [[ $line == __files__ ]]; then
505
+ _files
506
+ elif [[ $line == *$'\\t'* ]]; then
507
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
508
+ else
509
+ plain+=("$line")
510
+ fi
511
+ done
512
+ (( \${#described} )) && _describe -V value described
513
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
514
+ return 0
515
+ }`;
516
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
517
+ if (shell === "fish")
518
+ return `${header}
519
+ ${FISH_FUNCTION}
520
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
521
+ `).join("")}`;
522
+ if (shell === "bash")
523
+ return `${header}
524
+ ${BASH_FUNCTION}
525
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
526
+ `;
527
+ return `${header}
528
+ ${ZSH_FUNCTION}
529
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
530
+ `;
531
+ }
532
+
533
+ // ../kit/src/notify.ts
534
+ import process7 from "process";
535
+ var NOTIFY_AFTER_MS = 1e4;
536
+ var CANCELLED = 130;
537
+ function base64(text) {
538
+ return Buffer.from(text).toString("base64");
539
+ }
540
+ function notification(title, body, env = process7.env) {
541
+ const id = `kit${process7.pid}`;
542
+ 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\\`];
543
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
544
+ }
545
+ function notifyEnd(command, code, ms, { stream = process7.stderr, env = process7.env } = {}) {
546
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
547
+ return;
548
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
549
+ }
550
+
551
+ // ../kit/src/usage.ts
552
+ import { appendFileSync, mkdirSync } from "fs";
553
+ import { homedir } from "os";
554
+ import { dirname, isAbsolute, join } from "path";
555
+ import process8 from "process";
556
+
557
+ // ../kit/src/logs.ts
558
+ var DAY_MS = 24 * 60 * 60 * 1000;
559
+ var CLI_FOLDER = "kaynooo-cli";
560
+
561
+ // ../kit/src/usage.ts
562
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
563
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
564
+ var LONGEST_NAME = 40;
565
+ var usageError;
566
+ function noteUsageError(message) {
567
+ usageError = message;
568
+ }
569
+ function stateHome(env = process8.env) {
570
+ const dir = env.XDG_STATE_HOME;
571
+ return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
572
+ }
573
+ function usagePath(env = process8.env) {
574
+ return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
575
+ }
576
+ function usageRecorded(env = process8.env) {
577
+ const off = env.KAYNOOO_CLI_NO_USAGE;
578
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
579
+ }
580
+ function flagNames(argv) {
581
+ const end = argv.indexOf("--");
582
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
583
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
584
+ }
585
+ function usageEntry(bin, command, argv, code, now = new Date) {
586
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
587
+ usageError = undefined;
588
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
589
+ }
590
+ function recordUsage(entry, env = process8.env) {
591
+ if (!usageRecorded(env))
592
+ return;
593
+ try {
594
+ const path = usagePath(env);
595
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
596
+ appendFileSync(path, `${JSON.stringify(entry)}
597
+ `, { mode: 384 });
598
+ } catch {}
599
+ }
600
+
601
+ // ../kit/src/cli.ts
602
+ var LEVEL_OPTIONS = {
603
+ ...OUTPUT_OPTIONS,
604
+ help: { type: "boolean", short: "h", description: "show this help" }
605
+ };
606
+ var TOP_OPTIONS = {
607
+ ...LEVEL_OPTIONS,
608
+ version: { type: "boolean", short: "v", description: "print the version" },
609
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
610
+ };
611
+ async function commandRows(all, colors) {
612
+ const commands = shown(all);
613
+ const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
614
+ const groups = new Map([["Commands:", []]]);
615
+ const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
616
+ for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
617
+ const heading = group === undefined ? "Commands:" : `${group}:`;
618
+ const rows = groups.get(heading) ?? [];
619
+ rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`);
620
+ groups.set(heading, rows);
621
+ }
622
+ return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
623
+ }
624
+ function shown(commands) {
625
+ return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
626
+ }
627
+ function takeOutputFlags(argv) {
628
+ let index = 0;
629
+ for (;index < argv.length; index++) {
630
+ const word = argv[index];
631
+ if (word === "--plain")
632
+ applyOutput(undefined, true);
633
+ else if (word.startsWith("--color="))
634
+ applyOutput(word.slice("--color=".length), undefined);
635
+ else if (word === "--color" && argv[index + 1] !== undefined)
636
+ applyOutput(argv[++index], undefined);
637
+ else
638
+ break;
639
+ }
640
+ return argv.slice(index);
641
+ }
642
+ async function resolveSummary(summary) {
643
+ return typeof summary === "string" ? summary : summary();
644
+ }
645
+ function scopeOf(commands, extra, aliases) {
646
+ return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
647
+ }
648
+ async function expand(scope, words) {
649
+ if (scope.lazy.length === 0)
650
+ return scope;
651
+ const commands = { ...scope.commands };
652
+ for (const added of await Promise.all(scope.lazy.map(async (lazy) => lazy(words)))) {
653
+ for (const [name, command] of Object.entries(added))
654
+ commands[name] ??= command;
655
+ }
656
+ return { ...scope, commands, lazy: [] };
657
+ }
658
+ async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
659
+ const colors = paint(stream);
660
+ const prefix = path.join(" ");
661
+ const summary = await resolveSummary(lazySummary);
662
+ if (wantsHelpJson())
663
+ return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`, { examples, replaces }));
664
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
665
+ const options = fallback !== undefined && "run" in fallback ? await optionsOf(fallback.run) : undefined;
666
+ const own = Object.entries(options ?? {}).filter(([name]) => !(name in TOP_OPTIONS));
667
+ return [
668
+ header(colors, summary),
669
+ "",
670
+ usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
671
+ "",
672
+ ...await commandRows(commands, colors),
673
+ ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
674
+ "",
675
+ colors.bold("Options:"),
676
+ ...optionRows(path.length === 1 ? TOP_OPTIONS : LEVEL_OPTIONS, colors),
677
+ ...exampleRows(examples ?? [], colors),
678
+ "",
679
+ `${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`
680
+ ].join(`
681
+ `);
682
+ }
683
+ function printError(prefix, message, hint, cause) {
684
+ const colors = paint(process9.stderr);
685
+ const styled = takesControlCodes(process9.stderr);
686
+ const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
687
+ const under = (label, text, tint) => text === undefined ? "" : `
688
+ ${styled ? tint(label) : `${label}:`} ${text}`;
689
+ console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
690
+ }
691
+ function printJsonError(message, hint, cause) {
692
+ console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
693
+ }
694
+ function wantsJson(argv) {
695
+ const end = argv.indexOf("--");
696
+ return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
697
+ }
698
+ function reportThrown(prefix, error, redact = (text) => text, json = false) {
699
+ if (error instanceof HelpShown)
700
+ return 0;
701
+ const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
702
+ const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
703
+ const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
704
+ if (error instanceof Exit && error.code === 2)
705
+ noteUsageError(error.message);
706
+ const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
707
+ report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
708
+ return error instanceof Exit ? error.code : 1;
709
+ }
710
+ async function dispatch(level, typed, { version, redact }) {
711
+ const prefix = level.path.join(" ");
712
+ let argv;
713
+ try {
714
+ argv = takeOutputFlags(typed);
715
+ } catch (error) {
716
+ return reportThrown(prefix, error);
717
+ }
718
+ const [name, ...args] = argv;
719
+ const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
720
+ if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
721
+ try {
722
+ return await fallback.run([]);
723
+ } catch (error) {
724
+ return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
725
+ }
726
+ }
727
+ if (name === undefined && level.path.length > 1) {
728
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stderr));
729
+ return 2;
730
+ }
731
+ if (name === undefined || name === "help" || name === "--help" || name === "-h") {
732
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stdout));
733
+ return 0;
734
+ }
735
+ if (level.path.length === 1 && (name === "--version" || name === "-v")) {
736
+ console.log(version);
737
+ return 0;
738
+ }
739
+ let command = level.commands[level.aliases?.[name] ?? name];
740
+ let rest = args;
741
+ let ran = name;
742
+ if (command === undefined && level.lazy.length > 0) {
743
+ level = await expand(level, [...level.path.slice(1), ...argv]);
744
+ command = level.commands[level.aliases?.[name] ?? name];
745
+ }
746
+ if (command === undefined && level.defaultCommand !== undefined) {
747
+ command = level.commands[level.defaultCommand];
748
+ rest = argv;
749
+ ran = level.defaultCommand;
750
+ }
751
+ if (command === undefined) {
752
+ const meant = closest(name, Object.keys(shown(level.commands)));
753
+ printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
754
+ return 2;
755
+ }
756
+ if ("commands" in command) {
757
+ const { summary } = command;
758
+ 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 });
759
+ }
760
+ try {
761
+ return await command.run(rest);
762
+ } catch (error) {
763
+ return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
764
+ }
765
+ }
766
+ var COMPLETE = "__complete";
767
+ var FILES = "__files__";
768
+ async function completingOf(run) {
769
+ completion.active = true;
770
+ try {
771
+ await run([]);
772
+ } catch (error) {
773
+ if (error instanceof Completing)
774
+ return error;
775
+ } finally {
776
+ completion.active = false;
777
+ }
778
+ return new Completing({});
779
+ }
780
+ async function optionsOf(run) {
781
+ return (await completingOf(run)).options;
782
+ }
783
+ function candidateLine(candidate) {
784
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
785
+ }
786
+ function positionalBeingTyped(before, { options, positionals }) {
787
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
788
+ const typed = [];
789
+ let at = 0;
790
+ while (at < before.length) {
791
+ const word = before[at];
792
+ if (word === "--") {
793
+ typed.push(...before.slice(at + 1));
794
+ break;
795
+ }
796
+ if (!word.startsWith("-"))
797
+ typed.push(word);
798
+ else if (takesValue(word))
799
+ at++;
800
+ at++;
801
+ }
802
+ const last = positionals.at(-1);
803
+ if (typed.length < positionals.length)
804
+ return { name: positionals[typed.length], typed };
805
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
806
+ }
807
+ async function leafCandidates(run, words) {
808
+ const completing = await completingOf(run);
809
+ if ((words.at(-1) ?? "").startsWith("-"))
810
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
811
+ const flag = words.at(-2);
812
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
813
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
814
+ if (option?.type === "string") {
815
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
816
+ return values === undefined ? [FILES] : values.map(candidateLine);
817
+ }
818
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
819
+ return values === undefined ? [FILES] : values.map(candidateLine);
820
+ }
821
+ async function candidates(scope, defaultCommand, words, before = []) {
822
+ const [word = "", ...rest] = words;
823
+ const listing = rest.length === 0 && !word.startsWith("-");
824
+ let { commands, aliases } = scope;
825
+ let command = commands[aliases?.[word] ?? word];
826
+ if (listing || command === undefined) {
827
+ ({ commands, aliases } = await expand(scope, [...before, ...words]));
828
+ command = commands[aliases?.[word] ?? word];
829
+ }
830
+ if (listing) {
831
+ const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
832
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
833
+ const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
834
+ const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
835
+ return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
836
+ }
837
+ if (command === undefined) {
838
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
839
+ return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
840
+ }
841
+ return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
842
+ }
843
+ var COMPLETIONS = "--completions";
844
+ function flagValue([flag = "", ...rest]) {
845
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
846
+ }
847
+ function printCompletionScript(name, args) {
848
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
849
+ if (shell === undefined || args.length !== 1) {
850
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
851
+ return 2;
852
+ }
853
+ console.log(completionScript(shell, [name]).trimEnd());
854
+ return 0;
855
+ }
856
+ async function printCandidates(found) {
857
+ for (const line of await found)
858
+ console.log(line);
859
+ return 0;
860
+ }
861
+ function packageVersion(entry = Bun.main) {
862
+ let resolved = entry;
863
+ try {
864
+ resolved = realpathSync2(entry);
865
+ } catch {}
866
+ for (let dir = dirname2(resolved);; dir = dirname2(dir)) {
867
+ try {
868
+ const { version } = JSON.parse(readFileSync2(join2(dir, "package.json"), "utf8"));
869
+ if (typeof version === "string")
870
+ return version;
871
+ } catch {}
872
+ if (dirname2(dir) === dir)
873
+ return "0.0.0";
874
+ }
875
+ }
876
+ async function runCli(cli, argv = scriptArgs()) {
877
+ const version = cli.version ?? packageVersion();
878
+ if (argv[0] === COMPLETE)
879
+ return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
880
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
881
+ return printCompletionScript(cli.name, flagValue(argv));
882
+ const started = performance.now();
883
+ 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 });
884
+ const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
885
+ notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
886
+ if (cli.usage !== false) {
887
+ try {
888
+ recordUsage(usageEntry(cli.name, command, argv, code));
889
+ } catch {}
890
+ }
891
+ return code;
892
+ }
893
+ function commandPath(scope, argv) {
894
+ const path = [];
895
+ let level = scope;
896
+ for (const word of argv.filter((each) => !each.startsWith("-"))) {
897
+ const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
898
+ const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
899
+ if (command === undefined)
900
+ break;
901
+ path.push(word);
902
+ if (!("commands" in command))
903
+ break;
904
+ level = scopeOf(command.commands, command.extraCommands, command.aliases);
905
+ }
906
+ return path.length === 0 ? undefined : path.join(" ");
907
+ }
908
+ // ../kit/src/folders.ts
909
+ var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
910
+ // ../kit/src/secrets.ts
911
+ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
912
+ // ../kit/src/sessions.ts
913
+ var {Glob } = globalThis.Bun;
914
+ var SESSION_FILES = new Glob("*.json");
915
+ var ACCOUNT_DIRS = new Glob("*/sessions");
916
+ // src/commands.ts
917
+ import { existsSync as existsSync10, rmSync as rmSync4 } from "fs";
918
+ var {$: $8 } = globalThis.Bun;
919
+
920
+ // src/errors.ts
921
+ import { readFileSync as readFileSync3 } from "fs";
922
+ class KnownError extends Error {
923
+ }
924
+ var BOOT_TIME_LINE = /^btime (\d+)$/m;
925
+ var bootedAt;
926
+ function bootTime() {
927
+ bootedAt ??= Number(readFileSync3("/proc/stat", "utf8").match(BOOT_TIME_LINE)?.[1] ?? 0) * 1000;
928
+ return bootedAt;
929
+ }
930
+ function alive(pid) {
931
+ try {
932
+ process.kill(pid, 0);
933
+ return true;
934
+ } catch (error) {
935
+ return error.code === "EPERM";
936
+ }
937
+ }
938
+ function failKnown(error) {
939
+ if (error instanceof KnownError)
940
+ fail(error.message, 1);
941
+ throw error;
942
+ }
943
+
944
+ // src/files.ts
945
+ import { existsSync as existsSync4, lstatSync, mkdirSync as mkdirSync3, readFileSync as readFileSync6, renameSync, rmSync as rmSync2, statSync, symlinkSync, unlinkSync, writeFileSync as writeFileSync2 } from "fs";
946
+ import { constants } from "os";
947
+ import { basename as basename2, dirname as dirname4, join as join7 } from "path";
948
+ var {$: $2 } = globalThis.Bun;
949
+
950
+ // src/compose.ts
951
+ import { existsSync as existsSync3, readFileSync as readFileSync4 } from "fs";
952
+ import { join as join5 } from "path";
953
+ var {$ } = globalThis.Bun;
954
+
955
+ // src/project.ts
956
+ import { existsSync as existsSync2, readdirSync, realpathSync as realpathSync3 } from "fs";
957
+ import { basename, dirname as dirname3, join as join4 } from "path";
958
+
959
+ // src/config.ts
960
+ import { existsSync } from "fs";
961
+ import { homedir as homedir2 } from "os";
962
+ import { join as join3 } from "path";
963
+ var LEADING_TILDE = /^~(?=\/|$)/;
964
+ function expandHome(path) {
965
+ return path.replace(LEADING_TILDE, homedir2());
966
+ }
967
+ var configPath = () => process.env.WT_CONFIG ?? join3((process.env.XDG_CONFIG_HOME ?? "") || join3(homedir2(), ".config"), "wt", "config.ts");
968
+ function resolveConfig(config = {}) {
969
+ const configDir = join3(configPath(), "..");
970
+ const state = expandHome(config.state ?? join3(homedir2(), ".cache", "wt"));
971
+ return {
972
+ manifests: expandHome(config.manifests ?? join3(configDir, "projects")),
973
+ worktrees: expandHome(config.worktrees ?? "{root}/.worktrees/{repo}"),
974
+ overrides: expandHome(config.overrides ?? join3(homedir2(), ".local", "share", "wt", "overrides")),
975
+ state,
976
+ jobs: expandHome(config.jobs ?? join3(state, "jobs")),
977
+ proxyNetwork: config.proxyNetwork ?? "proxy",
978
+ runner: config.runner ?? {}
979
+ };
980
+ }
981
+ var loaded;
982
+ async function wtConfig() {
983
+ if (loaded)
984
+ return loaded;
985
+ const path = configPath();
986
+ if (!existsSync(path))
987
+ return loaded = resolveConfig();
988
+ try {
989
+ const { default: config } = await import(path);
990
+ return loaded = resolveConfig(config);
991
+ } catch (error) {
992
+ throw new KnownError(`${path} does not load: ${error instanceof Error ? error.message : String(error)}`);
993
+ }
994
+ }
995
+ function fillTemplate(argv, values) {
996
+ return argv.map((arg) => arg.replaceAll(/\{(\w+)\}/g, (match, key) => values[key] ?? match));
997
+ }
998
+
999
+ // src/port.ts
1000
+ function stringToPort(s, min = 1024, max = 65535) {
1001
+ let hash = 2166136261;
1002
+ for (let i = 0;i < s.length; i++) {
1003
+ hash ^= s.charCodeAt(i);
1004
+ hash = hash * 16777619 >>> 0;
1005
+ }
1006
+ return min + hash % (max - min + 1);
1007
+ }
1008
+
1009
+ // src/project.ts
1010
+ class WtError extends KnownError {
1011
+ }
1012
+ var TASK_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
1013
+ var ROUTE_TARGET = /^client$|^[\w.-]+:\d+$/;
1014
+ function worktreeFiles(settings, id) {
1015
+ return {
1016
+ override: join4(settings.overrides, `${id}.override.yml`),
1017
+ setupMarker: join4(settings.state, `${id}.setup`),
1018
+ clonesPending: join4(settings.state, `${id}.clones-pending`)
1019
+ };
1020
+ }
1021
+ function worktreeHost(host, task) {
1022
+ return host.startsWith("*.") ? `*.${task}.${host.slice(2)}` : `${task}.${host}`;
1023
+ }
1024
+ function assertValid(project) {
1025
+ for (const route of project.routes) {
1026
+ if (!ROUTE_TARGET.test(route.to))
1027
+ throw new WtError(`${project.name}: route ${route.host} goes to "${route.to}", expected "client" or "<service>:<port>"`);
1028
+ if (route.passthrough && project.certs === undefined)
1029
+ throw new WtError(`${project.name}: passthrough route ${route.host} needs \`certs\``);
1030
+ }
1031
+ }
1032
+ async function loadProjects() {
1033
+ const settings = await wtConfig();
1034
+ const files = existsSync2(settings.manifests) ? readdirSync(settings.manifests).filter((file) => file.endsWith(".ts")).sort() : [];
1035
+ return Promise.all(files.map(async (file) => {
1036
+ const { default: config } = await import(join4(settings.manifests, file));
1037
+ const project = { ...config, root: expandHome(config.root), name: basename(file, ".ts"), settings };
1038
+ assertValid(project);
1039
+ return project;
1040
+ }));
1041
+ }
1042
+ async function findProject(name) {
1043
+ const project = (await loadProjects()).find((p) => p.name === name);
1044
+ if (!project)
1045
+ throw new WtError(`no project named ${name} in ${(await wtConfig()).manifests}`);
1046
+ return project;
1047
+ }
1048
+ var tasksDir = (project) => fillTemplate([project.settings.worktrees], { root: dirname3(project.root), repo: basename(project.root) })[0];
1049
+ function worktreeOf(project, task) {
1050
+ if (task === "main" || !TASK_PATTERN.test(task))
1051
+ throw new WtError(`invalid task name "${task}": lowercase letters, digits and inner dashes, at most 63, and not "main"`);
1052
+ const mainHosts = new Set(project.routes.map((route) => route.host));
1053
+ const taken = project.routes.find((route) => mainHosts.has(worktreeHost(route.host, task)));
1054
+ if (taken)
1055
+ throw new WtError(`invalid task name "${task}": the worktree's ${worktreeHost(taken.host, task)} would be one of main's hosts`);
1056
+ const id = `${basename(project.root)}--${task}`;
1057
+ return {
1058
+ project,
1059
+ task,
1060
+ dir: join4(tasksDir(project), task),
1061
+ id,
1062
+ clientPort: stringToPort(`${project.name}--${task}`),
1063
+ files: worktreeFiles(project.settings, id)
1064
+ };
1065
+ }
1066
+ function assertWorktreeExists(worktree) {
1067
+ if (!existsSync2(worktree.dir))
1068
+ throw new WtError(`no worktree ${worktree.task}, create it with \`wt add ${worktree.task}\``);
1069
+ }
1070
+ function listTasks(project) {
1071
+ const dir = tasksDir(project);
1072
+ return existsSync2(dir) ? readdirSync(dir).filter((task) => TASK_PATTERN.test(task)).sort() : [];
1073
+ }
1074
+ async function locate(cwd, projectName) {
1075
+ const here = realpathSync3(cwd);
1076
+ const projects = projectName !== undefined ? [await findProject(projectName)] : await loadProjects();
1077
+ for (const project of projects) {
1078
+ const dir = tasksDir(project);
1079
+ if (here.startsWith(`${dir}/`)) {
1080
+ const rest = here.slice(dir.length + 1);
1081
+ const slash = rest.indexOf("/");
1082
+ return { project, task: slash === -1 ? rest : rest.slice(0, slash) };
1083
+ }
1084
+ if (here === project.root || here.startsWith(`${project.root}/`))
1085
+ return { project, task: "main" };
1086
+ }
1087
+ if (projects.length === 1)
1088
+ return { project: projects[0], task: "main" };
1089
+ throw new WtError("not inside a known project or worktree (cd into one, or pass --project)");
1090
+ }
1091
+ async function locateWorktree(cwd, task, projectName) {
1092
+ const here = await locate(cwd, projectName);
1093
+ const name = task ?? here.task;
1094
+ if (name === "main")
1095
+ throw new WtError("this is the main checkout, name a task");
1096
+ return worktreeOf(here.project, name);
1097
+ }
1098
+
1099
+ // src/compose.ts
1100
+ var COMPOSE_FILES = ["compose.yaml", "compose.yml", "docker-compose.yaml", "docker-compose.yml"];
1101
+ var SKIP_PROFILE = "wt-skip";
1102
+ function composeEnv(overrides = {}) {
1103
+ const env = Object.entries(process.env).filter(([key]) => key !== "COMPOSE_FILE" && key !== "COMPOSE_PROJECT_NAME");
1104
+ return { ...Object.fromEntries(env), ...overrides };
1105
+ }
1106
+ async function composeConfig(dir, env = {}) {
1107
+ const result = await $`docker compose config --format json`.cwd(dir).env(composeEnv(env)).quiet().nothrow();
1108
+ if (result.exitCode !== 0)
1109
+ throw new WtError(`docker compose config failed in ${dir}:
1110
+ ${result.stderr.toString()}`);
1111
+ return JSON.parse(result.stdout.toString());
1112
+ }
1113
+ var COMPOSE_FILE_LINE = /^COMPOSE_FILE=(.*)$/m;
1114
+ var QUOTES_AROUND = /^["']|["']$/g;
1115
+ function baseComposeFiles(dir, overrides) {
1116
+ const envFile = join5(dir, ".env");
1117
+ const line = existsSync3(envFile) ? readFileSync4(envFile, "utf8").match(COMPOSE_FILE_LINE) : null;
1118
+ const files = line ? line[1].replace(QUOTES_AROUND, "").split(":").filter(Boolean) : [];
1119
+ const base = files.filter((file) => !file.startsWith(`${overrides}/`));
1120
+ if (base.length)
1121
+ return base;
1122
+ const found = COMPOSE_FILES.find((file) => existsSync3(join5(dir, file)));
1123
+ if (found === undefined)
1124
+ throw new WtError(`no compose file in ${dir}`);
1125
+ return [found];
1126
+ }
1127
+ var q = (value) => JSON.stringify(value);
1128
+ var DEVPROXY_HOST_LABEL = /^devproxy\.[\w-]+\.host$/;
1129
+ var SERVICE = /^[^:]*/;
1130
+ function proxyLabels(worktree, config) {
1131
+ const { routes, skip = [] } = worktree.project;
1132
+ const labels = new Map;
1133
+ const add = (service, ...entries) => labels.set(service, [...labels.get(service) ?? [], ...entries]);
1134
+ const routed = routes.find((route) => route.to !== "client")?.to;
1135
+ const anchor = routed === undefined ? Object.keys(config.services).find((service) => !skip.includes(service)) : SERVICE.exec(routed)[0];
1136
+ for (const [index, route] of routes.entries()) {
1137
+ const key = `devproxy.wt${index}`;
1138
+ const host = [`${key}.host`, worktreeHost(route.host, worktree.task)];
1139
+ if (route.to === "client") {
1140
+ if (anchor !== undefined)
1141
+ add(anchor, host, [`${key}.to`, `host:${worktree.clientPort}`]);
1142
+ continue;
1143
+ }
1144
+ const [service = "", port = ""] = route.to.split(":");
1145
+ add(service, host, [`${key}.port`, port], ...route.passthrough ? [[`${key}.passthrough`, "true"]] : []);
1146
+ }
1147
+ for (const [service, settings] of Object.entries(config.services)) {
1148
+ for (const [key, value] of Object.entries(settings.labels ?? {})) {
1149
+ if (DEVPROXY_HOST_LABEL.test(key))
1150
+ add(service, [key, value.split(",").map((host) => worktreeHost(host.trim(), worktree.task)).join(",")]);
1151
+ }
1152
+ }
1153
+ return labels;
1154
+ }
1155
+ function renderOverride(worktree, config) {
1156
+ const skip = new Set(worktree.project.skip);
1157
+ const routeHosts = new Set(worktree.project.routeHosts);
1158
+ const labels = proxyLabels(worktree, config);
1159
+ const network = worktree.project.settings.proxyNetwork;
1160
+ const extraHosts = worktree.project.routes.filter((route) => !route.host.startsWith("*.")).map((route) => ` - ${q(`${worktreeHost(route.host, worktree.task)}:host-gateway`)}`);
1161
+ const lines = [`# Generated by wt for ${worktree.id}, rewritten on every \`wt sync\`.`, "services:"];
1162
+ let joined = false;
1163
+ for (const [name, service] of Object.entries(config.services)) {
1164
+ const body = [];
1165
+ if (skip.has(name))
1166
+ body.push(` profiles: [${q(SKIP_PROFILE)}]`);
1167
+ if (service.container_name !== undefined && service.container_name !== "")
1168
+ body.push(" container_name: !reset null");
1169
+ if ((service.ports?.length ?? 0) > 0)
1170
+ body.push(" ports: !reset []");
1171
+ if (routeHosts.has(name) && extraHosts.length)
1172
+ body.push(" extra_hosts:", ...extraHosts);
1173
+ if (labels.has(name))
1174
+ body.push(" labels:", ...labels.get(name).map(([key, value]) => ` ${q(key)}: ${q(value)}`));
1175
+ const networks = (service.network_mode ?? "") !== "" ? [] : Object.entries(service.networks ?? {});
1176
+ const joins = (service.network_mode ?? "") === "" && !skip.has(name) && !(network in (service.networks ?? {})) && labels.get(name)?.some(([key]) => key.endsWith(".port")) === true;
1177
+ const networkLines = networks.flatMap(([own, settings]) => {
1178
+ if (own === network)
1179
+ return (settings?.aliases?.length ?? 0) > 0 ? [` ${network}:`, " aliases: !reset []"] : [];
1180
+ if (service.container_name !== undefined && service.container_name !== "")
1181
+ return [` ${q(own)}:`, ` aliases: [${q(service.container_name)}]`];
1182
+ return joins ? [` ${q(own)}: {}`] : [];
1183
+ });
1184
+ if (joins) {
1185
+ joined = true;
1186
+ networkLines.push(` ${network}: {}`);
1187
+ }
1188
+ if (networkLines.length)
1189
+ body.push(" networks:", ...networkLines);
1190
+ if (body.length)
1191
+ lines.push(` ${q(name)}:`, ...body);
1192
+ }
1193
+ if (joined && config.networks?.[network] === undefined)
1194
+ lines.push("networks:", ` ${network}:`, ` name: ${network}`, " external: true");
1195
+ return `${lines.join(`
1196
+ `)}
1197
+ `;
1198
+ }
1199
+ function overrideWarnings(worktree, config) {
1200
+ const skip = new Set(worktree.project.skip);
1201
+ const network = worktree.project.settings.proxyNetwork;
1202
+ const warnings = [];
1203
+ for (const [name, service] of Object.entries(config.services)) {
1204
+ if (skip.has(name))
1205
+ continue;
1206
+ if (service.network_mode === "host")
1207
+ warnings.push(`service ${name} runs on the host network and may collide with main, consider adding it to skip`);
1208
+ if (service.networks && network in service.networks && !service.networks[network]?.aliases?.some((alias) => alias !== name))
1209
+ warnings.push(`service ${name} has no alias of its own on the proxy network, so the worktree answers to ${name} there too and the shared proxy round-robins between them, give it one in the project override`);
1210
+ }
1211
+ for (const [key, volume] of Object.entries(config.volumes ?? {})) {
1212
+ if (volume.external || volume.name !== undefined && !volume.name.startsWith(`${config.name}_`))
1213
+ warnings.push(`volume ${key} is named ${volume.name ?? key} outside the project, main and the worktree share it`);
1214
+ }
1215
+ return warnings;
1216
+ }
1217
+ async function runningProjects() {
1218
+ const result = await $`docker compose ls --format json`.quiet().nothrow();
1219
+ if (result.exitCode !== 0)
1220
+ return new Set;
1221
+ return new Set(JSON.parse(result.stdout.toString()).map((stack) => stack.Name));
1222
+ }
1223
+
1224
+ // src/queue.ts
1225
+ import { mkdirSync as mkdirSync2, readdirSync as readdirSync2, readFileSync as readFileSync5, rmSync, writeFileSync } from "fs";
1226
+ import { join as join6 } from "path";
1227
+ var queueDir = (settings, name) => join6(settings.state, "queues", name);
1228
+ var POLL_MS = 1000;
1229
+ function liveTickets(dir) {
1230
+ const names = readdirSync2(dir).sort();
1231
+ return names.filter((name) => {
1232
+ const dash = name.indexOf("-");
1233
+ if (Number(name.slice(0, dash)) >= bootTime() && alive(Number(name.slice(dash + 1))))
1234
+ return true;
1235
+ rmSync(join6(dir, name), { force: true });
1236
+ return false;
1237
+ });
1238
+ }
1239
+ function labelOf(ticket) {
1240
+ try {
1241
+ return readFileSync5(ticket, "utf8");
1242
+ } catch {
1243
+ return "";
1244
+ }
1245
+ }
1246
+ async function inLine(dir, label, waiting, work) {
1247
+ mkdirSync2(dir, { recursive: true });
1248
+ const name = `${String(Date.now()).padStart(15, "0")}-${process.pid}`;
1249
+ const ticket = join6(dir, name);
1250
+ const release = () => rmSync(ticket, { force: true });
1251
+ writeFileSync(ticket, label);
1252
+ process.once("exit", release);
1253
+ try {
1254
+ let shown = -1;
1255
+ for (;; ) {
1256
+ const ahead = liveTickets(dir).filter((other) => other < name);
1257
+ if (ahead.length === 0)
1258
+ break;
1259
+ if (ahead.length !== shown) {
1260
+ shown = ahead.length;
1261
+ waiting(ahead.length, labelOf(join6(dir, ahead[0])));
1262
+ }
1263
+ await Bun.sleep(POLL_MS);
1264
+ }
1265
+ return await work();
1266
+ } finally {
1267
+ release();
1268
+ }
1269
+ }
1270
+
1271
+ // src/files.ts
1272
+ var PARTIAL = ".wt-partial";
1273
+ var PAUSE_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
1274
+ function writeIfChanged(path, content) {
1275
+ if (existsSync4(path) && readFileSync6(path, "utf8") === content)
1276
+ return false;
1277
+ mkdirSync3(dirname4(path), { recursive: true });
1278
+ writeFileSync2(path, content);
1279
+ return true;
1280
+ }
1281
+ async function volumeExists(name) {
1282
+ return (await $2`docker volume inspect ${name}`.quiet().nothrow()).exitCode === 0;
1283
+ }
1284
+ async function copyFromMain(worktree) {
1285
+ const warnings = [];
1286
+ for (const entry of worktree.project.copy ?? []) {
1287
+ const source = join7(worktree.project.root, entry);
1288
+ const target = join7(worktree.dir, entry);
1289
+ if (!existsSync4(source)) {
1290
+ warnings.push(`copy: ${entry} does not exist in main`);
1291
+ continue;
1292
+ }
1293
+ if (existsSync4(target))
1294
+ continue;
1295
+ const partial = `${target}${PARTIAL}`;
1296
+ mkdirSync3(dirname4(target), { recursive: true });
1297
+ rmSync2(partial, { recursive: true, force: true });
1298
+ await $2`cp -a --reflink=auto ${source} ${partial}`.quiet();
1299
+ renameSync(partial, target);
1300
+ }
1301
+ return warnings;
1302
+ }
1303
+ function linkFromMain(worktree) {
1304
+ for (const entry of worktree.project.link ?? []) {
1305
+ const source = join7(worktree.project.root, entry);
1306
+ const target = join7(worktree.dir, entry);
1307
+ if (existsSync4(source) && !existsSync4(target)) {
1308
+ mkdirSync3(dirname4(target), { recursive: true });
1309
+ symlinkSync(source, target);
1310
+ }
1311
+ }
1312
+ }
1313
+ var WILDCARD_LABEL = /^\*\./;
1314
+ function rewriteHosts(text, routes, task) {
1315
+ const hosts = [...new Set(routes.map((route) => route.host.replace(WILDCARD_LABEL, "")))].sort((a, b) => b.length - a.length);
1316
+ const pattern = new RegExp(`(?<![\\w.-])(\\.?)(${hosts.map(B).join("|")})(?![\\w.-])`, "g");
1317
+ return text.replace(pattern, (_, dot, host) => `${dot}${worktreeHost(host, task)}`);
1318
+ }
1319
+ function setEnvValue(text, key, value) {
1320
+ const line = `${key}=${value}`;
1321
+ const pattern = new RegExp(`^${B(key)}=.*$`, "m");
1322
+ if (pattern.test(text))
1323
+ return text.replace(pattern, line);
1324
+ return `${text}${text === "" || text.endsWith(`
1325
+ `) ? "" : `
1326
+ `}${line}
1327
+ `;
1328
+ }
1329
+ function expandEnvValue(value, worktree) {
1330
+ return value.replaceAll("{task}", worktree.task).replaceAll("{port}", String(worktree.clientPort));
1331
+ }
1332
+ function writeEnvFiles(worktree) {
1333
+ const { project, task, dir } = worktree;
1334
+ const envFiles = (project.copy ?? []).filter((entry) => basename2(entry).startsWith(".env") && statSync(join7(dir, entry), { throwIfNoEntry: false })?.isFile());
1335
+ for (const entry of new Set([...envFiles, ".env"])) {
1336
+ const file = join7(dir, entry);
1337
+ let text = existsSync4(file) ? rewriteHosts(readFileSync6(file, "utf8"), project.routes, task) : "";
1338
+ for (const [key, value] of Object.entries(project.env?.[entry] ?? {}))
1339
+ text = setEnvValue(text, key, expandEnvValue(value, worktree));
1340
+ if (entry === ".env") {
1341
+ text = setEnvValue(text, "COMPOSE_PROJECT_NAME", worktree.id);
1342
+ text = setEnvValue(text, "COMPOSE_FILE", [...baseComposeFiles(dir, worktree.project.settings.overrides), worktree.files.override].join(":"));
1343
+ }
1344
+ writeIfChanged(file, text);
1345
+ }
1346
+ }
1347
+ function unlinkLegacySymlink(dir, entry) {
1348
+ let path = dir;
1349
+ for (const part of entry.split("/")) {
1350
+ path = join7(path, part);
1351
+ const stat = lstatSync(path, { throwIfNoEntry: false });
1352
+ if (!stat)
1353
+ return;
1354
+ if (stat.isSymbolicLink())
1355
+ return unlinkSync(path);
1356
+ }
1357
+ }
1358
+ async function mainContainers(main, status) {
1359
+ return (await $2`docker ps -q --filter ${`status=${status}`} --filter ${`label=com.docker.compose.project=${main.name}`}`.quiet().text()).split(`
1360
+ `).filter(Boolean);
1361
+ }
1362
+ function unpause(ids) {
1363
+ if (ids.length)
1364
+ Bun.spawnSync(["docker", "unpause", ...ids], { stdout: "ignore", stderr: "ignore" });
1365
+ }
1366
+ async function whilePaused(ids, work, abort, record) {
1367
+ const release = () => {
1368
+ unpause(ids);
1369
+ if (record !== undefined)
1370
+ rmSync2(record, { force: true });
1371
+ };
1372
+ const onSignal = (signal) => {
1373
+ abort?.();
1374
+ release();
1375
+ process.exit(128 + constants.signals[signal]);
1376
+ };
1377
+ for (const signal of PAUSE_SIGNALS)
1378
+ process.once(signal, onSignal);
1379
+ try {
1380
+ if (ids.length) {
1381
+ if (record !== undefined) {
1382
+ mkdirSync3(dirname4(record), { recursive: true });
1383
+ writeFileSync2(record, `${ids.join(`
1384
+ `)}
1385
+ `);
1386
+ }
1387
+ await $2`docker pause ${ids}`.quiet();
1388
+ }
1389
+ return await work();
1390
+ } finally {
1391
+ for (const signal of PAUSE_SIGNALS)
1392
+ process.off(signal, onSignal);
1393
+ release();
1394
+ }
1395
+ }
1396
+ async function settle(copies) {
1397
+ const results = await Promise.allSettled(copies.map(async (copy) => copy()));
1398
+ return results.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
1399
+ }
1400
+ function failureText(error) {
1401
+ if (error instanceof $2.ShellError)
1402
+ return error.stderr.toString().trim() || error.message;
1403
+ return error instanceof Error ? error.message : String(error);
1404
+ }
1405
+ var pausedRecord = (worktree) => queueDir(worktree.project.settings, `${worktree.project.name}.paused`);
1406
+ function readPending(file) {
1407
+ return new Set(existsSync4(file) ? readFileSync6(file, "utf8").split(`
1408
+ `).filter(Boolean) : []);
1409
+ }
1410
+ function writePending(file, volumes) {
1411
+ const text = [...volumes].join(`
1412
+ `);
1413
+ if (!text)
1414
+ return rmSync2(file, { force: true });
1415
+ mkdirSync3(dirname4(file), { recursive: true });
1416
+ writeFileSync2(file, `${text}
1417
+ `);
1418
+ }
1419
+ async function cloneData(worktree, main) {
1420
+ return inLine(queueDir(worktree.project.settings, `${worktree.project.name}.clone`), `cloning ${worktree.task}`, (_, running) => console.error(`wt: ${worktree.project.name}'s main is busy ${running || "cloning"}, waiting`), async () => {
1421
+ const record = pausedRecord(worktree);
1422
+ const recorded = readPending(record);
1423
+ const leftover = recorded.size ? (await mainContainers(main, "paused")).filter((id) => recorded.has(id)) : [];
1424
+ unpause(leftover);
1425
+ rmSync2(record, { force: true });
1426
+ const warnings = leftover.length ? [`clone: unpaused ${leftover.length} of main's containers a clone cut short had left paused`] : [];
1427
+ return [...warnings, ...await cloneInLine(worktree, main)];
1428
+ });
1429
+ }
1430
+ async function cloneInLine(worktree, main) {
1431
+ const warnings = [];
1432
+ const pending = [];
1433
+ const unfinished = readPending(worktree.files.clonesPending);
1434
+ const copyLabel = `wt.clone=${worktree.id}`;
1435
+ const stopCopies = () => {
1436
+ const ids = Bun.spawnSync(["docker", "ps", "-q", "--filter", `label=${copyLabel}`]).stdout.toString().split(`
1437
+ `).filter(Boolean);
1438
+ if (ids.length)
1439
+ Bun.spawnSync(["docker", "rm", "-f", ...ids], { stdout: "ignore", stderr: "ignore" });
1440
+ };
1441
+ for (const entry of worktree.project.clone ?? []) {
1442
+ const source = join7(worktree.project.root, entry);
1443
+ if (existsSync4(source)) {
1444
+ unlinkLegacySymlink(worktree.dir, entry);
1445
+ const target = join7(worktree.dir, entry);
1446
+ if (existsSync4(target))
1447
+ continue;
1448
+ if (!statSync(source).isDirectory())
1449
+ throw new WtError(`clone: ${entry} is not a directory`);
1450
+ const partial = `/to/${basename2(target)}${PARTIAL}`;
1451
+ pending.push({
1452
+ copy: async () => {
1453
+ mkdirSync3(dirname4(target), { recursive: true });
1454
+ await $2`docker run --rm --label ${copyLabel} -v ${`${source}:/from:ro`} -v ${`${dirname4(target)}:/to`} alpine sh -c ${`rm -rf '${partial}' && mkdir '${partial}' && cp -a /from/. '${partial}/' && mv '${partial}' '/to/${basename2(target)}'`}`.quiet();
1455
+ }
1456
+ });
1457
+ continue;
1458
+ }
1459
+ const volume = main.volumes?.[entry];
1460
+ if (!volume) {
1461
+ warnings.push(`clone: ${entry} is neither a path in main nor a volume of its stack`);
1462
+ continue;
1463
+ }
1464
+ if (volume.driver_opts?.device !== undefined && volume.driver_opts.device !== "")
1465
+ throw new WtError(`clone: volume ${entry} is a bind to ${volume.driver_opts.device}, list that path instead`);
1466
+ const sourceVolume = volume.name ?? `${main.name}_${entry}`;
1467
+ const targetVolume = `${worktree.id}_${entry}`;
1468
+ if (await volumeExists(targetVolume)) {
1469
+ if (!unfinished.has(targetVolume))
1470
+ continue;
1471
+ const removed = await $2`docker volume rm ${targetVolume}`.quiet().nothrow();
1472
+ if (removed.exitCode !== 0)
1473
+ throw new WtError(`clone: volume ${targetVolume} was cut short mid-copy and cannot be emptied (${removed.stderr.toString().trim()}), \`wt down ${worktree.task}\` then \`wt sync ${worktree.task}\``);
1474
+ }
1475
+ if (!await volumeExists(sourceVolume)) {
1476
+ warnings.push(`clone: main has no volume ${sourceVolume} yet, the worktree starts with an empty one`);
1477
+ continue;
1478
+ }
1479
+ pending.push({
1480
+ volume: targetVolume,
1481
+ copy: async () => {
1482
+ await $2`docker volume create --label ${`com.docker.compose.project=${worktree.id}`} --label ${`com.docker.compose.volume=${entry}`} ${targetVolume}`.quiet();
1483
+ await $2`docker run --rm --label ${copyLabel} -v ${`${sourceVolume}:/from:ro`} -v ${`${targetVolume}:/to`} alpine cp -a /from/. /to/`.quiet();
1484
+ unfinished.delete(targetVolume);
1485
+ }
1486
+ });
1487
+ }
1488
+ if (!pending.length) {
1489
+ writePending(worktree.files.clonesPending, unfinished);
1490
+ return warnings;
1491
+ }
1492
+ for (const { volume } of pending) {
1493
+ if (volume !== undefined)
1494
+ unfinished.add(volume);
1495
+ }
1496
+ writePending(worktree.files.clonesPending, unfinished);
1497
+ const failures = await whilePaused(await mainContainers(main, "running"), async () => settle(pending.map(({ copy }) => copy)), stopCopies, pausedRecord(worktree));
1498
+ writePending(worktree.files.clonesPending, unfinished);
1499
+ if (failures.length)
1500
+ throw new WtError(`clone failed, \`wt sync ${worktree.task}\` starts it again:
1501
+ ${failures.map(failureText).join(`
1502
+ `)}`);
1503
+ return warnings;
1504
+ }
1505
+
1506
+ // src/git.ts
1507
+ import { existsSync as existsSync5, mkdirSync as mkdirSync4, readdirSync as readdirSync3, rmdirSync } from "fs";
1508
+ import { basename as basename3, dirname as dirname5, join as join8 } from "path";
1509
+ var {$: $3 } = globalThis.Bun;
1510
+ async function git2(cwd, ...args) {
1511
+ const result = await $3`git -C ${cwd} ${args}`.quiet().nothrow();
1512
+ return { ok: result.exitCode === 0, out: `${result.stdout.toString()}${result.stderr.toString()}`.trim() };
1513
+ }
1514
+ async function branchExists(repo, branch) {
1515
+ if ((await git2(repo, "show-ref", "--quiet", "--verify", `refs/heads/${branch}`)).ok)
1516
+ return true;
1517
+ return (await git2(repo, "for-each-ref", "--format=%(refname)", `refs/remotes/*/${branch}`)).out !== "";
1518
+ }
1519
+ async function onBranch(repo, dir, branch) {
1520
+ return git2(repo, "worktree", "add", ...await branchExists(repo, branch) ? [dir, branch] : ["-b", branch, dir]);
1521
+ }
1522
+ async function addWorktrees(worktree, branch) {
1523
+ const { project, dir } = worktree;
1524
+ if (existsSync5(dir))
1525
+ throw new WtError(`${dir} already exists: \`wt sync ${worktree.task} -p ${project.name}\` finishes it, \`wt rm ${worktree.task} -p ${project.name}\` removes it`);
1526
+ mkdirSync4(dirname5(dir), { recursive: true });
1527
+ const root = project.repos.length ? await git2(project.root, "worktree", "add", "--detach", dir) : await onBranch(project.root, dir, branch);
1528
+ if (!root.ok)
1529
+ throw new WtError(`git worktree add failed for the root:
1530
+ ${root.out}`);
1531
+ for (const repo of project.repos) {
1532
+ const added = await onBranch(join8(project.root, repo), join8(dir, repo), branch);
1533
+ if (!added.ok) {
1534
+ await removeWorktrees(worktree);
1535
+ throw new WtError(`git worktree add failed for ${repo}, rolled back:
1536
+ ${added.out}`);
1537
+ }
1538
+ }
1539
+ }
1540
+ async function removeWorktrees(worktree) {
1541
+ const { project, dir } = worktree;
1542
+ await Promise.all(project.repos.map(async (repo) => git2(join8(project.root, repo), "worktree", "remove", "--force", join8(dir, repo))));
1543
+ await git2(project.root, "worktree", "remove", "--force", dir);
1544
+ if (existsSync5(dir))
1545
+ await $3`docker run --rm -v ${`${dirname5(dir)}:/parent`} alpine rm -rf ${`/parent/${basename3(dir)}`}`.quiet();
1546
+ await Promise.all([".", ...project.repos].map(async (repo) => git2(join8(project.root, repo), "worktree", "prune")));
1547
+ if (existsSync5(dirname5(dir)) && !readdirSync3(dirname5(dir)).length)
1548
+ rmdirSync(dirname5(dir));
1549
+ }
1550
+ async function dirtyRepos(worktree) {
1551
+ const repos = [".", ...worktree.project.repos];
1552
+ const statuses = await Promise.all(repos.map(async (repo) => git2(join8(worktree.dir, repo), "status", "--porcelain")));
1553
+ return repos.filter((_, index) => statuses[index].ok && statuses[index].out !== "").map((repo) => repo === "." ? "root" : repo);
1554
+ }
1555
+ async function unreachableByRepo(dir, repos) {
1556
+ const all = [".", ...repos];
1557
+ const counts = await Promise.all(all.map(async (repo) => git2(join8(dir, repo), "rev-list", "--count", "HEAD", "--not", "--branches", "--remotes", "--tags")));
1558
+ return all.map((repo, index) => ({ repo: repo === "." ? "root" : repo, count: Number(counts[index].ok ? counts[index].out : 0) })).filter(({ count }) => count > 0);
1559
+ }
1560
+ async function unreachableCommits(worktree) {
1561
+ return (await unreachableByRepo(worktree.dir, worktree.project.repos)).map(({ repo, count }) => `${repo} (${count} commit${count === 1 ? "" : "s"})`);
1562
+ }
1563
+ async function unreachableCount(dir, repos) {
1564
+ return (await unreachableByRepo(dir, repos)).reduce((total, { count }) => total + count, 0);
1565
+ }
1566
+ async function isRegistered(worktree) {
1567
+ const listed = await git2(worktree.project.root, "worktree", "list", "--porcelain");
1568
+ return listed.out.split(`
1569
+ `).includes(`worktree ${worktree.dir}`);
1570
+ }
1571
+ async function currentBranch(dir) {
1572
+ const result = await git2(dir, "rev-parse", "--abbrev-ref", "HEAD");
1573
+ return result.ok ? result.out : "?";
1574
+ }
1575
+
1576
+ // src/routes.ts
1577
+ import { existsSync as existsSync6, mkdirSync as mkdirSync5 } from "fs";
1578
+ import { join as join9 } from "path";
1579
+ var {$: $4 } = globalThis.Bun;
1580
+ var LEADING_STAR = /^\*/;
1581
+ async function mkcert(certFile, keyFile, hosts) {
1582
+ const result = await $4`mkcert -cert-file ${certFile} -key-file ${keyFile} ${hosts}`.quiet().nothrow();
1583
+ if (result.exitCode !== 0)
1584
+ throw new WtError(`mkcert failed for ${hosts.join(" ")}:
1585
+ ${result.stderr.toString()}`);
1586
+ }
1587
+ async function writeStackCerts(worktree) {
1588
+ const { project } = worktree;
1589
+ if (project.certs === undefined)
1590
+ return;
1591
+ const dir = join9(worktree.dir, project.certs);
1592
+ mkdirSync5(dir, { recursive: true });
1593
+ await Promise.all(project.routes.map(async (route) => {
1594
+ const served = worktreeHost(route.host, worktree.task);
1595
+ const name = served.replace(LEADING_STAR, "_wildcard");
1596
+ const cert = join9(dir, `${name}.pem`);
1597
+ const key = join9(dir, `${name}-key.pem`);
1598
+ return existsSync6(cert) && existsSync6(key) ? undefined : mkcert(cert, key, [served]);
1599
+ }));
1600
+ }
1601
+ function urlsOf(worktree) {
1602
+ return worktree.project.routes.filter((route) => !route.host.startsWith("*.")).map((route) => `https://${worktreeHost(route.host, worktree.task)}`);
1603
+ }
1604
+
1605
+ // src/run.ts
1606
+ import { existsSync as existsSync8, mkdirSync as mkdirSync6, readdirSync as readdirSync4, rmSync as rmSync3, writeFileSync as writeFileSync3 } from "fs";
1607
+ import { userInfo } from "os";
1608
+ import { join as join10 } from "path";
1609
+ var {$: $5 } = globalThis.Bun;
1610
+
1611
+ // src/env_file.ts
1612
+ import { existsSync as existsSync7, readFileSync as readFileSync7 } from "fs";
1613
+
1614
+ // ../env/src/dotenv.ts
1615
+ var ASSIGNMENT = /^\s*(?:export\s+)?([A-Z_][\w.-]*)\s*=(.*)$/i;
1616
+ var INLINE_COMMENT = /\s+#.*$/;
1617
+ var CARRIAGE_RETURN = /\r$/;
1618
+ var ESCAPES = { n: `
1619
+ `, r: "\r", t: "\t", '"': '"', "\\": "\\", $: "$" };
1620
+ function closingQuote(text, quote) {
1621
+ for (let index = 0;index < text.length; index++) {
1622
+ if (quote === '"' && text[index] === "\\")
1623
+ index++;
1624
+ else if (text[index] === quote)
1625
+ return index;
1626
+ }
1627
+ return -1;
1628
+ }
1629
+ function unescapeDollar(text) {
1630
+ return text.replaceAll("\\$", "$");
1631
+ }
1632
+ function unescapeDouble(text) {
1633
+ let out = "";
1634
+ for (let index = 0;index < text.length; index++) {
1635
+ const next = text[index + 1];
1636
+ if (text[index] === "\\" && next !== undefined && next in ESCAPES) {
1637
+ out += ESCAPES[next];
1638
+ index++;
1639
+ } else {
1640
+ out += text[index];
1641
+ }
1642
+ }
1643
+ return out;
1644
+ }
1645
+ function parseDotenv(text) {
1646
+ const physical = text.split(`
1647
+ `);
1648
+ const lines = [];
1649
+ for (let index = 0;index < physical.length; index++) {
1650
+ const line = physical[index] ?? "";
1651
+ const match = ASSIGNMENT.exec(line.replace(CARRIAGE_RETURN, ""));
1652
+ if (match === null) {
1653
+ lines.push({ raw: line });
1654
+ continue;
1655
+ }
1656
+ const [, key = "", rest = ""] = match;
1657
+ const start = rest.trimStart();
1658
+ const quote = start[0];
1659
+ if (quote !== '"' && quote !== "'" && quote !== "`") {
1660
+ lines.push({ raw: line, key, value: unescapeDollar(start.replace(INLINE_COMMENT, "").trim()) });
1661
+ continue;
1662
+ }
1663
+ let body = start.slice(1);
1664
+ let raw = line;
1665
+ let end = closingQuote(body, quote);
1666
+ const first = index;
1667
+ while (end === -1 && index + 1 < physical.length && !ASSIGNMENT.test(physical[index + 1] ?? "")) {
1668
+ index++;
1669
+ body += `
1670
+ ${(physical[index] ?? "").replace(CARRIAGE_RETURN, "")}`;
1671
+ raw += `
1672
+ ${physical[index] ?? ""}`;
1673
+ end = closingQuote(body, quote);
1674
+ }
1675
+ if (end === -1 && index + 1 < physical.length) {
1676
+ index = first;
1677
+ lines.push({ raw: line, key, value: unescapeDollar(start.replace(INLINE_COMMENT, "").trim()), unterminated: true });
1678
+ continue;
1679
+ }
1680
+ const inner = end === -1 ? body : body.slice(0, end);
1681
+ lines.push({ raw, key, value: quote === '"' ? unescapeDouble(inner) : unescapeDollar(inner) });
1682
+ }
1683
+ return { lines };
1684
+ }
1685
+ function entries(file) {
1686
+ const map = new Map;
1687
+ for (const line of file.lines) {
1688
+ if (line.key !== undefined)
1689
+ map.set(line.key, line.value ?? "");
1690
+ }
1691
+ return map;
1692
+ }
1693
+
1694
+ // src/env_file.ts
1695
+ function readEnvFile(path) {
1696
+ return existsSync7(path) ? Object.fromEntries(entries(parseDotenv(readFileSync7(path, "utf8")))) : {};
1697
+ }
1698
+
1699
+ // src/run.ts
1700
+ var POSTGRES = /^postgres(?:ql)?:$/;
1701
+ var DEFAULT_PORT = 5432;
1702
+ var READY_TRIES = 60;
1703
+ var testContainer = (worktree) => `wt-${worktree.project.name}-test-db`;
1704
+ function testDatabase(dir) {
1705
+ const base = existsSync8(join10(dir, ".env")) ? ".env" : ".env.dist";
1706
+ const env = Object.assign({}, ...[base, ".env.test", ".env.test.local"].map((file) => readEnvFile(join10(dir, file))));
1707
+ if (env.DATABASE_URL === undefined || env.DATABASE_URL === "")
1708
+ throw new WtError(`no DATABASE_URL in the test env files of ${dir}`);
1709
+ const url = new URL(env.DATABASE_URL);
1710
+ if (!POSTGRES.test(url.protocol))
1711
+ throw new WtError(`wt run only starts Postgres, and ${dir} tests against ${url.protocol.slice(0, -1)}`);
1712
+ return { host: url.hostname, port: Number(url.port || DEFAULT_PORT), user: decodeURIComponent(url.username), password: decodeURIComponent(url.password) };
1713
+ }
1714
+ function testToken(task) {
1715
+ return task.replaceAll("-", "_");
1716
+ }
1717
+ function databaseImage(config, host) {
1718
+ const service = config.services[host] ?? Object.values(config.services).find((each) => Object.values(each.networks ?? {}).some((network) => network?.aliases?.includes(host)));
1719
+ if (service?.image === undefined || service.image === "")
1720
+ throw new WtError(`no service of ${config.name} answers to ${host}, the test database host, with an image to start`);
1721
+ return service.image;
1722
+ }
1723
+ function runPlan(worktree, run, config, database, ids = userInfo(), tty = false) {
1724
+ const service = config.services[run.service];
1725
+ if (!service)
1726
+ throw new WtError(`${config.name} has no service ${run.service}`);
1727
+ const source = join10(worktree.project.root, run.dir);
1728
+ const target = service.volumes?.find((volume) => volume.type === "bind" && volume.source === source)?.target;
1729
+ if (target === undefined)
1730
+ throw new WtError(`${run.service} does not bind-mount ${source}, so wt cannot tell where the worktree's copy goes`);
1731
+ const network = `wt-${worktree.project.name}-test`;
1732
+ const container = testContainer(worktree);
1733
+ return {
1734
+ network,
1735
+ container,
1736
+ database: [
1737
+ "run",
1738
+ "-d",
1739
+ "--name",
1740
+ container,
1741
+ "--network",
1742
+ network,
1743
+ "--network-alias",
1744
+ database.host,
1745
+ "--tmpfs",
1746
+ "/var/lib/postgresql/data",
1747
+ "-e",
1748
+ `POSTGRES_USER=${database.user}`,
1749
+ "-e",
1750
+ "POSTGRES_PASSWORD",
1751
+ "-e",
1752
+ `PGPORT=${database.port}`,
1753
+ databaseImage(config, database.host)
1754
+ ],
1755
+ runner: (command) => [
1756
+ "run",
1757
+ "--rm",
1758
+ "-i",
1759
+ ...tty ? ["-t"] : [],
1760
+ "--pull",
1761
+ "never",
1762
+ "--network",
1763
+ network,
1764
+ ...run.dns !== undefined ? ["--dns", run.dns] : [],
1765
+ "-u",
1766
+ `${ids.uid}:${ids.gid}`,
1767
+ "-e",
1768
+ "HOME=/tmp",
1769
+ ...Object.entries(run.env ?? {}).flatMap(([key, value]) => ["-e", `${key}=${value}`]),
1770
+ "-e",
1771
+ `TEST_TOKEN=${testToken(worktree.task)}`,
1772
+ "-v",
1773
+ `${join10(worktree.dir, run.dir)}:${target}`,
1774
+ "-w",
1775
+ target,
1776
+ service.image ?? `${config.name}-${run.service}`,
1777
+ ...command
1778
+ ]
1779
+ };
1780
+ }
1781
+ async function runningId(container) {
1782
+ const result = await $5`docker inspect --format ${"{{if .State.Running}}{{.Id}}{{end}}"} ${container}`.quiet().nothrow();
1783
+ return result.text().trim() || undefined;
1784
+ }
1785
+ async function ensureDatabase(plan, database) {
1786
+ if ((await $5`docker network inspect ${plan.network}`.quiet().nothrow()).exitCode !== 0)
1787
+ await $5`docker network create ${plan.network}`.quiet().nothrow();
1788
+ let id = await runningId(plan.container);
1789
+ if (id === undefined) {
1790
+ await $5`docker rm -f ${plan.container}`.quiet().nothrow();
1791
+ const started = await $5`docker ${plan.database}`.env({ ...process.env, POSTGRES_PASSWORD: database.password }).quiet().nothrow();
1792
+ id = await runningId(plan.container);
1793
+ if (id === undefined)
1794
+ throw new WtError(`${plan.container} did not start:
1795
+ ${started.stderr.toString().trim()}`);
1796
+ }
1797
+ for (let tries = 0;tries < READY_TRIES; tries++) {
1798
+ if ((await $5`docker exec ${plan.container} pg_isready -q -h 127.0.0.1 -U ${database.user}`.quiet().nothrow()).exitCode === 0)
1799
+ return id;
1800
+ await Bun.sleep(1000);
1801
+ }
1802
+ throw new WtError(`${plan.container} is not accepting connections after ${READY_TRIES} s: docker logs ${plan.container}`);
1803
+ }
1804
+ async function runInherit(command) {
1805
+ const child = Bun.spawn(command, { stdio: ["inherit", "inherit", "inherit"] });
1806
+ const forward = (signal) => child.kill(signal);
1807
+ process.on("SIGINT", forward);
1808
+ process.on("SIGTERM", forward);
1809
+ try {
1810
+ return await child.exited;
1811
+ } finally {
1812
+ process.off("SIGINT", forward);
1813
+ process.off("SIGTERM", forward);
1814
+ }
1815
+ }
1816
+ async function forgetTestDatabases(worktree) {
1817
+ const container = testContainer(worktree);
1818
+ if (await runningId(container) !== undefined) {
1819
+ const listed = await $5`docker exec ${container} sh -c ${'psql -U "$POSTGRES_USER" -d postgres -Atc "select datname from pg_database"'}`.quiet().nothrow();
1820
+ const ours = listed.text().split(`
1821
+ `).filter((name) => name.endsWith(`_test${testToken(worktree.task)}`));
1822
+ for (const name of ours)
1823
+ await $5`docker exec ${container} sh -c ${'dropdb -U "$POSTGRES_USER" --force "$0"'} ${name}`.quiet().nothrow();
1824
+ }
1825
+ const markers = worktree.project.settings.state;
1826
+ if (!existsSync8(markers))
1827
+ return;
1828
+ for (const file of readdirSync4(markers).filter((name) => name.startsWith(`${worktree.id}.test-`)))
1829
+ rmSync3(join10(markers, file), { force: true });
1830
+ }
1831
+ async function provision(worktree, run, plan, databaseId) {
1832
+ const markers = worktree.project.settings.state;
1833
+ const marker = join10(markers, `${worktree.id}.test-${databaseId.slice(0, 12)}`);
1834
+ if (existsSync8(marker))
1835
+ return;
1836
+ await inLine(queueDir(worktree.project.settings, `${worktree.id}.provision`), "provisioning", () => console.error(`wt run: waiting for ${worktree.task}'s test database to be provisioned`), async () => {
1837
+ if (existsSync8(marker))
1838
+ return;
1839
+ console.error(`wt run: provisioning ${worktree.task}'s test database`);
1840
+ for (const step of run.provision) {
1841
+ if (await runInherit(["docker", ...plan.runner(["sh", "-c", step])]) !== 0)
1842
+ throw new WtError(`provisioning failed on \`${step}\`, run it again with \`wt run ${worktree.task} -- sh -c '${step}'\``);
1843
+ }
1844
+ mkdirSync6(markers, { recursive: true });
1845
+ writeFileSync3(marker, "");
1846
+ });
1847
+ }
1848
+ async function runTask(task, command, project) {
1849
+ const worktree = await locateWorktree(process.cwd(), task, project);
1850
+ const { run, name, root } = worktree.project;
1851
+ assertWorktreeExists(worktree);
1852
+ if (!run)
1853
+ throw new WtError(`${name} has no \`run\` in its manifest, so wt cannot tell which service runs its tests`);
1854
+ const database = testDatabase(join10(worktree.dir, run.dir));
1855
+ const plan = runPlan(worktree, run, await composeConfig(root), database, userInfo(), Boolean(process.stdin.isTTY && process.stdout.isTTY));
1856
+ await provision(worktree, run, plan, await ensureDatabase(plan, database));
1857
+ return runInherit(["docker", ...plan.runner(command)]);
1858
+ }
1859
+ async function runHeavy(command) {
1860
+ const label = `${command.join(" ")} (in ${process.cwd()})`;
1861
+ return inLine(queueDir(await wtConfig(), "heavy"), label, (ahead, running) => console.error(`wt heavy: ${ahead} ahead, running ${running}`), async () => runInherit(command));
1862
+ }
1863
+
1864
+ // src/stack.ts
1865
+ import { existsSync as existsSync9, mkdirSync as mkdirSync7, writeFileSync as writeFileSync4 } from "fs";
1866
+ import { homedir as homedir3 } from "os";
1867
+ import { dirname as dirname7 } from "path";
1868
+ var {$: $7 } = globalThis.Bun;
1869
+
1870
+ // src/proxy.ts
1871
+ import { dirname as dirname6, join as join11 } from "path";
1872
+ var {$: $6 } = globalThis.Bun;
1873
+ function devproxyArgv() {
1874
+ const onPath = Bun.which("devproxy");
1875
+ if (onPath !== null)
1876
+ return [onPath];
1877
+ try {
1878
+ return [process.execPath, join11(dirname6(Bun.resolveSync("@kaynooo/devproxy", import.meta.dir)), "..", "dist", "cli.js")];
1879
+ } catch {
1880
+ return [];
1881
+ }
1882
+ }
1883
+ async function hasDevproxy() {
1884
+ const argv = devproxyArgv();
1885
+ return argv.length > 0 && (await $6`${argv} hosts --json`.quiet().nothrow()).exitCode === 0;
1886
+ }
1887
+ async function proxyHostList() {
1888
+ const argv = devproxyArgv();
1889
+ const result = argv.length ? await $6`${argv} hosts --json`.quiet().nothrow() : undefined;
1890
+ return result?.exitCode === 0 ? JSON.parse(result.stdout.toString()) : [];
1891
+ }
1892
+ async function devproxyUp() {
1893
+ const argv = devproxyArgv();
1894
+ if (!argv.length || (await $6`${argv} up`.nothrow()).exitCode !== 0)
1895
+ throw new WtError("the shared proxy did not come up: `devproxy status` says why");
1896
+ }
1897
+
1898
+ // src/stack.ts
1899
+ var LEADING_ROOT = /^[/~]+/;
1900
+ var UNSAFE_IN_FILE_NAME = /[^\w.-]+/g;
1901
+ function slugOf(ref) {
1902
+ return ref.replace(LEADING_ROOT, "").replace(UNSAFE_IN_FILE_NAME, "--");
1903
+ }
1904
+ async function spawnInherit(argv, cwd, env = process.env) {
1905
+ return Bun.spawn(argv, { cwd, env, stdio: ["inherit", "inherit", "inherit"] }).exited;
1906
+ }
1907
+ async function runTemplate(template, worktree) {
1908
+ const argv = fillTemplate(template, { project: worktree.project.name, task: worktree.task, dir: worktree.dir, id: worktree.id });
1909
+ if (await spawnInherit(argv, worktree.dir) !== 0)
1910
+ throw new WtError(`\`${argv.join(" ")}\` failed`);
1911
+ }
1912
+ async function runSetup(worktree, env = composeEnv()) {
1913
+ const setup = worktree.project.setup ?? [];
1914
+ const marker = worktree.files.setupMarker;
1915
+ if (!setup.length || existsSync9(marker))
1916
+ return;
1917
+ for (const command of setup) {
1918
+ if (await spawnInherit(["sh", "-c", command], worktree.dir, env) !== 0)
1919
+ throw new WtError(`the worktree setup failed on \`${command}\``);
1920
+ }
1921
+ mkdirSync7(dirname7(marker), { recursive: true });
1922
+ writeFileSync4(marker, "");
1923
+ }
1924
+ async function stackUp(worktree) {
1925
+ const { up } = worktree.project.settings.runner;
1926
+ if (up)
1927
+ return runTemplate(up, worktree);
1928
+ if (await hasDevproxy())
1929
+ await devproxyUp();
1930
+ const network = worktree.project.settings.proxyNetwork;
1931
+ if (worktree.project.routes.length > 0 && (await $7`docker network inspect ${network}`.quiet().nothrow()).exitCode !== 0)
1932
+ throw new WtError(`the routed services join the ${network} network, which does not exist: install and configure devproxy, or set proxyNetwork in ${configPath()} to the network your proxy dials stacks on`);
1933
+ if (await spawnInherit(["docker", "compose", "up", "-d", "--build"], worktree.dir, composeEnv()) !== 0)
1934
+ throw new WtError(`docker compose up failed in ${worktree.dir}`);
1935
+ await runSetup(worktree);
1936
+ }
1937
+ async function stackDown(worktree) {
1938
+ const { down } = worktree.project.settings.runner;
1939
+ if (down && existsSync9(worktree.dir))
1940
+ return runTemplate(down, worktree);
1941
+ const here = existsSync9(worktree.dir);
1942
+ const argv = here ? ["docker", "compose", "down", "--remove-orphans"] : ["docker", "compose", "-p", worktree.id, "down", "--remove-orphans"];
1943
+ if (await spawnInherit(argv, here ? worktree.dir : homedir3(), composeEnv()) !== 0)
1944
+ throw new WtError(`docker compose down failed for ${worktree.id}`);
1945
+ }
1946
+ async function afterRemove(worktree) {
1947
+ const { removed } = worktree.project.settings.runner;
1948
+ if (!removed)
1949
+ return;
1950
+ const argv = fillTemplate(removed, { project: worktree.project.name, task: worktree.task, dir: worktree.dir, id: worktree.id });
1951
+ if (await spawnInherit(argv, worktree.project.root) !== 0)
1952
+ console.warn(`wt: \`${argv.join(" ")}\` failed after removing ${worktree.id}`);
1953
+ }
1954
+ async function hasContainers(composeName) {
1955
+ const found = await $7`docker ps -aq --filter ${`label=com.docker.compose.project=${composeName}`}`.quiet().nothrow();
1956
+ return found.stdout.toString().trim() !== "";
1957
+ }
1958
+
1959
+ // src/sync.ts
1960
+ async function syncWorktree(worktree) {
1961
+ assertWorktreeExists(worktree);
1962
+ const [warnings, main] = await Promise.all([copyFromMain(worktree), composeConfig(worktree.project.root)]);
1963
+ linkFromMain(worktree);
1964
+ writeEnvFiles(worktree);
1965
+ warnings.push(...await cloneData(worktree, main));
1966
+ const config = await composeConfig(worktree.dir, { COMPOSE_FILE: baseComposeFiles(worktree.dir, worktree.project.settings.overrides).join(":"), COMPOSE_PROJECT_NAME: worktree.id });
1967
+ writeIfChanged(worktree.files.override, renderOverride(worktree, config));
1968
+ warnings.push(...overrideWarnings(worktree, config));
1969
+ await composeConfig(worktree.dir);
1970
+ await writeStackCerts(worktree);
1971
+ for (const warning of warnings)
1972
+ console.warn(`wt: ${warning}`);
1973
+ }
1974
+
1975
+ // src/commands.ts
1976
+ var ANONYMOUS_VOLUME = /^[0-9a-f]{64}$/;
1977
+ var WHITESPACE = /\s+/;
1978
+ async function anonymousVolumes(worktree) {
1979
+ const containers = (await $8`docker ps -aq --filter ${`label=com.docker.compose.project=${worktree.id}`}`.quiet().text()).split(`
1980
+ `).filter(Boolean);
1981
+ if (!containers.length)
1982
+ return [];
1983
+ const mounts = await $8`docker inspect --format ${'{{range .Mounts}}{{if eq .Type "volume"}}{{.Name}} {{end}}{{end}}'} ${containers}`.quiet().nothrow();
1984
+ return mounts.text().split(WHITESPACE).filter((name) => ANONYMOUS_VOLUME.test(name));
1985
+ }
1986
+ async function removeVolumes(worktree, anonymous) {
1987
+ const named = (await $8`docker volume ls -q --filter ${`label=com.docker.compose.project=${worktree.id}`}`.quiet().text()).split(`
1988
+ `).filter((volume) => volume.startsWith(`${worktree.id}_`));
1989
+ const volumes = [...new Set([...named, ...anonymous])];
1990
+ if (!volumes.length)
1991
+ return;
1992
+ const removed = await $8`docker volume rm ${volumes}`.quiet().nothrow();
1993
+ if (removed.exitCode !== 0)
1994
+ throw new WtError(`could not remove the volumes of ${worktree.id}:
1995
+ ${removed.stderr.toString().trim()}`);
1996
+ }
1997
+ async function addTask(task, branch, options) {
1998
+ const { project } = await locate(process.cwd(), options.project);
1999
+ const worktree = worktreeOf(project, task);
2000
+ const checkout = branch ?? `wt/${task}`;
2001
+ await addWorktrees(worktree, checkout);
2002
+ try {
2003
+ await syncWorktree(worktree);
2004
+ } catch (error) {
2005
+ const way = `the worktree is checked out but not ready: \`wt sync ${task} -p ${project.name}\` resumes it, \`wt rm ${task} -p ${project.name}\` removes it`;
2006
+ if (error instanceof KnownError || error instanceof $8.ShellError)
2007
+ throw new WtError(`${failureText(error)}
2008
+ ${way}`);
2009
+ console.error(`wt: ${way}`);
2010
+ throw error;
2011
+ }
2012
+ console.log(`wt: created ${worktree.dir} on ${checkout}`);
2013
+ for (const url of urlsOf(worktree))
2014
+ console.log(` ${url}`);
2015
+ console.log(` wt up ${task}`);
2016
+ }
2017
+ async function syncTask(task, options) {
2018
+ const worktree = await locateWorktree(process.cwd(), task, options.project);
2019
+ await syncWorktree(worktree);
2020
+ console.log(`wt: synced ${worktree.id}`);
2021
+ }
2022
+ async function refuseLosingWork(worktree, force) {
2023
+ if (force || !existsSync10(worktree.dir))
2024
+ return;
2025
+ const dirty = await dirtyRepos(worktree);
2026
+ if (dirty.length)
2027
+ throw new WtError(`uncommitted changes in ${dirty.join(", ")}, commit them or pass --force`);
2028
+ const unreachable = await unreachableCommits(worktree);
2029
+ if (unreachable.length)
2030
+ throw new WtError(`commits on no branch in ${unreachable.join(", ")} would be lost, \`git switch -c <branch>\` there or pass --force`);
2031
+ }
2032
+ async function assertRemovable(task, options) {
2033
+ const worktree = await locateWorktree(process.cwd(), task, options.project);
2034
+ if (!existsSync10(worktree.dir) && !Object.values(worktree.files).some((file) => existsSync10(file)) && !await isRegistered(worktree))
2035
+ throw new WtError(`no worktree ${worktree.task} of ${worktree.project.name}, nothing removed`);
2036
+ await refuseLosingWork(worktree, options.force === true);
2037
+ }
2038
+ async function removeTask(task, options) {
2039
+ const worktree = await locateWorktree(process.cwd(), task, options.project);
2040
+ process.chdir(worktree.project.root);
2041
+ const anonymous = await anonymousVolumes(worktree);
2042
+ await refuseLosingWork(worktree, options.force === true);
2043
+ if (existsSync10(worktree.dir) || await hasContainers(worktree.id))
2044
+ await stackDown(worktree);
2045
+ await removeVolumes(worktree, anonymous);
2046
+ for (const file of Object.values(worktree.files))
2047
+ rmSync4(file, { force: true });
2048
+ await forgetTestDatabases(worktree);
2049
+ await removeWorktrees(worktree);
2050
+ await afterRemove(worktree);
2051
+ console.log(`wt: removed ${worktree.id}, its branches are kept`);
2052
+ }
2053
+ async function printUrls(task, options) {
2054
+ for (const url of urlsOf(await locateWorktree(process.cwd(), task, options.project)))
2055
+ console.log(url);
2056
+ }
2057
+ async function upTask(worktree) {
2058
+ assertWorktreeExists(worktree);
2059
+ await stackUp(worktree);
2060
+ }
2061
+ async function downTask(worktree) {
2062
+ assertWorktreeExists(worktree);
2063
+ await stackDown(worktree);
2064
+ }
2065
+ async function printPath(task, options) {
2066
+ const { project } = await locate(process.cwd(), options.project);
2067
+ if (task === undefined || task === "main")
2068
+ return console.log(project.root);
2069
+ const worktree = worktreeOf(project, task);
2070
+ assertWorktreeExists(worktree);
2071
+ console.log(worktree.dir);
2072
+ }
2073
+ async function printTasks(options) {
2074
+ try {
2075
+ console.log(listTasks((await locate(process.cwd(), options.project)).project).join(`
2076
+ `));
2077
+ } catch {}
2078
+ }
2079
+
2080
+ // src/init.ts
2081
+ import { existsSync as existsSync11, mkdirSync as mkdirSync8, readdirSync as readdirSync5, statSync as statSync2, writeFileSync as writeFileSync5 } from "fs";
2082
+ import { homedir as homedir4 } from "os";
2083
+ import { basename as basename4, join as join12, relative } from "path";
2084
+ var CERT_PATH = /cert/i;
2085
+ var HTTP_TARGET = /^(?:https?:\/\/)?([\w.-]+):(\d+)$/;
2086
+ var PASSTHROUGH_TARGET = /^([\w.-]+):(\d+)$/;
2087
+ async function ignoredPaths(repo, paths) {
2088
+ if (!paths.length)
2089
+ return [];
2090
+ const matched = new Set((await git2(repo, "check-ignore", ...paths)).out.split(`
2091
+ `));
2092
+ return paths.filter((path) => matched.has(path));
2093
+ }
2094
+ function mountedPaths(config) {
2095
+ const binds = Object.values(config.services).flatMap((service) => (service.volumes ?? []).filter((v) => v.type === "bind").map((v) => v.source));
2096
+ const devices = Object.values(config.volumes ?? {}).flatMap((volume) => volume.driver_opts?.device ?? []);
2097
+ return [...new Set([...binds, ...devices])];
2098
+ }
2099
+ async function findRoutes(config, name, network) {
2100
+ const serviceOf = (target) => Object.entries(config.services).find(([service, settings]) => settings.container_name === target || `${config.name}-${service}-1` === target || settings.networks?.[network]?.aliases?.includes(target))?.[0];
2101
+ const routes = [];
2102
+ for (const { host, to, passthrough } of await proxyHostList()) {
2103
+ const [, target = "", port = ""] = (passthrough ? PASSTHROUGH_TARGET : HTTP_TARGET).exec(to) ?? [];
2104
+ const service = serviceOf(target);
2105
+ if (target === "host" && Number(port) === stringToPort(name))
2106
+ routes.push({ host, to: "client" });
2107
+ else if (service !== undefined)
2108
+ routes.push({ host, to: `${service}:${Number(port)}`, ...passthrough ? { passthrough } : {} });
2109
+ }
2110
+ return routes;
2111
+ }
2112
+ async function secretsToCopy(root, repos) {
2113
+ const perBase = await Promise.all([".", ...repos].map(async (base) => {
2114
+ const envFiles = readdirSync5(join12(root, base)).filter((entry) => (entry.startsWith(".env") || entry === ".nuxtrc") && statSync2(join12(root, base, entry)).isFile());
2115
+ const jwt = base !== "." && existsSync11(join12(root, base, "config", "jwt")) ? [join12(base, "config", "jwt")] : [];
2116
+ return [...(await ignoredPaths(join12(root, base), envFiles)).map((entry) => join12(base, entry)), ...jwt];
2117
+ }));
2118
+ return perBase.flat();
2119
+ }
2120
+ async function draftFor(dir, given) {
2121
+ const top = await git2(dir, "rev-parse", "--show-toplevel");
2122
+ if (!top.ok)
2123
+ throw new WtError(`${dir} is not inside a git repository`);
2124
+ const root = top.out;
2125
+ const config = await composeConfig(root);
2126
+ const name = given ?? basename4(root);
2127
+ const mounted = mountedPaths(config).filter((path) => path.startsWith(`${root}/`)).map((path) => relative(root, path));
2128
+ const repos = readdirSync5(root).filter((entry) => existsSync11(join12(root, entry, ".git")) && mounted.some((path) => path === entry || path.startsWith(`${entry}/`)));
2129
+ const inRepo = (path) => repos.some((repo) => path === repo || path.startsWith(`${repo}/`));
2130
+ const volumes = Object.entries(config.volumes ?? {}).filter(([, volume]) => (volume.driver_opts?.device ?? "") === "");
2131
+ const [secrets, ignoredMounts, volumesExist] = await Promise.all([
2132
+ secretsToCopy(root, repos),
2133
+ ignoredPaths(root, mounted.filter((path) => !inRepo(path) && existsSync11(join12(root, path)))),
2134
+ Promise.all(volumes.map(async ([key, volume]) => volumeExists(volume.name ?? `${config.name}_${key}`)))
2135
+ ]);
2136
+ const routes = await findRoutes(config, name, (await wtConfig()).proxyNetwork);
2137
+ const certs = routes.some((route) => route.passthrough) ? mounted.find((path) => CERT_PATH.test(path)) : undefined;
2138
+ return {
2139
+ name,
2140
+ root: root.replace(homedir4(), "~"),
2141
+ repos,
2142
+ copy: [...secrets, ...ignoredMounts.filter((path) => CERT_PATH.test(path))],
2143
+ clone: [...ignoredMounts.filter((path) => !CERT_PATH.test(path)), ...volumes.filter((_, index) => volumesExist[index]).map(([key]) => key)],
2144
+ skip: Object.entries(config.services).filter(([, service]) => service.network_mode === "host").map(([service]) => service),
2145
+ ...certs !== undefined && { certs },
2146
+ routes
2147
+ };
2148
+ }
2149
+ var list = (values) => `[${values.map((value) => `'${value}'`).join(", ")}]`;
2150
+ function render(draft) {
2151
+ const routes = draft.routes.map((route) => ` { host: '${route.host}', to: '${route.to}'${route.passthrough ? ", passthrough: true" : ""} },`);
2152
+ return [
2153
+ `import type { ProjectConfig } from '@kaynooo/cli-wt'`,
2154
+ "",
2155
+ "// Drafted by `wt init`: check every list against the stack before the first `wt add`.",
2156
+ "export default {",
2157
+ ` root: '${draft.root}',`,
2158
+ ` repos: ${list(draft.repos)},`,
2159
+ ` copy: ${list(draft.copy)},`,
2160
+ ` clone: ${list(draft.clone)},`,
2161
+ ...draft.skip.length ? [` skip: ${list(draft.skip)},`] : [],
2162
+ ...draft.certs !== undefined ? [` certs: '${draft.certs}',`] : [],
2163
+ " setup: [],",
2164
+ " routes: [",
2165
+ ...routes,
2166
+ " ],",
2167
+ "} satisfies ProjectConfig",
2168
+ ""
2169
+ ].join(`
2170
+ `);
2171
+ }
2172
+ async function initProject(dir, options) {
2173
+ const draft = await draftFor(dir, options.name);
2174
+ const content = render(draft);
2175
+ if (options.print)
2176
+ return console.log(content);
2177
+ const { manifests } = await wtConfig();
2178
+ const file = join12(manifests, `${draft.name}.ts`);
2179
+ mkdirSync8(manifests, { recursive: true });
2180
+ if (existsSync11(file))
2181
+ throw new WtError(`${file} already exists, compare with \`wt init --print\``);
2182
+ writeFileSync5(file, content);
2183
+ console.log(`wt: drafted ${file}, review it before \`wt add\``);
2184
+ }
2185
+
2186
+ // src/jobs.ts
2187
+ import { closeSync, fstatSync, mkdirSync as mkdirSync9, openSync, readdirSync as readdirSync6, readFileSync as readFileSync8, readSync, renameSync as renameSync2, rmSync as rmSync5, statSync as statSync3, writeFileSync as writeFileSync6 } from "fs";
2188
+ import { join as join13 } from "path";
2189
+ var {$: $9 } = globalThis.Bun;
2190
+ var HELD_ENV = "WT_JOBS_HELD";
2191
+ var STARTING_MS = 30000;
2192
+ var TAKEOVER_MS = 5000;
2193
+ var TAIL_BYTES = 4096;
2194
+ var DOING = { up: "coming up", down: "stopping", add: "being made", sync: "syncing", rm: "being removed" };
2195
+ var DONE = { up: ["is up", "Its stack came up"], add: ["is ready", "The worktree is made, its stack still down"] };
2196
+ function writeJob(file, job) {
2197
+ const partial = `${file}.${process.pid}.tmp`;
2198
+ writeFileSync6(partial, JSON.stringify(job));
2199
+ renameSync2(partial, file);
2200
+ }
2201
+ function readJob(file) {
2202
+ try {
2203
+ return JSON.parse(readFileSync8(file, "utf8"));
2204
+ } catch {
2205
+ return;
2206
+ }
2207
+ }
2208
+ function doing(table, job) {
2209
+ const words = job === undefined ? "busy" : table[job.verb] ?? `busy with ${job.verb}`;
2210
+ return job?.service !== undefined ? `${words} ${job.service}` : words;
2211
+ }
2212
+ function held(lock, now = Date.now()) {
2213
+ try {
2214
+ const pid = Number(readFileSync8(lock, "utf8").trim());
2215
+ const writtenAt = statSync3(lock, { throwIfNoEntry: false })?.mtimeMs ?? 0;
2216
+ if (writtenAt < bootTime())
2217
+ return false;
2218
+ return pid ? alive(pid) : now - writtenAt < STARTING_MS;
2219
+ } catch {
2220
+ return false;
2221
+ }
2222
+ }
2223
+ function takeOver(lock) {
2224
+ const guard = `${lock}.takeover`;
2225
+ try {
2226
+ writeFileSync6(guard, "", { flag: "wx" });
2227
+ } catch (error) {
2228
+ if (error.code !== "EEXIST")
2229
+ throw error;
2230
+ if (Date.now() - (statSync3(guard, { throwIfNoEntry: false })?.mtimeMs ?? 0) < TAKEOVER_MS)
2231
+ return false;
2232
+ rmSync5(guard, { force: true });
2233
+ return takeOver(lock);
2234
+ }
2235
+ try {
2236
+ if (!held(lock))
2237
+ rmSync5(lock, { force: true });
2238
+ return true;
2239
+ } finally {
2240
+ rmSync5(guard, { force: true });
2241
+ }
2242
+ }
2243
+ var heldHere = () => (process.env[HELD_ENV] ?? "").split(`
2244
+ `).filter(Boolean);
2245
+ var heldEntry = (lock) => `${process.pid} ${lock}`;
2246
+ function stillHeldBy(entry) {
2247
+ const space = entry.indexOf(" ");
2248
+ const lock = entry.slice(space + 1);
2249
+ try {
2250
+ return readFileSync8(lock, "utf8").trim() === entry.slice(0, space) && held(lock);
2251
+ } catch {
2252
+ return false;
2253
+ }
2254
+ }
2255
+ function logTail(file, lines = 5) {
2256
+ try {
2257
+ const fd = openSync(file, "r");
2258
+ try {
2259
+ const size = fstatSync(fd).size;
2260
+ const buffer = Buffer.alloc(Math.min(size, TAIL_BYTES));
2261
+ readSync(fd, buffer, 0, buffer.length, size - buffer.length);
2262
+ return buffer.toString("utf8").trim().split(`
2263
+ `).slice(-lines).join(`
2264
+ `);
2265
+ } finally {
2266
+ closeSync(fd);
2267
+ }
2268
+ } catch {
2269
+ return "";
2270
+ }
2271
+ }
2272
+ async function notify(app, title, body, critical = false) {
2273
+ if (Bun.which("notify-send") !== null)
2274
+ await $9`notify-send -a ${app} ${critical ? ["-u", "critical"] : []} ${title} ${body}`.quiet().nothrow();
2275
+ }
2276
+
2277
+ class Jobs {
2278
+ dir;
2279
+ app;
2280
+ env;
2281
+ doing;
2282
+ done;
2283
+ constructor({ dir, app, words = {} }) {
2284
+ this.dir = dir;
2285
+ this.app = app;
2286
+ this.env = `${app.toUpperCase()}_JOB`;
2287
+ this.doing = { ...DOING, ...words.doing };
2288
+ this.done = { ...DONE, ...words.done };
2289
+ }
2290
+ paths(slug) {
2291
+ return { job: join13(this.dir, `${slug}.json`), lock: join13(this.dir, `${slug}.lock`), log: join13(this.dir, `${slug}.log`) };
2292
+ }
2293
+ holds(stack) {
2294
+ const { lock } = this.paths(stack.slug);
2295
+ return heldHere().some((entry) => entry.endsWith(` ${lock}`) && stillHeldBy(entry));
2296
+ }
2297
+ claim(stack, verb, detached, service) {
2298
+ const { job: jobFile, lock, log } = this.paths(stack.slug);
2299
+ mkdirSync9(this.dir, { recursive: true });
2300
+ for (let attempt = 0;; attempt++) {
2301
+ try {
2302
+ writeFileSync6(lock, detached ? "" : String(process.pid), { flag: "wx" });
2303
+ break;
2304
+ } catch (error) {
2305
+ if (error.code !== "EEXIST")
2306
+ throw error;
2307
+ if (attempt > 0 || held(lock) || !takeOver(lock)) {
2308
+ const running = readJob(jobFile);
2309
+ throw new KnownError(`${stack.ref} is already ${doing(this.doing, running)}${running !== undefined && running.log !== "" ? `, see ${running.log}` : ""}`);
2310
+ }
2311
+ }
2312
+ }
2313
+ const job = { ref: stack.ref, verb, ...service !== undefined && { service }, pid: detached ? null : process.pid, startedAt: Date.now(), log: detached ? log : "" };
2314
+ writeJob(jobFile, job);
2315
+ return job;
2316
+ }
2317
+ adopt(stack) {
2318
+ const { job: jobFile, lock } = this.paths(stack.slug);
2319
+ const job = readJob(jobFile);
2320
+ if (!job)
2321
+ throw new KnownError(`no job claimed for ${stack.slug}`);
2322
+ job.pid = process.pid;
2323
+ writeFileSync6(lock, String(process.pid));
2324
+ writeJob(jobFile, job);
2325
+ return job;
2326
+ }
2327
+ finish(stack, job, code) {
2328
+ const { job: jobFile, lock } = this.paths(stack.slug);
2329
+ writeJob(jobFile, { ...job, endedAt: Date.now(), code });
2330
+ rmSync5(lock, { force: true });
2331
+ }
2332
+ states() {
2333
+ const states = new Map;
2334
+ let files;
2335
+ try {
2336
+ files = readdirSync6(this.dir).filter((file) => file.endsWith(".json"));
2337
+ } catch {
2338
+ return states;
2339
+ }
2340
+ for (const file of files) {
2341
+ const slug = file.slice(0, -".json".length);
2342
+ const job = readJob(join13(this.dir, file));
2343
+ if (!job)
2344
+ continue;
2345
+ if (job.endedAt !== undefined)
2346
+ states.set(slug, { last: job });
2347
+ else if (held(this.paths(slug).lock))
2348
+ states.set(slug, { running: job });
2349
+ else
2350
+ states.set(slug, { last: { ...job, code: null, endedAt: statSync3(join13(this.dir, file), { throwIfNoEntry: false })?.mtimeMs ?? job.startedAt } });
2351
+ }
2352
+ return states;
2353
+ }
2354
+ forget(stack) {
2355
+ for (const file of Object.values(this.paths(stack.slug)))
2356
+ rmSync5(file, { force: true });
2357
+ }
2358
+ async run(stack, verb, work, service) {
2359
+ if (this.holds(stack))
2360
+ return attempt(async () => work(false));
2361
+ const detached = process.env[this.env] === stack.slug;
2362
+ const job = detached ? this.adopt(stack) : this.claim(stack, verb, false, service);
2363
+ const before = process.env[HELD_ENV];
2364
+ delete process.env[this.env];
2365
+ process.env[HELD_ENV] = [...heldHere(), heldEntry(this.paths(stack.slug).lock)].join(`
2366
+ `);
2367
+ let code = 1;
2368
+ try {
2369
+ code = await attempt(async () => work(detached));
2370
+ } finally {
2371
+ if (before === undefined)
2372
+ delete process.env[HELD_ENV];
2373
+ else
2374
+ process.env[HELD_ENV] = before;
2375
+ this.finish(stack, job, code);
2376
+ }
2377
+ if (detached)
2378
+ await this.notifyEnd(stack, job, code);
2379
+ return code;
2380
+ }
2381
+ async failDetached(message) {
2382
+ const slug = process.env[this.env];
2383
+ if (slug === undefined || slug === "")
2384
+ return;
2385
+ delete process.env[this.env];
2386
+ const job = readJob(this.paths(slug).job);
2387
+ if (!job || job.endedAt !== undefined)
2388
+ return;
2389
+ this.finish({ slug }, job, 1);
2390
+ await notify(this.app, `${this.what(job)} failed`, message, true);
2391
+ }
2392
+ async guarded(action, bg) {
2393
+ try {
2394
+ return await action() ?? 0;
2395
+ } catch (error) {
2396
+ const message = error instanceof Error ? error.message : String(error);
2397
+ await this.failDetached(message);
2398
+ if (bg !== undefined)
2399
+ await this.notifyRefused(bg, message);
2400
+ return failKnown(error);
2401
+ }
2402
+ }
2403
+ async notifyRefused(what, message) {
2404
+ await notify(this.app, `${what} not started`, message, true);
2405
+ }
2406
+ detach(stack, verb, argv, service) {
2407
+ const job = this.claim(stack, verb, true, service);
2408
+ const out = openSync(job.log, "w");
2409
+ try {
2410
+ Bun.spawn([process.execPath, "--no-env-file", ...argv], { stdio: ["ignore", out, out], env: { ...process.env, [this.env]: stack.slug }, detached: true }).unref();
2411
+ } catch (error) {
2412
+ this.finish(stack, job, 1);
2413
+ throw error;
2414
+ } finally {
2415
+ closeSync(out);
2416
+ }
2417
+ return job;
2418
+ }
2419
+ what(job) {
2420
+ return [this.app, job.verb, job.ref, ...job.service !== undefined ? [job.service] : []].join(" ");
2421
+ }
2422
+ async notifyEnd(stack, job, code) {
2423
+ const done = job.service !== undefined ? undefined : this.done[job.verb];
2424
+ if (code === 0) {
2425
+ if (done)
2426
+ await notify(this.app, `${stack.ref} ${done[0]}`, done[1]);
2427
+ return;
2428
+ }
2429
+ await notify(this.app, `${this.what(job)} failed`, logTail(job.log) || `see ${job.log}`, true);
2430
+ }
2431
+ }
2432
+ async function attempt(work) {
2433
+ try {
2434
+ await work();
2435
+ return 0;
2436
+ } catch (error) {
2437
+ console.error(error instanceof KnownError ? `error: ${error.message}` : error);
2438
+ return 1;
2439
+ }
2440
+ }
2441
+
2442
+ // src/list.ts
2443
+ import { basename as basename5, join as join14 } from "path";
2444
+ var UNSAFE_IN_SESSION = /[.:\s/]/g;
2445
+ var sessionOf = (name) => name.replace(UNSAFE_IN_SESSION, "-");
2446
+ async function projectsToList(options) {
2447
+ let here = null;
2448
+ try {
2449
+ here = (await locate(process.cwd(), options.project)).project;
2450
+ } catch {}
2451
+ const everywhere = options.all === true || !here && !options.json;
2452
+ return { here, projects: everywhere ? await loadProjects() : [here].filter((project) => project !== null) };
2453
+ }
2454
+ function changedFiles(outputs) {
2455
+ return outputs.flatMap((out) => out.split(`
2456
+ `)).filter((line) => line.trim() !== "").length;
2457
+ }
2458
+ async function dirtyCount(dir, repos) {
2459
+ const statuses = await Promise.all([".", ...repos].map(async (repo) => git2(join14(dir, repo), "--no-optional-locks", "status", "--porcelain")));
2460
+ return changedFiles(statuses.filter((status) => status.ok).map((status) => status.out));
2461
+ }
2462
+ async function checkoutsOf(project, running) {
2463
+ const branchDir = project.repos[0] ?? ".";
2464
+ const mainHost = project.routes.find((route) => !route.host.startsWith("*."))?.host;
2465
+ const main = { id: basename5(project.root), task: "main", dir: project.root, url: mainHost !== undefined ? `https://${mainHost}` : "" };
2466
+ const worktrees = listTasks(project).map((task) => {
2467
+ const worktree = worktreeOf(project, task);
2468
+ return { id: worktree.id, task, dir: worktree.dir, url: urlsOf(worktree)[0] ?? "" };
2469
+ });
2470
+ return Promise.all([main, ...worktrees].map(async ({ id, task, dir, url }) => ({
2471
+ project: project.name,
2472
+ task,
2473
+ dir,
2474
+ branch: await currentBranch(join14(dir, branchDir)),
2475
+ url,
2476
+ running: running.has(id),
2477
+ dirty: await dirtyCount(dir, project.repos),
2478
+ unbranched: task === "main" ? 0 : await unreachableCount(dir, project.repos),
2479
+ session: sessionOf(task === "main" ? basename5(dir) : id)
2480
+ })));
2481
+ }
2482
+ async function listWorktrees(options) {
2483
+ const [running, { here, projects }] = await Promise.all([runningProjects(), projectsToList(options)]);
2484
+ const checkouts = (await Promise.all(projects.map(async (project) => checkoutsOf(project, running)))).flat();
2485
+ if (options.json) {
2486
+ console.log(JSON.stringify({ project: here?.name ?? null, checkouts }));
2487
+ return;
2488
+ }
2489
+ const rows = checkouts.map((checkout) => [checkout.running ? "*" : " ", checkout.project, checkout.task, checkout.branch, checkout.url, [checkout.dirty ? `${checkout.dirty} changed` : "", checkout.unbranched ? `${checkout.unbranched} on no branch` : ""].filter(Boolean).join(", ")]);
2490
+ const widths = rows[0]?.map((_, column) => Math.max(...rows.map((row) => row[column].length))) ?? [];
2491
+ for (const row of rows)
2492
+ console.log(row.map((cell, column) => cell.padEnd(widths[column])).join(" ").trimEnd());
2493
+ }
2494
+
2495
+ // src/shell.ts
2496
+ var FISH = `function wt --description 'git worktrees of a compose project, each with its own stack'
2497
+ switch "$argv[1]"
2498
+ case cd
2499
+ set -l dir (command wt path $argv[2..-1]); or return
2500
+ builtin cd $dir
2501
+ case rm
2502
+ set -l main (command wt path 2>/dev/null)
2503
+ command wt $argv
2504
+ set -l code $status
2505
+ test -d $PWD; or builtin cd $main
2506
+ return $code
2507
+ case '*'
2508
+ command wt $argv
2509
+ end
2510
+ end
2511
+ command wt --completions fish | source
2512
+ complete -c wt -n __fish_use_subcommand -a cd -d 'go to a worktree, or main'
2513
+ complete -c wt -n '__fish_seen_subcommand_from cd' -f -a '(command wt tasks) main'`;
2514
+ function shellWrapper(shell) {
2515
+ if (shell !== "fish")
2516
+ throw new KnownError(`no wrapper for ${shell ?? "that shell"} yet, only fish`);
2517
+ return FISH;
2518
+ }
2519
+
2520
+ // src/cli.ts
2521
+ async function jobs() {
2522
+ return new Jobs({ dir: (await wtConfig()).jobs, app: "wt" });
2523
+ }
2524
+ async function guarded(action) {
2525
+ try {
2526
+ return await (await jobs()).guarded(action);
2527
+ } catch (error) {
2528
+ return failKnown(error);
2529
+ }
2530
+ }
2531
+ async function projectNames() {
2532
+ return (await loadProjects()).map((project) => project.name);
2533
+ }
2534
+ async function taskNames() {
2535
+ try {
2536
+ return listTasks((await locate(process11.cwd())).project);
2537
+ } catch {
2538
+ return [];
2539
+ }
2540
+ }
2541
+ var TASK = { "[task]": taskNames, "<task>": taskNames };
2542
+ var PROJECT_OPTION = { type: "string", short: "p", candidates: projectNames, description: "manifest to use instead of the one the current directory belongs to" };
2543
+ var BG_OPTION = { type: "boolean", description: "run it away from any terminal, its output in the worktree's job log, a notification saying how it went" };
2544
+ async function asWorktreeJob(verb, task, options, argv, work) {
2545
+ const { project } = await locate(process11.cwd(), options.project);
2546
+ const ref = `${project.name}/${task}`;
2547
+ const stack = { ref, slug: slugOf(ref) };
2548
+ const queue = await jobs();
2549
+ if (!options.bg) {
2550
+ const code = await queue.run(stack, verb, work);
2551
+ if (verb === "rm" && code === 0)
2552
+ queue.forget(stack);
2553
+ return code;
2554
+ }
2555
+ try {
2556
+ const job = queue.detach(stack, verb, [import.meta.path, ...argv, "-p", project.name]);
2557
+ console.log(`wt: ${verb} ${ref} runs out of sight, its output in ${job.log}`);
2558
+ } catch (error) {
2559
+ await queue.notifyRefused(`wt ${verb} ${ref}`, error instanceof Error ? error.message : String(error));
2560
+ throw error;
2561
+ }
2562
+ return 0;
2563
+ }
2564
+ var ADD_USAGE = `wt add <task> [branch] [-p <name>] [--bg]
2565
+
2566
+ Creates a worktree, copies its files and data from main, and routes its subdomains. The task is a lowercase name, also the subdomain label; the branch defaults to wt/<task>.
2567
+
2568
+ Exits 0 once the worktree is ready, 1 when it cannot be made or provisioned, 2 on a usage error.`;
2569
+ var SYNC_USAGE = `wt sync [task] [-p <name>]
2570
+
2571
+ Provisions a worktree again after a manifest change: missing copies and clones, compose override, certificates and routes. The task defaults to the worktree the current directory is in.
2572
+
2573
+ Exits 0 once it is provisioned, 1 when a step fails, 2 on a usage error.`;
2574
+ var RM_USAGE = `wt rm <task> [-f] [-p <name>] [--bg]
2575
+
2576
+ Stops a worktree stack and deletes its checkouts, volumes, certificates and routes, keeping its branches.
2577
+
2578
+ Exits 0 once it is gone, 1 when uncommitted changes or lost commits refuse it (unless --force) or a step fails, 2 on a usage error.`;
2579
+ var UP_USAGE = `wt up [task] [-p <name>] [--bg]
2580
+
2581
+ Starts a worktree stack: \`docker compose up -d --build\` in the worktree then the manifest's setup the first time, or the config's runner.up. The task defaults to the worktree the current directory is in.
2582
+
2583
+ Exits 0 once the stack is up, 1 when a command fails, 2 on a usage error.`;
2584
+ var DOWN_USAGE = `wt down [task] [-p <name>] [--bg]
2585
+
2586
+ Stops a worktree stack: \`docker compose down\` in the worktree, or the config's runner.down. The task defaults to the worktree the current directory is in.
2587
+
2588
+ Exits 0 once the stack is down, 1 when a command fails, 2 on a usage error.`;
2589
+ var SHELL_USAGE = `wt shell <shell>
2590
+
2591
+ Prints the shell function that lets \`wt cd\` change directory and \`wt rm\` leave the folder it removes: \`wt shell fish | source\` in config.fish.
2592
+
2593
+ Exits 0 when it printed the wrapper, 1 for a shell it has none for, 2 on a usage error.`;
2594
+ var LS_USAGE = `wt ls [-a] [-p <name>] [--json]
2595
+
2596
+ Lists main and the worktrees of the current project, or of every project, with their changed files.
2597
+
2598
+ Exits 0 when it listed them, 1 when a manifest does not load, 2 on a usage error.`;
2599
+ var PATH_USAGE = `wt path [task] [-p <name>]
2600
+
2601
+ Prints the directory of a worktree, or of main when no task is given.
2602
+
2603
+ Exits 0 when it printed it, 1 when there is no such worktree or project, 2 on a usage error.`;
2604
+ var INIT_USAGE = `wt init [dir] [--name <name>] [--print]
2605
+
2606
+ Drafts a manifest for the project checked out in a directory, the current one by default, into the config's manifests folder.
2607
+
2608
+ Exits 0 once it is written or printed, 1 when the folder holds no compose project, 2 on a usage error.`;
2609
+ var RUN_USAGE = `wt run <task> [-p <name>] -- <command>...
2610
+
2611
+ Runs a command of a worktree in a throwaway container of its run service, against a test database of its own, provisioned on first use.
2612
+
2613
+ Exits with the command's code, 1 when the test database cannot be provisioned, 2 on a usage error.`;
2614
+ var HEAVY_USAGE = `wt heavy -- <command>...
2615
+
2616
+ Runs a heavy command (a full suite, e2e) once those queued before it, from any session, are done.
2617
+
2618
+ Exits with the command's code, 2 on a usage error.`;
2619
+ var URL_USAGE = `wt url [task] [-p <name>]
2620
+
2621
+ Prints the URLs of a worktree.
2622
+
2623
+ Exits 0 when it printed it, 1 when there is no such worktree or project, 2 on a usage error.`;
2624
+ var TASKS_USAGE = `wt tasks [-p <name>]
2625
+
2626
+ Prints the worktree names of the project, one per line.
2627
+
2628
+ Exits 0 when it printed them, 1 when there is no such project, 2 on a usage error.`;
2629
+ process11.exitCode = await runCli({
2630
+ name: "wt",
2631
+ about: "git worktrees of a compose project, each with its own stack, data and <task>.<host> subdomains beside main",
2632
+ replaces: "a second clone, port juggling and a shared database to try a branch",
2633
+ examples: [["wt add planning", "a worktree on wt/planning with its own stack"], ["wt up planning", "start it"], ["wt rm planning", "stop and delete it, keeping its branches"]],
2634
+ commands: {
2635
+ add: {
2636
+ summary: "create a worktree, copy its files and data from main, and route its subdomains",
2637
+ run: async (args) => {
2638
+ const { values, positionals: [task, branch] } = parse(args, ADD_USAGE, { project: PROJECT_OPTION, bg: BG_OPTION }, { positionals: ["<task>", "[branch]"] });
2639
+ return guarded(async () => asWorktreeJob("add", task, values, ["add", task, ...branch === undefined ? [] : [branch]], async () => addTask(task, branch, values)));
2640
+ }
2641
+ },
2642
+ sync: {
2643
+ summary: "provision a worktree again after a manifest change",
2644
+ run: async (args) => {
2645
+ const { values, positionals: [task] } = parse(args, SYNC_USAGE, { project: PROJECT_OPTION }, { positionals: ["[task]"], candidates: TASK });
2646
+ return guarded(async () => {
2647
+ const { task: name } = await locateWorktree(process11.cwd(), task, values.project);
2648
+ return asWorktreeJob("sync", name, values, ["sync", name], async () => syncTask(name, values));
2649
+ });
2650
+ }
2651
+ },
2652
+ rm: {
2653
+ summary: "stop a worktree stack and delete its checkouts, volumes, certificates and routes, keeping its branches",
2654
+ run: async (args) => {
2655
+ const { values, positionals: [task] } = parse(args, RM_USAGE, {
2656
+ project: PROJECT_OPTION,
2657
+ force: { type: "boolean", short: "f", description: "remove even with uncommitted changes or commits on no branch" },
2658
+ bg: BG_OPTION
2659
+ }, { positionals: ["<task>"], candidates: TASK });
2660
+ return guarded(async () => {
2661
+ await assertRemovable(task, values);
2662
+ return asWorktreeJob("rm", task, values, ["rm", task, ...values.force ? ["--force"] : []], async () => removeTask(task, values));
2663
+ });
2664
+ }
2665
+ },
2666
+ up: {
2667
+ summary: "start a worktree stack",
2668
+ run: async (args) => {
2669
+ const { values, positionals: [task] } = parse(args, UP_USAGE, { project: PROJECT_OPTION, bg: BG_OPTION }, { positionals: ["[task]"], candidates: TASK });
2670
+ return guarded(async () => {
2671
+ const worktree = await locateWorktree(process11.cwd(), task, values.project);
2672
+ return asWorktreeJob("up", worktree.task, values, ["up", worktree.task], async () => upTask(worktree));
2673
+ });
2674
+ }
2675
+ },
2676
+ down: {
2677
+ summary: "stop a worktree stack",
2678
+ run: async (args) => {
2679
+ const { values, positionals: [task] } = parse(args, DOWN_USAGE, { project: PROJECT_OPTION, bg: BG_OPTION }, { positionals: ["[task]"], candidates: TASK });
2680
+ return guarded(async () => {
2681
+ const worktree = await locateWorktree(process11.cwd(), task, values.project);
2682
+ return asWorktreeJob("down", worktree.task, values, ["down", worktree.task], async () => downTask(worktree));
2683
+ });
2684
+ }
2685
+ },
2686
+ ls: {
2687
+ summary: "list main and the worktrees of the current project, or of every project",
2688
+ run: async (args) => {
2689
+ const { values } = parse(args, LS_USAGE, {
2690
+ project: PROJECT_OPTION,
2691
+ all: { type: "boolean", short: "a", description: "every project, even from inside one" },
2692
+ json: { type: "boolean", description: "print { project, checkouts }, project being the one the directory is in, null outside every one" }
2693
+ }, { positionals: [] });
2694
+ return guarded(async () => listWorktrees(values));
2695
+ }
2696
+ },
2697
+ path: {
2698
+ summary: "print the directory of a worktree, or of main",
2699
+ run: async (args) => {
2700
+ const { values, positionals: [task] } = parse(args, PATH_USAGE, { project: PROJECT_OPTION }, { positionals: ["[task]"], candidates: TASK });
2701
+ return guarded(async () => printPath(task, values));
2702
+ }
2703
+ },
2704
+ init: {
2705
+ summary: "draft a manifest for the project checked out in a directory",
2706
+ run: async (args) => {
2707
+ const { values, positionals: [dir] } = parse(args, INIT_USAGE, {
2708
+ name: { type: "string", description: "the manifest's name, also hashed into the dev server port (the checkout's folder name)" },
2709
+ print: { type: "boolean", description: "print the draft instead of writing it" }
2710
+ }, { positionals: ["[dir]"] });
2711
+ return guarded(async () => initProject(dir ?? process11.cwd(), values));
2712
+ }
2713
+ },
2714
+ run: {
2715
+ summary: "run a command of a worktree in a throwaway container of its run service, against a test database of its own",
2716
+ run: async (args) => {
2717
+ const { values, positionals: [task], rest } = parse(args, RUN_USAGE, { project: PROJECT_OPTION }, {
2718
+ positionals: ["<task>"],
2719
+ candidates: TASK,
2720
+ rest: true,
2721
+ examples: [["wt run planning -- vendor/bin/phpunit --filter Foo", "a test run in the planning worktree"]]
2722
+ });
2723
+ if (rest === undefined || rest.length === 0)
2724
+ badUsage("give the command after --");
2725
+ return guarded(async () => runTask(task, rest, values.project));
2726
+ }
2727
+ },
2728
+ heavy: {
2729
+ summary: "run a heavy command once those queued before it, from any session, are done",
2730
+ run: async (args) => {
2731
+ const { rest } = parse(args, HEAVY_USAGE, {}, {
2732
+ positionals: [],
2733
+ rest: true,
2734
+ examples: [["wt heavy -- wt run planning -- vendor/bin/phpunit", "a full suite, queued"]]
2735
+ });
2736
+ if (rest === undefined || rest.length === 0)
2737
+ badUsage("give the command after --");
2738
+ return guarded(async () => runHeavy(rest));
2739
+ }
2740
+ },
2741
+ shell: {
2742
+ summary: "print the shell function letting `wt cd` change directory",
2743
+ run: async (args) => {
2744
+ const { positionals: [shell] } = parse(args, SHELL_USAGE, {}, { positionals: ["<shell>"], candidates: { "<shell>": async () => Promise.resolve(["fish"]) } });
2745
+ return guarded(async () => {
2746
+ console.log(shellWrapper(shell));
2747
+ await Promise.resolve();
2748
+ });
2749
+ }
2750
+ },
2751
+ url: {
2752
+ summary: "print the URLs of a worktree",
2753
+ hidden: true,
2754
+ run: async (args) => {
2755
+ const { values, positionals: [task] } = parse(args, URL_USAGE, { project: PROJECT_OPTION }, { positionals: ["[task]"], candidates: TASK });
2756
+ return guarded(async () => printUrls(task, values));
2757
+ }
2758
+ },
2759
+ tasks: {
2760
+ summary: "print the worktree names of the project",
2761
+ hidden: true,
2762
+ run: async (args) => {
2763
+ const { values } = parse(args, TASKS_USAGE, { project: PROJECT_OPTION }, { positionals: [] });
2764
+ return guarded(async () => printTasks(values));
2765
+ }
2766
+ }
2767
+ }
2768
+ });