@residue/cli 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,4443 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+ var __create = Object.create;
4
+ var __getProtoOf = Object.getPrototypeOf;
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __toESM = (mod, isNodeMode, target) => {
10
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
11
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
12
+ for (let key of __getOwnPropNames(mod))
13
+ if (!__hasOwnProp.call(to, key))
14
+ __defProp(to, key, {
15
+ get: () => mod[key],
16
+ enumerable: true
17
+ });
18
+ return to;
19
+ };
20
+ var __moduleCache = /* @__PURE__ */ new WeakMap;
21
+ var __toCommonJS = (from) => {
22
+ var entry = __moduleCache.get(from), desc;
23
+ if (entry)
24
+ return entry;
25
+ entry = __defProp({}, "__esModule", { value: true });
26
+ if (from && typeof from === "object" || typeof from === "function")
27
+ __getOwnPropNames(from).map((key) => !__hasOwnProp.call(entry, key) && __defProp(entry, key, {
28
+ get: () => from[key],
29
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
30
+ }));
31
+ __moduleCache.set(from, entry);
32
+ return entry;
33
+ };
34
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
35
+ var __export = (target, all) => {
36
+ for (var name in all)
37
+ __defProp(target, name, {
38
+ get: all[name],
39
+ enumerable: true,
40
+ configurable: true,
41
+ set: (newValue) => all[name] = () => newValue
42
+ });
43
+ };
44
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
45
+ var __require = import.meta.require;
46
+
47
+ // ../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/error.js
48
+ var require_error = __commonJS((exports) => {
49
+ class CommanderError extends Error {
50
+ constructor(exitCode, code, message) {
51
+ super(message);
52
+ Error.captureStackTrace(this, this.constructor);
53
+ this.name = this.constructor.name;
54
+ this.code = code;
55
+ this.exitCode = exitCode;
56
+ this.nestedError = undefined;
57
+ }
58
+ }
59
+
60
+ class InvalidArgumentError extends CommanderError {
61
+ constructor(message) {
62
+ super(1, "commander.invalidArgument", message);
63
+ Error.captureStackTrace(this, this.constructor);
64
+ this.name = this.constructor.name;
65
+ }
66
+ }
67
+ exports.CommanderError = CommanderError;
68
+ exports.InvalidArgumentError = InvalidArgumentError;
69
+ });
70
+
71
+ // ../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/argument.js
72
+ var require_argument = __commonJS((exports) => {
73
+ var { InvalidArgumentError } = require_error();
74
+
75
+ class Argument {
76
+ constructor(name, description) {
77
+ this.description = description || "";
78
+ this.variadic = false;
79
+ this.parseArg = undefined;
80
+ this.defaultValue = undefined;
81
+ this.defaultValueDescription = undefined;
82
+ this.argChoices = undefined;
83
+ switch (name[0]) {
84
+ case "<":
85
+ this.required = true;
86
+ this._name = name.slice(1, -1);
87
+ break;
88
+ case "[":
89
+ this.required = false;
90
+ this._name = name.slice(1, -1);
91
+ break;
92
+ default:
93
+ this.required = true;
94
+ this._name = name;
95
+ break;
96
+ }
97
+ if (this._name.endsWith("...")) {
98
+ this.variadic = true;
99
+ this._name = this._name.slice(0, -3);
100
+ }
101
+ }
102
+ name() {
103
+ return this._name;
104
+ }
105
+ _collectValue(value, previous) {
106
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
107
+ return [value];
108
+ }
109
+ previous.push(value);
110
+ return previous;
111
+ }
112
+ default(value, description) {
113
+ this.defaultValue = value;
114
+ this.defaultValueDescription = description;
115
+ return this;
116
+ }
117
+ argParser(fn) {
118
+ this.parseArg = fn;
119
+ return this;
120
+ }
121
+ choices(values) {
122
+ this.argChoices = values.slice();
123
+ this.parseArg = (arg, previous) => {
124
+ if (!this.argChoices.includes(arg)) {
125
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
126
+ }
127
+ if (this.variadic) {
128
+ return this._collectValue(arg, previous);
129
+ }
130
+ return arg;
131
+ };
132
+ return this;
133
+ }
134
+ argRequired() {
135
+ this.required = true;
136
+ return this;
137
+ }
138
+ argOptional() {
139
+ this.required = false;
140
+ return this;
141
+ }
142
+ }
143
+ function humanReadableArgName(arg) {
144
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
145
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
146
+ }
147
+ exports.Argument = Argument;
148
+ exports.humanReadableArgName = humanReadableArgName;
149
+ });
150
+
151
+ // ../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/help.js
152
+ var require_help = __commonJS((exports) => {
153
+ var { humanReadableArgName } = require_argument();
154
+
155
+ class Help {
156
+ constructor() {
157
+ this.helpWidth = undefined;
158
+ this.minWidthToWrap = 40;
159
+ this.sortSubcommands = false;
160
+ this.sortOptions = false;
161
+ this.showGlobalOptions = false;
162
+ }
163
+ prepareContext(contextOptions) {
164
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
165
+ }
166
+ visibleCommands(cmd) {
167
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
168
+ const helpCommand = cmd._getHelpCommand();
169
+ if (helpCommand && !helpCommand._hidden) {
170
+ visibleCommands.push(helpCommand);
171
+ }
172
+ if (this.sortSubcommands) {
173
+ visibleCommands.sort((a, b) => {
174
+ return a.name().localeCompare(b.name());
175
+ });
176
+ }
177
+ return visibleCommands;
178
+ }
179
+ compareOptions(a, b) {
180
+ const getSortKey = (option) => {
181
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
182
+ };
183
+ return getSortKey(a).localeCompare(getSortKey(b));
184
+ }
185
+ visibleOptions(cmd) {
186
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
187
+ const helpOption = cmd._getHelpOption();
188
+ if (helpOption && !helpOption.hidden) {
189
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
190
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
191
+ if (!removeShort && !removeLong) {
192
+ visibleOptions.push(helpOption);
193
+ } else if (helpOption.long && !removeLong) {
194
+ visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
195
+ } else if (helpOption.short && !removeShort) {
196
+ visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
197
+ }
198
+ }
199
+ if (this.sortOptions) {
200
+ visibleOptions.sort(this.compareOptions);
201
+ }
202
+ return visibleOptions;
203
+ }
204
+ visibleGlobalOptions(cmd) {
205
+ if (!this.showGlobalOptions)
206
+ return [];
207
+ const globalOptions = [];
208
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
209
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
210
+ globalOptions.push(...visibleOptions);
211
+ }
212
+ if (this.sortOptions) {
213
+ globalOptions.sort(this.compareOptions);
214
+ }
215
+ return globalOptions;
216
+ }
217
+ visibleArguments(cmd) {
218
+ if (cmd._argsDescription) {
219
+ cmd.registeredArguments.forEach((argument) => {
220
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
221
+ });
222
+ }
223
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
224
+ return cmd.registeredArguments;
225
+ }
226
+ return [];
227
+ }
228
+ subcommandTerm(cmd) {
229
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
230
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
231
+ }
232
+ optionTerm(option) {
233
+ return option.flags;
234
+ }
235
+ argumentTerm(argument) {
236
+ return argument.name();
237
+ }
238
+ longestSubcommandTermLength(cmd, helper) {
239
+ return helper.visibleCommands(cmd).reduce((max, command) => {
240
+ return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
241
+ }, 0);
242
+ }
243
+ longestOptionTermLength(cmd, helper) {
244
+ return helper.visibleOptions(cmd).reduce((max, option) => {
245
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
246
+ }, 0);
247
+ }
248
+ longestGlobalOptionTermLength(cmd, helper) {
249
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
250
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
251
+ }, 0);
252
+ }
253
+ longestArgumentTermLength(cmd, helper) {
254
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
255
+ return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
256
+ }, 0);
257
+ }
258
+ commandUsage(cmd) {
259
+ let cmdName = cmd._name;
260
+ if (cmd._aliases[0]) {
261
+ cmdName = cmdName + "|" + cmd._aliases[0];
262
+ }
263
+ let ancestorCmdNames = "";
264
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
265
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
266
+ }
267
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
268
+ }
269
+ commandDescription(cmd) {
270
+ return cmd.description();
271
+ }
272
+ subcommandDescription(cmd) {
273
+ return cmd.summary() || cmd.description();
274
+ }
275
+ optionDescription(option) {
276
+ const extraInfo = [];
277
+ if (option.argChoices) {
278
+ extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
279
+ }
280
+ if (option.defaultValue !== undefined) {
281
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
282
+ if (showDefault) {
283
+ extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
284
+ }
285
+ }
286
+ if (option.presetArg !== undefined && option.optional) {
287
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
288
+ }
289
+ if (option.envVar !== undefined) {
290
+ extraInfo.push(`env: ${option.envVar}`);
291
+ }
292
+ if (extraInfo.length > 0) {
293
+ const extraDescription = `(${extraInfo.join(", ")})`;
294
+ if (option.description) {
295
+ return `${option.description} ${extraDescription}`;
296
+ }
297
+ return extraDescription;
298
+ }
299
+ return option.description;
300
+ }
301
+ argumentDescription(argument) {
302
+ const extraInfo = [];
303
+ if (argument.argChoices) {
304
+ extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
305
+ }
306
+ if (argument.defaultValue !== undefined) {
307
+ extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
308
+ }
309
+ if (extraInfo.length > 0) {
310
+ const extraDescription = `(${extraInfo.join(", ")})`;
311
+ if (argument.description) {
312
+ return `${argument.description} ${extraDescription}`;
313
+ }
314
+ return extraDescription;
315
+ }
316
+ return argument.description;
317
+ }
318
+ formatItemList(heading, items, helper) {
319
+ if (items.length === 0)
320
+ return [];
321
+ return [helper.styleTitle(heading), ...items, ""];
322
+ }
323
+ groupItems(unsortedItems, visibleItems, getGroup) {
324
+ const result = new Map;
325
+ unsortedItems.forEach((item) => {
326
+ const group = getGroup(item);
327
+ if (!result.has(group))
328
+ result.set(group, []);
329
+ });
330
+ visibleItems.forEach((item) => {
331
+ const group = getGroup(item);
332
+ if (!result.has(group)) {
333
+ result.set(group, []);
334
+ }
335
+ result.get(group).push(item);
336
+ });
337
+ return result;
338
+ }
339
+ formatHelp(cmd, helper) {
340
+ const termWidth = helper.padWidth(cmd, helper);
341
+ const helpWidth = helper.helpWidth ?? 80;
342
+ function callFormatItem(term, description) {
343
+ return helper.formatItem(term, termWidth, description, helper);
344
+ }
345
+ let output = [
346
+ `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
347
+ ""
348
+ ];
349
+ const commandDescription = helper.commandDescription(cmd);
350
+ if (commandDescription.length > 0) {
351
+ output = output.concat([
352
+ helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth),
353
+ ""
354
+ ]);
355
+ }
356
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
357
+ return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
358
+ });
359
+ output = output.concat(this.formatItemList("Arguments:", argumentList, helper));
360
+ const optionGroups = this.groupItems(cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? "Options:");
361
+ optionGroups.forEach((options, group) => {
362
+ const optionList = options.map((option) => {
363
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
364
+ });
365
+ output = output.concat(this.formatItemList(group, optionList, helper));
366
+ });
367
+ if (helper.showGlobalOptions) {
368
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
369
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
370
+ });
371
+ output = output.concat(this.formatItemList("Global Options:", globalOptionList, helper));
372
+ }
373
+ const commandGroups = this.groupItems(cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || "Commands:");
374
+ commandGroups.forEach((commands, group) => {
375
+ const commandList = commands.map((sub) => {
376
+ return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)));
377
+ });
378
+ output = output.concat(this.formatItemList(group, commandList, helper));
379
+ });
380
+ return output.join(`
381
+ `);
382
+ }
383
+ displayWidth(str) {
384
+ return stripColor(str).length;
385
+ }
386
+ styleTitle(str) {
387
+ return str;
388
+ }
389
+ styleUsage(str) {
390
+ return str.split(" ").map((word) => {
391
+ if (word === "[options]")
392
+ return this.styleOptionText(word);
393
+ if (word === "[command]")
394
+ return this.styleSubcommandText(word);
395
+ if (word[0] === "[" || word[0] === "<")
396
+ return this.styleArgumentText(word);
397
+ return this.styleCommandText(word);
398
+ }).join(" ");
399
+ }
400
+ styleCommandDescription(str) {
401
+ return this.styleDescriptionText(str);
402
+ }
403
+ styleOptionDescription(str) {
404
+ return this.styleDescriptionText(str);
405
+ }
406
+ styleSubcommandDescription(str) {
407
+ return this.styleDescriptionText(str);
408
+ }
409
+ styleArgumentDescription(str) {
410
+ return this.styleDescriptionText(str);
411
+ }
412
+ styleDescriptionText(str) {
413
+ return str;
414
+ }
415
+ styleOptionTerm(str) {
416
+ return this.styleOptionText(str);
417
+ }
418
+ styleSubcommandTerm(str) {
419
+ return str.split(" ").map((word) => {
420
+ if (word === "[options]")
421
+ return this.styleOptionText(word);
422
+ if (word[0] === "[" || word[0] === "<")
423
+ return this.styleArgumentText(word);
424
+ return this.styleSubcommandText(word);
425
+ }).join(" ");
426
+ }
427
+ styleArgumentTerm(str) {
428
+ return this.styleArgumentText(str);
429
+ }
430
+ styleOptionText(str) {
431
+ return str;
432
+ }
433
+ styleArgumentText(str) {
434
+ return str;
435
+ }
436
+ styleSubcommandText(str) {
437
+ return str;
438
+ }
439
+ styleCommandText(str) {
440
+ return str;
441
+ }
442
+ padWidth(cmd, helper) {
443
+ return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
444
+ }
445
+ preformatted(str) {
446
+ return /\n[^\S\r\n]/.test(str);
447
+ }
448
+ formatItem(term, termWidth, description, helper) {
449
+ const itemIndent = 2;
450
+ const itemIndentStr = " ".repeat(itemIndent);
451
+ if (!description)
452
+ return itemIndentStr + term;
453
+ const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
454
+ const spacerWidth = 2;
455
+ const helpWidth = this.helpWidth ?? 80;
456
+ const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
457
+ let formattedDescription;
458
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
459
+ formattedDescription = description;
460
+ } else {
461
+ const wrappedDescription = helper.boxWrap(description, remainingWidth);
462
+ formattedDescription = wrappedDescription.replace(/\n/g, `
463
+ ` + " ".repeat(termWidth + spacerWidth));
464
+ }
465
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
466
+ ${itemIndentStr}`);
467
+ }
468
+ boxWrap(str, width) {
469
+ if (width < this.minWidthToWrap)
470
+ return str;
471
+ const rawLines = str.split(/\r\n|\n/);
472
+ const chunkPattern = /[\s]*[^\s]+/g;
473
+ const wrappedLines = [];
474
+ rawLines.forEach((line) => {
475
+ const chunks = line.match(chunkPattern);
476
+ if (chunks === null) {
477
+ wrappedLines.push("");
478
+ return;
479
+ }
480
+ let sumChunks = [chunks.shift()];
481
+ let sumWidth = this.displayWidth(sumChunks[0]);
482
+ chunks.forEach((chunk) => {
483
+ const visibleWidth = this.displayWidth(chunk);
484
+ if (sumWidth + visibleWidth <= width) {
485
+ sumChunks.push(chunk);
486
+ sumWidth += visibleWidth;
487
+ return;
488
+ }
489
+ wrappedLines.push(sumChunks.join(""));
490
+ const nextChunk = chunk.trimStart();
491
+ sumChunks = [nextChunk];
492
+ sumWidth = this.displayWidth(nextChunk);
493
+ });
494
+ wrappedLines.push(sumChunks.join(""));
495
+ });
496
+ return wrappedLines.join(`
497
+ `);
498
+ }
499
+ }
500
+ function stripColor(str) {
501
+ const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
502
+ return str.replace(sgrPattern, "");
503
+ }
504
+ exports.Help = Help;
505
+ exports.stripColor = stripColor;
506
+ });
507
+
508
+ // ../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/option.js
509
+ var require_option = __commonJS((exports) => {
510
+ var { InvalidArgumentError } = require_error();
511
+
512
+ class Option {
513
+ constructor(flags, description) {
514
+ this.flags = flags;
515
+ this.description = description || "";
516
+ this.required = flags.includes("<");
517
+ this.optional = flags.includes("[");
518
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
519
+ this.mandatory = false;
520
+ const optionFlags = splitOptionFlags(flags);
521
+ this.short = optionFlags.shortFlag;
522
+ this.long = optionFlags.longFlag;
523
+ this.negate = false;
524
+ if (this.long) {
525
+ this.negate = this.long.startsWith("--no-");
526
+ }
527
+ this.defaultValue = undefined;
528
+ this.defaultValueDescription = undefined;
529
+ this.presetArg = undefined;
530
+ this.envVar = undefined;
531
+ this.parseArg = undefined;
532
+ this.hidden = false;
533
+ this.argChoices = undefined;
534
+ this.conflictsWith = [];
535
+ this.implied = undefined;
536
+ this.helpGroupHeading = undefined;
537
+ }
538
+ default(value, description) {
539
+ this.defaultValue = value;
540
+ this.defaultValueDescription = description;
541
+ return this;
542
+ }
543
+ preset(arg) {
544
+ this.presetArg = arg;
545
+ return this;
546
+ }
547
+ conflicts(names) {
548
+ this.conflictsWith = this.conflictsWith.concat(names);
549
+ return this;
550
+ }
551
+ implies(impliedOptionValues) {
552
+ let newImplied = impliedOptionValues;
553
+ if (typeof impliedOptionValues === "string") {
554
+ newImplied = { [impliedOptionValues]: true };
555
+ }
556
+ this.implied = Object.assign(this.implied || {}, newImplied);
557
+ return this;
558
+ }
559
+ env(name) {
560
+ this.envVar = name;
561
+ return this;
562
+ }
563
+ argParser(fn) {
564
+ this.parseArg = fn;
565
+ return this;
566
+ }
567
+ makeOptionMandatory(mandatory = true) {
568
+ this.mandatory = !!mandatory;
569
+ return this;
570
+ }
571
+ hideHelp(hide = true) {
572
+ this.hidden = !!hide;
573
+ return this;
574
+ }
575
+ _collectValue(value, previous) {
576
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
577
+ return [value];
578
+ }
579
+ previous.push(value);
580
+ return previous;
581
+ }
582
+ choices(values) {
583
+ this.argChoices = values.slice();
584
+ this.parseArg = (arg, previous) => {
585
+ if (!this.argChoices.includes(arg)) {
586
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
587
+ }
588
+ if (this.variadic) {
589
+ return this._collectValue(arg, previous);
590
+ }
591
+ return arg;
592
+ };
593
+ return this;
594
+ }
595
+ name() {
596
+ if (this.long) {
597
+ return this.long.replace(/^--/, "");
598
+ }
599
+ return this.short.replace(/^-/, "");
600
+ }
601
+ attributeName() {
602
+ if (this.negate) {
603
+ return camelcase(this.name().replace(/^no-/, ""));
604
+ }
605
+ return camelcase(this.name());
606
+ }
607
+ helpGroup(heading) {
608
+ this.helpGroupHeading = heading;
609
+ return this;
610
+ }
611
+ is(arg) {
612
+ return this.short === arg || this.long === arg;
613
+ }
614
+ isBoolean() {
615
+ return !this.required && !this.optional && !this.negate;
616
+ }
617
+ }
618
+
619
+ class DualOptions {
620
+ constructor(options) {
621
+ this.positiveOptions = new Map;
622
+ this.negativeOptions = new Map;
623
+ this.dualOptions = new Set;
624
+ options.forEach((option) => {
625
+ if (option.negate) {
626
+ this.negativeOptions.set(option.attributeName(), option);
627
+ } else {
628
+ this.positiveOptions.set(option.attributeName(), option);
629
+ }
630
+ });
631
+ this.negativeOptions.forEach((value, key) => {
632
+ if (this.positiveOptions.has(key)) {
633
+ this.dualOptions.add(key);
634
+ }
635
+ });
636
+ }
637
+ valueFromOption(value, option) {
638
+ const optionKey = option.attributeName();
639
+ if (!this.dualOptions.has(optionKey))
640
+ return true;
641
+ const preset = this.negativeOptions.get(optionKey).presetArg;
642
+ const negativeValue = preset !== undefined ? preset : false;
643
+ return option.negate === (negativeValue === value);
644
+ }
645
+ }
646
+ function camelcase(str) {
647
+ return str.split("-").reduce((str2, word) => {
648
+ return str2 + word[0].toUpperCase() + word.slice(1);
649
+ });
650
+ }
651
+ function splitOptionFlags(flags) {
652
+ let shortFlag;
653
+ let longFlag;
654
+ const shortFlagExp = /^-[^-]$/;
655
+ const longFlagExp = /^--[^-]/;
656
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
657
+ if (shortFlagExp.test(flagParts[0]))
658
+ shortFlag = flagParts.shift();
659
+ if (longFlagExp.test(flagParts[0]))
660
+ longFlag = flagParts.shift();
661
+ if (!shortFlag && shortFlagExp.test(flagParts[0]))
662
+ shortFlag = flagParts.shift();
663
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
664
+ shortFlag = longFlag;
665
+ longFlag = flagParts.shift();
666
+ }
667
+ if (flagParts[0].startsWith("-")) {
668
+ const unsupportedFlag = flagParts[0];
669
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
670
+ if (/^-[^-][^-]/.test(unsupportedFlag))
671
+ throw new Error(`${baseError}
672
+ - a short flag is a single dash and a single character
673
+ - either use a single dash and a single character (for a short flag)
674
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
675
+ if (shortFlagExp.test(unsupportedFlag))
676
+ throw new Error(`${baseError}
677
+ - too many short flags`);
678
+ if (longFlagExp.test(unsupportedFlag))
679
+ throw new Error(`${baseError}
680
+ - too many long flags`);
681
+ throw new Error(`${baseError}
682
+ - unrecognised flag format`);
683
+ }
684
+ if (shortFlag === undefined && longFlag === undefined)
685
+ throw new Error(`option creation failed due to no flags found in '${flags}'.`);
686
+ return { shortFlag, longFlag };
687
+ }
688
+ exports.Option = Option;
689
+ exports.DualOptions = DualOptions;
690
+ });
691
+
692
+ // ../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/suggestSimilar.js
693
+ var require_suggestSimilar = __commonJS((exports) => {
694
+ var maxDistance = 3;
695
+ function editDistance(a, b) {
696
+ if (Math.abs(a.length - b.length) > maxDistance)
697
+ return Math.max(a.length, b.length);
698
+ const d = [];
699
+ for (let i = 0;i <= a.length; i++) {
700
+ d[i] = [i];
701
+ }
702
+ for (let j = 0;j <= b.length; j++) {
703
+ d[0][j] = j;
704
+ }
705
+ for (let j = 1;j <= b.length; j++) {
706
+ for (let i = 1;i <= a.length; i++) {
707
+ let cost = 1;
708
+ if (a[i - 1] === b[j - 1]) {
709
+ cost = 0;
710
+ } else {
711
+ cost = 1;
712
+ }
713
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
714
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
715
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
716
+ }
717
+ }
718
+ }
719
+ return d[a.length][b.length];
720
+ }
721
+ function suggestSimilar(word, candidates) {
722
+ if (!candidates || candidates.length === 0)
723
+ return "";
724
+ candidates = Array.from(new Set(candidates));
725
+ const searchingOptions = word.startsWith("--");
726
+ if (searchingOptions) {
727
+ word = word.slice(2);
728
+ candidates = candidates.map((candidate) => candidate.slice(2));
729
+ }
730
+ let similar = [];
731
+ let bestDistance = maxDistance;
732
+ const minSimilarity = 0.4;
733
+ candidates.forEach((candidate) => {
734
+ if (candidate.length <= 1)
735
+ return;
736
+ const distance = editDistance(word, candidate);
737
+ const length = Math.max(word.length, candidate.length);
738
+ const similarity = (length - distance) / length;
739
+ if (similarity > minSimilarity) {
740
+ if (distance < bestDistance) {
741
+ bestDistance = distance;
742
+ similar = [candidate];
743
+ } else if (distance === bestDistance) {
744
+ similar.push(candidate);
745
+ }
746
+ }
747
+ });
748
+ similar.sort((a, b) => a.localeCompare(b));
749
+ if (searchingOptions) {
750
+ similar = similar.map((candidate) => `--${candidate}`);
751
+ }
752
+ if (similar.length > 1) {
753
+ return `
754
+ (Did you mean one of ${similar.join(", ")}?)`;
755
+ }
756
+ if (similar.length === 1) {
757
+ return `
758
+ (Did you mean ${similar[0]}?)`;
759
+ }
760
+ return "";
761
+ }
762
+ exports.suggestSimilar = suggestSimilar;
763
+ });
764
+
765
+ // ../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/command.js
766
+ var require_command = __commonJS((exports) => {
767
+ var EventEmitter = __require("events").EventEmitter;
768
+ var childProcess = __require("child_process");
769
+ var path = __require("path");
770
+ var fs = __require("fs");
771
+ var process2 = __require("process");
772
+ var { Argument, humanReadableArgName } = require_argument();
773
+ var { CommanderError } = require_error();
774
+ var { Help, stripColor } = require_help();
775
+ var { Option, DualOptions } = require_option();
776
+ var { suggestSimilar } = require_suggestSimilar();
777
+
778
+ class Command extends EventEmitter {
779
+ constructor(name) {
780
+ super();
781
+ this.commands = [];
782
+ this.options = [];
783
+ this.parent = null;
784
+ this._allowUnknownOption = false;
785
+ this._allowExcessArguments = false;
786
+ this.registeredArguments = [];
787
+ this._args = this.registeredArguments;
788
+ this.args = [];
789
+ this.rawArgs = [];
790
+ this.processedArgs = [];
791
+ this._scriptPath = null;
792
+ this._name = name || "";
793
+ this._optionValues = {};
794
+ this._optionValueSources = {};
795
+ this._storeOptionsAsProperties = false;
796
+ this._actionHandler = null;
797
+ this._executableHandler = false;
798
+ this._executableFile = null;
799
+ this._executableDir = null;
800
+ this._defaultCommandName = null;
801
+ this._exitCallback = null;
802
+ this._aliases = [];
803
+ this._combineFlagAndOptionalValue = true;
804
+ this._description = "";
805
+ this._summary = "";
806
+ this._argsDescription = undefined;
807
+ this._enablePositionalOptions = false;
808
+ this._passThroughOptions = false;
809
+ this._lifeCycleHooks = {};
810
+ this._showHelpAfterError = false;
811
+ this._showSuggestionAfterError = true;
812
+ this._savedState = null;
813
+ this._outputConfiguration = {
814
+ writeOut: (str) => process2.stdout.write(str),
815
+ writeErr: (str) => process2.stderr.write(str),
816
+ outputError: (str, write) => write(str),
817
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : undefined,
818
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : undefined,
819
+ getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
820
+ getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
821
+ stripColor: (str) => stripColor(str)
822
+ };
823
+ this._hidden = false;
824
+ this._helpOption = undefined;
825
+ this._addImplicitHelpCommand = undefined;
826
+ this._helpCommand = undefined;
827
+ this._helpConfiguration = {};
828
+ this._helpGroupHeading = undefined;
829
+ this._defaultCommandGroup = undefined;
830
+ this._defaultOptionGroup = undefined;
831
+ }
832
+ copyInheritedSettings(sourceCommand) {
833
+ this._outputConfiguration = sourceCommand._outputConfiguration;
834
+ this._helpOption = sourceCommand._helpOption;
835
+ this._helpCommand = sourceCommand._helpCommand;
836
+ this._helpConfiguration = sourceCommand._helpConfiguration;
837
+ this._exitCallback = sourceCommand._exitCallback;
838
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
839
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
840
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
841
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
842
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
843
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
844
+ return this;
845
+ }
846
+ _getCommandAndAncestors() {
847
+ const result = [];
848
+ for (let command = this;command; command = command.parent) {
849
+ result.push(command);
850
+ }
851
+ return result;
852
+ }
853
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
854
+ let desc = actionOptsOrExecDesc;
855
+ let opts = execOpts;
856
+ if (typeof desc === "object" && desc !== null) {
857
+ opts = desc;
858
+ desc = null;
859
+ }
860
+ opts = opts || {};
861
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
862
+ const cmd = this.createCommand(name);
863
+ if (desc) {
864
+ cmd.description(desc);
865
+ cmd._executableHandler = true;
866
+ }
867
+ if (opts.isDefault)
868
+ this._defaultCommandName = cmd._name;
869
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
870
+ cmd._executableFile = opts.executableFile || null;
871
+ if (args)
872
+ cmd.arguments(args);
873
+ this._registerCommand(cmd);
874
+ cmd.parent = this;
875
+ cmd.copyInheritedSettings(this);
876
+ if (desc)
877
+ return this;
878
+ return cmd;
879
+ }
880
+ createCommand(name) {
881
+ return new Command(name);
882
+ }
883
+ createHelp() {
884
+ return Object.assign(new Help, this.configureHelp());
885
+ }
886
+ configureHelp(configuration) {
887
+ if (configuration === undefined)
888
+ return this._helpConfiguration;
889
+ this._helpConfiguration = configuration;
890
+ return this;
891
+ }
892
+ configureOutput(configuration) {
893
+ if (configuration === undefined)
894
+ return this._outputConfiguration;
895
+ this._outputConfiguration = {
896
+ ...this._outputConfiguration,
897
+ ...configuration
898
+ };
899
+ return this;
900
+ }
901
+ showHelpAfterError(displayHelp = true) {
902
+ if (typeof displayHelp !== "string")
903
+ displayHelp = !!displayHelp;
904
+ this._showHelpAfterError = displayHelp;
905
+ return this;
906
+ }
907
+ showSuggestionAfterError(displaySuggestion = true) {
908
+ this._showSuggestionAfterError = !!displaySuggestion;
909
+ return this;
910
+ }
911
+ addCommand(cmd, opts) {
912
+ if (!cmd._name) {
913
+ throw new Error(`Command passed to .addCommand() must have a name
914
+ - specify the name in Command constructor or using .name()`);
915
+ }
916
+ opts = opts || {};
917
+ if (opts.isDefault)
918
+ this._defaultCommandName = cmd._name;
919
+ if (opts.noHelp || opts.hidden)
920
+ cmd._hidden = true;
921
+ this._registerCommand(cmd);
922
+ cmd.parent = this;
923
+ cmd._checkForBrokenPassThrough();
924
+ return this;
925
+ }
926
+ createArgument(name, description) {
927
+ return new Argument(name, description);
928
+ }
929
+ argument(name, description, parseArg, defaultValue) {
930
+ const argument = this.createArgument(name, description);
931
+ if (typeof parseArg === "function") {
932
+ argument.default(defaultValue).argParser(parseArg);
933
+ } else {
934
+ argument.default(parseArg);
935
+ }
936
+ this.addArgument(argument);
937
+ return this;
938
+ }
939
+ arguments(names) {
940
+ names.trim().split(/ +/).forEach((detail) => {
941
+ this.argument(detail);
942
+ });
943
+ return this;
944
+ }
945
+ addArgument(argument) {
946
+ const previousArgument = this.registeredArguments.slice(-1)[0];
947
+ if (previousArgument?.variadic) {
948
+ throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
949
+ }
950
+ if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {
951
+ throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
952
+ }
953
+ this.registeredArguments.push(argument);
954
+ return this;
955
+ }
956
+ helpCommand(enableOrNameAndArgs, description) {
957
+ if (typeof enableOrNameAndArgs === "boolean") {
958
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
959
+ if (enableOrNameAndArgs && this._defaultCommandGroup) {
960
+ this._initCommandGroup(this._getHelpCommand());
961
+ }
962
+ return this;
963
+ }
964
+ const nameAndArgs = enableOrNameAndArgs ?? "help [command]";
965
+ const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
966
+ const helpDescription = description ?? "display help for command";
967
+ const helpCommand = this.createCommand(helpName);
968
+ helpCommand.helpOption(false);
969
+ if (helpArgs)
970
+ helpCommand.arguments(helpArgs);
971
+ if (helpDescription)
972
+ helpCommand.description(helpDescription);
973
+ this._addImplicitHelpCommand = true;
974
+ this._helpCommand = helpCommand;
975
+ if (enableOrNameAndArgs || description)
976
+ this._initCommandGroup(helpCommand);
977
+ return this;
978
+ }
979
+ addHelpCommand(helpCommand, deprecatedDescription) {
980
+ if (typeof helpCommand !== "object") {
981
+ this.helpCommand(helpCommand, deprecatedDescription);
982
+ return this;
983
+ }
984
+ this._addImplicitHelpCommand = true;
985
+ this._helpCommand = helpCommand;
986
+ this._initCommandGroup(helpCommand);
987
+ return this;
988
+ }
989
+ _getHelpCommand() {
990
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
991
+ if (hasImplicitHelpCommand) {
992
+ if (this._helpCommand === undefined) {
993
+ this.helpCommand(undefined, undefined);
994
+ }
995
+ return this._helpCommand;
996
+ }
997
+ return null;
998
+ }
999
+ hook(event, listener) {
1000
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
1001
+ if (!allowedValues.includes(event)) {
1002
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
1003
+ Expecting one of '${allowedValues.join("', '")}'`);
1004
+ }
1005
+ if (this._lifeCycleHooks[event]) {
1006
+ this._lifeCycleHooks[event].push(listener);
1007
+ } else {
1008
+ this._lifeCycleHooks[event] = [listener];
1009
+ }
1010
+ return this;
1011
+ }
1012
+ exitOverride(fn) {
1013
+ if (fn) {
1014
+ this._exitCallback = fn;
1015
+ } else {
1016
+ this._exitCallback = (err) => {
1017
+ if (err.code !== "commander.executeSubCommandAsync") {
1018
+ throw err;
1019
+ } else {}
1020
+ };
1021
+ }
1022
+ return this;
1023
+ }
1024
+ _exit(exitCode, code, message) {
1025
+ if (this._exitCallback) {
1026
+ this._exitCallback(new CommanderError(exitCode, code, message));
1027
+ }
1028
+ process2.exit(exitCode);
1029
+ }
1030
+ action(fn) {
1031
+ const listener = (args) => {
1032
+ const expectedArgsCount = this.registeredArguments.length;
1033
+ const actionArgs = args.slice(0, expectedArgsCount);
1034
+ if (this._storeOptionsAsProperties) {
1035
+ actionArgs[expectedArgsCount] = this;
1036
+ } else {
1037
+ actionArgs[expectedArgsCount] = this.opts();
1038
+ }
1039
+ actionArgs.push(this);
1040
+ return fn.apply(this, actionArgs);
1041
+ };
1042
+ this._actionHandler = listener;
1043
+ return this;
1044
+ }
1045
+ createOption(flags, description) {
1046
+ return new Option(flags, description);
1047
+ }
1048
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1049
+ try {
1050
+ return target.parseArg(value, previous);
1051
+ } catch (err) {
1052
+ if (err.code === "commander.invalidArgument") {
1053
+ const message = `${invalidArgumentMessage} ${err.message}`;
1054
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1055
+ }
1056
+ throw err;
1057
+ }
1058
+ }
1059
+ _registerOption(option) {
1060
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1061
+ if (matchingOption) {
1062
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1063
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1064
+ - already used by option '${matchingOption.flags}'`);
1065
+ }
1066
+ this._initOptionGroup(option);
1067
+ this.options.push(option);
1068
+ }
1069
+ _registerCommand(command) {
1070
+ const knownBy = (cmd) => {
1071
+ return [cmd.name()].concat(cmd.aliases());
1072
+ };
1073
+ const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
1074
+ if (alreadyUsed) {
1075
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1076
+ const newCmd = knownBy(command).join("|");
1077
+ throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
1078
+ }
1079
+ this._initCommandGroup(command);
1080
+ this.commands.push(command);
1081
+ }
1082
+ addOption(option) {
1083
+ this._registerOption(option);
1084
+ const oname = option.name();
1085
+ const name = option.attributeName();
1086
+ if (option.negate) {
1087
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1088
+ if (!this._findOption(positiveLongFlag)) {
1089
+ this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, "default");
1090
+ }
1091
+ } else if (option.defaultValue !== undefined) {
1092
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
1093
+ }
1094
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1095
+ if (val == null && option.presetArg !== undefined) {
1096
+ val = option.presetArg;
1097
+ }
1098
+ const oldValue = this.getOptionValue(name);
1099
+ if (val !== null && option.parseArg) {
1100
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1101
+ } else if (val !== null && option.variadic) {
1102
+ val = option._collectValue(val, oldValue);
1103
+ }
1104
+ if (val == null) {
1105
+ if (option.negate) {
1106
+ val = false;
1107
+ } else if (option.isBoolean() || option.optional) {
1108
+ val = true;
1109
+ } else {
1110
+ val = "";
1111
+ }
1112
+ }
1113
+ this.setOptionValueWithSource(name, val, valueSource);
1114
+ };
1115
+ this.on("option:" + oname, (val) => {
1116
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1117
+ handleOptionValue(val, invalidValueMessage, "cli");
1118
+ });
1119
+ if (option.envVar) {
1120
+ this.on("optionEnv:" + oname, (val) => {
1121
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1122
+ handleOptionValue(val, invalidValueMessage, "env");
1123
+ });
1124
+ }
1125
+ return this;
1126
+ }
1127
+ _optionEx(config, flags, description, fn, defaultValue) {
1128
+ if (typeof flags === "object" && flags instanceof Option) {
1129
+ throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
1130
+ }
1131
+ const option = this.createOption(flags, description);
1132
+ option.makeOptionMandatory(!!config.mandatory);
1133
+ if (typeof fn === "function") {
1134
+ option.default(defaultValue).argParser(fn);
1135
+ } else if (fn instanceof RegExp) {
1136
+ const regex = fn;
1137
+ fn = (val, def) => {
1138
+ const m = regex.exec(val);
1139
+ return m ? m[0] : def;
1140
+ };
1141
+ option.default(defaultValue).argParser(fn);
1142
+ } else {
1143
+ option.default(fn);
1144
+ }
1145
+ return this.addOption(option);
1146
+ }
1147
+ option(flags, description, parseArg, defaultValue) {
1148
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1149
+ }
1150
+ requiredOption(flags, description, parseArg, defaultValue) {
1151
+ return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
1152
+ }
1153
+ combineFlagAndOptionalValue(combine = true) {
1154
+ this._combineFlagAndOptionalValue = !!combine;
1155
+ return this;
1156
+ }
1157
+ allowUnknownOption(allowUnknown = true) {
1158
+ this._allowUnknownOption = !!allowUnknown;
1159
+ return this;
1160
+ }
1161
+ allowExcessArguments(allowExcess = true) {
1162
+ this._allowExcessArguments = !!allowExcess;
1163
+ return this;
1164
+ }
1165
+ enablePositionalOptions(positional = true) {
1166
+ this._enablePositionalOptions = !!positional;
1167
+ return this;
1168
+ }
1169
+ passThroughOptions(passThrough = true) {
1170
+ this._passThroughOptions = !!passThrough;
1171
+ this._checkForBrokenPassThrough();
1172
+ return this;
1173
+ }
1174
+ _checkForBrokenPassThrough() {
1175
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1176
+ throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
1177
+ }
1178
+ }
1179
+ storeOptionsAsProperties(storeAsProperties = true) {
1180
+ if (this.options.length) {
1181
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1182
+ }
1183
+ if (Object.keys(this._optionValues).length) {
1184
+ throw new Error("call .storeOptionsAsProperties() before setting option values");
1185
+ }
1186
+ this._storeOptionsAsProperties = !!storeAsProperties;
1187
+ return this;
1188
+ }
1189
+ getOptionValue(key) {
1190
+ if (this._storeOptionsAsProperties) {
1191
+ return this[key];
1192
+ }
1193
+ return this._optionValues[key];
1194
+ }
1195
+ setOptionValue(key, value) {
1196
+ return this.setOptionValueWithSource(key, value, undefined);
1197
+ }
1198
+ setOptionValueWithSource(key, value, source) {
1199
+ if (this._storeOptionsAsProperties) {
1200
+ this[key] = value;
1201
+ } else {
1202
+ this._optionValues[key] = value;
1203
+ }
1204
+ this._optionValueSources[key] = source;
1205
+ return this;
1206
+ }
1207
+ getOptionValueSource(key) {
1208
+ return this._optionValueSources[key];
1209
+ }
1210
+ getOptionValueSourceWithGlobals(key) {
1211
+ let source;
1212
+ this._getCommandAndAncestors().forEach((cmd) => {
1213
+ if (cmd.getOptionValueSource(key) !== undefined) {
1214
+ source = cmd.getOptionValueSource(key);
1215
+ }
1216
+ });
1217
+ return source;
1218
+ }
1219
+ _prepareUserArgs(argv, parseOptions) {
1220
+ if (argv !== undefined && !Array.isArray(argv)) {
1221
+ throw new Error("first parameter to parse must be array or undefined");
1222
+ }
1223
+ parseOptions = parseOptions || {};
1224
+ if (argv === undefined && parseOptions.from === undefined) {
1225
+ if (process2.versions?.electron) {
1226
+ parseOptions.from = "electron";
1227
+ }
1228
+ const execArgv = process2.execArgv ?? [];
1229
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1230
+ parseOptions.from = "eval";
1231
+ }
1232
+ }
1233
+ if (argv === undefined) {
1234
+ argv = process2.argv;
1235
+ }
1236
+ this.rawArgs = argv.slice();
1237
+ let userArgs;
1238
+ switch (parseOptions.from) {
1239
+ case undefined:
1240
+ case "node":
1241
+ this._scriptPath = argv[1];
1242
+ userArgs = argv.slice(2);
1243
+ break;
1244
+ case "electron":
1245
+ if (process2.defaultApp) {
1246
+ this._scriptPath = argv[1];
1247
+ userArgs = argv.slice(2);
1248
+ } else {
1249
+ userArgs = argv.slice(1);
1250
+ }
1251
+ break;
1252
+ case "user":
1253
+ userArgs = argv.slice(0);
1254
+ break;
1255
+ case "eval":
1256
+ userArgs = argv.slice(1);
1257
+ break;
1258
+ default:
1259
+ throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1260
+ }
1261
+ if (!this._name && this._scriptPath)
1262
+ this.nameFromFilename(this._scriptPath);
1263
+ this._name = this._name || "program";
1264
+ return userArgs;
1265
+ }
1266
+ parse(argv, parseOptions) {
1267
+ this._prepareForParse();
1268
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1269
+ this._parseCommand([], userArgs);
1270
+ return this;
1271
+ }
1272
+ async parseAsync(argv, parseOptions) {
1273
+ this._prepareForParse();
1274
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1275
+ await this._parseCommand([], userArgs);
1276
+ return this;
1277
+ }
1278
+ _prepareForParse() {
1279
+ if (this._savedState === null) {
1280
+ this.saveStateBeforeParse();
1281
+ } else {
1282
+ this.restoreStateBeforeParse();
1283
+ }
1284
+ }
1285
+ saveStateBeforeParse() {
1286
+ this._savedState = {
1287
+ _name: this._name,
1288
+ _optionValues: { ...this._optionValues },
1289
+ _optionValueSources: { ...this._optionValueSources }
1290
+ };
1291
+ }
1292
+ restoreStateBeforeParse() {
1293
+ if (this._storeOptionsAsProperties)
1294
+ throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
1295
+ - either make a new Command for each call to parse, or stop storing options as properties`);
1296
+ this._name = this._savedState._name;
1297
+ this._scriptPath = null;
1298
+ this.rawArgs = [];
1299
+ this._optionValues = { ...this._savedState._optionValues };
1300
+ this._optionValueSources = { ...this._savedState._optionValueSources };
1301
+ this.args = [];
1302
+ this.processedArgs = [];
1303
+ }
1304
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
1305
+ if (fs.existsSync(executableFile))
1306
+ return;
1307
+ const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
1308
+ const executableMissing = `'${executableFile}' does not exist
1309
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1310
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1311
+ - ${executableDirMessage}`;
1312
+ throw new Error(executableMissing);
1313
+ }
1314
+ _executeSubCommand(subcommand, args) {
1315
+ args = args.slice();
1316
+ let launchWithNode = false;
1317
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1318
+ function findFile(baseDir, baseName) {
1319
+ const localBin = path.resolve(baseDir, baseName);
1320
+ if (fs.existsSync(localBin))
1321
+ return localBin;
1322
+ if (sourceExt.includes(path.extname(baseName)))
1323
+ return;
1324
+ const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
1325
+ if (foundExt)
1326
+ return `${localBin}${foundExt}`;
1327
+ return;
1328
+ }
1329
+ this._checkForMissingMandatoryOptions();
1330
+ this._checkForConflictingOptions();
1331
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1332
+ let executableDir = this._executableDir || "";
1333
+ if (this._scriptPath) {
1334
+ let resolvedScriptPath;
1335
+ try {
1336
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1337
+ } catch {
1338
+ resolvedScriptPath = this._scriptPath;
1339
+ }
1340
+ executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
1341
+ }
1342
+ if (executableDir) {
1343
+ let localFile = findFile(executableDir, executableFile);
1344
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1345
+ const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
1346
+ if (legacyName !== this._name) {
1347
+ localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1348
+ }
1349
+ }
1350
+ executableFile = localFile || executableFile;
1351
+ }
1352
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
1353
+ let proc;
1354
+ if (process2.platform !== "win32") {
1355
+ if (launchWithNode) {
1356
+ args.unshift(executableFile);
1357
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1358
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
1359
+ } else {
1360
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1361
+ }
1362
+ } else {
1363
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1364
+ args.unshift(executableFile);
1365
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1366
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
1367
+ }
1368
+ if (!proc.killed) {
1369
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1370
+ signals.forEach((signal) => {
1371
+ process2.on(signal, () => {
1372
+ if (proc.killed === false && proc.exitCode === null) {
1373
+ proc.kill(signal);
1374
+ }
1375
+ });
1376
+ });
1377
+ }
1378
+ const exitCallback = this._exitCallback;
1379
+ proc.on("close", (code) => {
1380
+ code = code ?? 1;
1381
+ if (!exitCallback) {
1382
+ process2.exit(code);
1383
+ } else {
1384
+ exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
1385
+ }
1386
+ });
1387
+ proc.on("error", (err) => {
1388
+ if (err.code === "ENOENT") {
1389
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1390
+ } else if (err.code === "EACCES") {
1391
+ throw new Error(`'${executableFile}' not executable`);
1392
+ }
1393
+ if (!exitCallback) {
1394
+ process2.exit(1);
1395
+ } else {
1396
+ const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
1397
+ wrappedError.nestedError = err;
1398
+ exitCallback(wrappedError);
1399
+ }
1400
+ });
1401
+ this.runningCommand = proc;
1402
+ }
1403
+ _dispatchSubcommand(commandName, operands, unknown) {
1404
+ const subCommand = this._findCommand(commandName);
1405
+ if (!subCommand)
1406
+ this.help({ error: true });
1407
+ subCommand._prepareForParse();
1408
+ let promiseChain;
1409
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
1410
+ promiseChain = this._chainOrCall(promiseChain, () => {
1411
+ if (subCommand._executableHandler) {
1412
+ this._executeSubCommand(subCommand, operands.concat(unknown));
1413
+ } else {
1414
+ return subCommand._parseCommand(operands, unknown);
1415
+ }
1416
+ });
1417
+ return promiseChain;
1418
+ }
1419
+ _dispatchHelpCommand(subcommandName) {
1420
+ if (!subcommandName) {
1421
+ this.help();
1422
+ }
1423
+ const subCommand = this._findCommand(subcommandName);
1424
+ if (subCommand && !subCommand._executableHandler) {
1425
+ subCommand.help();
1426
+ }
1427
+ return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
1428
+ }
1429
+ _checkNumberOfArguments() {
1430
+ this.registeredArguments.forEach((arg, i) => {
1431
+ if (arg.required && this.args[i] == null) {
1432
+ this.missingArgument(arg.name());
1433
+ }
1434
+ });
1435
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
1436
+ return;
1437
+ }
1438
+ if (this.args.length > this.registeredArguments.length) {
1439
+ this._excessArguments(this.args);
1440
+ }
1441
+ }
1442
+ _processArguments() {
1443
+ const myParseArg = (argument, value, previous) => {
1444
+ let parsedValue = value;
1445
+ if (value !== null && argument.parseArg) {
1446
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
1447
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
1448
+ }
1449
+ return parsedValue;
1450
+ };
1451
+ this._checkNumberOfArguments();
1452
+ const processedArgs = [];
1453
+ this.registeredArguments.forEach((declaredArg, index) => {
1454
+ let value = declaredArg.defaultValue;
1455
+ if (declaredArg.variadic) {
1456
+ if (index < this.args.length) {
1457
+ value = this.args.slice(index);
1458
+ if (declaredArg.parseArg) {
1459
+ value = value.reduce((processed, v) => {
1460
+ return myParseArg(declaredArg, v, processed);
1461
+ }, declaredArg.defaultValue);
1462
+ }
1463
+ } else if (value === undefined) {
1464
+ value = [];
1465
+ }
1466
+ } else if (index < this.args.length) {
1467
+ value = this.args[index];
1468
+ if (declaredArg.parseArg) {
1469
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
1470
+ }
1471
+ }
1472
+ processedArgs[index] = value;
1473
+ });
1474
+ this.processedArgs = processedArgs;
1475
+ }
1476
+ _chainOrCall(promise, fn) {
1477
+ if (promise?.then && typeof promise.then === "function") {
1478
+ return promise.then(() => fn());
1479
+ }
1480
+ return fn();
1481
+ }
1482
+ _chainOrCallHooks(promise, event) {
1483
+ let result = promise;
1484
+ const hooks = [];
1485
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== undefined).forEach((hookedCommand) => {
1486
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
1487
+ hooks.push({ hookedCommand, callback });
1488
+ });
1489
+ });
1490
+ if (event === "postAction") {
1491
+ hooks.reverse();
1492
+ }
1493
+ hooks.forEach((hookDetail) => {
1494
+ result = this._chainOrCall(result, () => {
1495
+ return hookDetail.callback(hookDetail.hookedCommand, this);
1496
+ });
1497
+ });
1498
+ return result;
1499
+ }
1500
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
1501
+ let result = promise;
1502
+ if (this._lifeCycleHooks[event] !== undefined) {
1503
+ this._lifeCycleHooks[event].forEach((hook) => {
1504
+ result = this._chainOrCall(result, () => {
1505
+ return hook(this, subCommand);
1506
+ });
1507
+ });
1508
+ }
1509
+ return result;
1510
+ }
1511
+ _parseCommand(operands, unknown) {
1512
+ const parsed = this.parseOptions(unknown);
1513
+ this._parseOptionsEnv();
1514
+ this._parseOptionsImplied();
1515
+ operands = operands.concat(parsed.operands);
1516
+ unknown = parsed.unknown;
1517
+ this.args = operands.concat(unknown);
1518
+ if (operands && this._findCommand(operands[0])) {
1519
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
1520
+ }
1521
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
1522
+ return this._dispatchHelpCommand(operands[1]);
1523
+ }
1524
+ if (this._defaultCommandName) {
1525
+ this._outputHelpIfRequested(unknown);
1526
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
1527
+ }
1528
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
1529
+ this.help({ error: true });
1530
+ }
1531
+ this._outputHelpIfRequested(parsed.unknown);
1532
+ this._checkForMissingMandatoryOptions();
1533
+ this._checkForConflictingOptions();
1534
+ const checkForUnknownOptions = () => {
1535
+ if (parsed.unknown.length > 0) {
1536
+ this.unknownOption(parsed.unknown[0]);
1537
+ }
1538
+ };
1539
+ const commandEvent = `command:${this.name()}`;
1540
+ if (this._actionHandler) {
1541
+ checkForUnknownOptions();
1542
+ this._processArguments();
1543
+ let promiseChain;
1544
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
1545
+ promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
1546
+ if (this.parent) {
1547
+ promiseChain = this._chainOrCall(promiseChain, () => {
1548
+ this.parent.emit(commandEvent, operands, unknown);
1549
+ });
1550
+ }
1551
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
1552
+ return promiseChain;
1553
+ }
1554
+ if (this.parent?.listenerCount(commandEvent)) {
1555
+ checkForUnknownOptions();
1556
+ this._processArguments();
1557
+ this.parent.emit(commandEvent, operands, unknown);
1558
+ } else if (operands.length) {
1559
+ if (this._findCommand("*")) {
1560
+ return this._dispatchSubcommand("*", operands, unknown);
1561
+ }
1562
+ if (this.listenerCount("command:*")) {
1563
+ this.emit("command:*", operands, unknown);
1564
+ } else if (this.commands.length) {
1565
+ this.unknownCommand();
1566
+ } else {
1567
+ checkForUnknownOptions();
1568
+ this._processArguments();
1569
+ }
1570
+ } else if (this.commands.length) {
1571
+ checkForUnknownOptions();
1572
+ this.help({ error: true });
1573
+ } else {
1574
+ checkForUnknownOptions();
1575
+ this._processArguments();
1576
+ }
1577
+ }
1578
+ _findCommand(name) {
1579
+ if (!name)
1580
+ return;
1581
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
1582
+ }
1583
+ _findOption(arg) {
1584
+ return this.options.find((option) => option.is(arg));
1585
+ }
1586
+ _checkForMissingMandatoryOptions() {
1587
+ this._getCommandAndAncestors().forEach((cmd) => {
1588
+ cmd.options.forEach((anOption) => {
1589
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === undefined) {
1590
+ cmd.missingMandatoryOptionValue(anOption);
1591
+ }
1592
+ });
1593
+ });
1594
+ }
1595
+ _checkForConflictingLocalOptions() {
1596
+ const definedNonDefaultOptions = this.options.filter((option) => {
1597
+ const optionKey = option.attributeName();
1598
+ if (this.getOptionValue(optionKey) === undefined) {
1599
+ return false;
1600
+ }
1601
+ return this.getOptionValueSource(optionKey) !== "default";
1602
+ });
1603
+ const optionsWithConflicting = definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0);
1604
+ optionsWithConflicting.forEach((option) => {
1605
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
1606
+ if (conflictingAndDefined) {
1607
+ this._conflictingOption(option, conflictingAndDefined);
1608
+ }
1609
+ });
1610
+ }
1611
+ _checkForConflictingOptions() {
1612
+ this._getCommandAndAncestors().forEach((cmd) => {
1613
+ cmd._checkForConflictingLocalOptions();
1614
+ });
1615
+ }
1616
+ parseOptions(args) {
1617
+ const operands = [];
1618
+ const unknown = [];
1619
+ let dest = operands;
1620
+ function maybeOption(arg) {
1621
+ return arg.length > 1 && arg[0] === "-";
1622
+ }
1623
+ const negativeNumberArg = (arg) => {
1624
+ if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg))
1625
+ return false;
1626
+ return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short)));
1627
+ };
1628
+ let activeVariadicOption = null;
1629
+ let activeGroup = null;
1630
+ let i = 0;
1631
+ while (i < args.length || activeGroup) {
1632
+ const arg = activeGroup ?? args[i++];
1633
+ activeGroup = null;
1634
+ if (arg === "--") {
1635
+ if (dest === unknown)
1636
+ dest.push(arg);
1637
+ dest.push(...args.slice(i));
1638
+ break;
1639
+ }
1640
+ if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
1641
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
1642
+ continue;
1643
+ }
1644
+ activeVariadicOption = null;
1645
+ if (maybeOption(arg)) {
1646
+ const option = this._findOption(arg);
1647
+ if (option) {
1648
+ if (option.required) {
1649
+ const value = args[i++];
1650
+ if (value === undefined)
1651
+ this.optionMissingArgument(option);
1652
+ this.emit(`option:${option.name()}`, value);
1653
+ } else if (option.optional) {
1654
+ let value = null;
1655
+ if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) {
1656
+ value = args[i++];
1657
+ }
1658
+ this.emit(`option:${option.name()}`, value);
1659
+ } else {
1660
+ this.emit(`option:${option.name()}`);
1661
+ }
1662
+ activeVariadicOption = option.variadic ? option : null;
1663
+ continue;
1664
+ }
1665
+ }
1666
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
1667
+ const option = this._findOption(`-${arg[1]}`);
1668
+ if (option) {
1669
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
1670
+ this.emit(`option:${option.name()}`, arg.slice(2));
1671
+ } else {
1672
+ this.emit(`option:${option.name()}`);
1673
+ activeGroup = `-${arg.slice(2)}`;
1674
+ }
1675
+ continue;
1676
+ }
1677
+ }
1678
+ if (/^--[^=]+=/.test(arg)) {
1679
+ const index = arg.indexOf("=");
1680
+ const option = this._findOption(arg.slice(0, index));
1681
+ if (option && (option.required || option.optional)) {
1682
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
1683
+ continue;
1684
+ }
1685
+ }
1686
+ if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) {
1687
+ dest = unknown;
1688
+ }
1689
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
1690
+ if (this._findCommand(arg)) {
1691
+ operands.push(arg);
1692
+ unknown.push(...args.slice(i));
1693
+ break;
1694
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
1695
+ operands.push(arg, ...args.slice(i));
1696
+ break;
1697
+ } else if (this._defaultCommandName) {
1698
+ unknown.push(arg, ...args.slice(i));
1699
+ break;
1700
+ }
1701
+ }
1702
+ if (this._passThroughOptions) {
1703
+ dest.push(arg, ...args.slice(i));
1704
+ break;
1705
+ }
1706
+ dest.push(arg);
1707
+ }
1708
+ return { operands, unknown };
1709
+ }
1710
+ opts() {
1711
+ if (this._storeOptionsAsProperties) {
1712
+ const result = {};
1713
+ const len = this.options.length;
1714
+ for (let i = 0;i < len; i++) {
1715
+ const key = this.options[i].attributeName();
1716
+ result[key] = key === this._versionOptionName ? this._version : this[key];
1717
+ }
1718
+ return result;
1719
+ }
1720
+ return this._optionValues;
1721
+ }
1722
+ optsWithGlobals() {
1723
+ return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
1724
+ }
1725
+ error(message, errorOptions) {
1726
+ this._outputConfiguration.outputError(`${message}
1727
+ `, this._outputConfiguration.writeErr);
1728
+ if (typeof this._showHelpAfterError === "string") {
1729
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
1730
+ `);
1731
+ } else if (this._showHelpAfterError) {
1732
+ this._outputConfiguration.writeErr(`
1733
+ `);
1734
+ this.outputHelp({ error: true });
1735
+ }
1736
+ const config = errorOptions || {};
1737
+ const exitCode = config.exitCode || 1;
1738
+ const code = config.code || "commander.error";
1739
+ this._exit(exitCode, code, message);
1740
+ }
1741
+ _parseOptionsEnv() {
1742
+ this.options.forEach((option) => {
1743
+ if (option.envVar && option.envVar in process2.env) {
1744
+ const optionKey = option.attributeName();
1745
+ if (this.getOptionValue(optionKey) === undefined || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
1746
+ if (option.required || option.optional) {
1747
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
1748
+ } else {
1749
+ this.emit(`optionEnv:${option.name()}`);
1750
+ }
1751
+ }
1752
+ }
1753
+ });
1754
+ }
1755
+ _parseOptionsImplied() {
1756
+ const dualHelper = new DualOptions(this.options);
1757
+ const hasCustomOptionValue = (optionKey) => {
1758
+ return this.getOptionValue(optionKey) !== undefined && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
1759
+ };
1760
+ this.options.filter((option) => option.implied !== undefined && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
1761
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
1762
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
1763
+ });
1764
+ });
1765
+ }
1766
+ missingArgument(name) {
1767
+ const message = `error: missing required argument '${name}'`;
1768
+ this.error(message, { code: "commander.missingArgument" });
1769
+ }
1770
+ optionMissingArgument(option) {
1771
+ const message = `error: option '${option.flags}' argument missing`;
1772
+ this.error(message, { code: "commander.optionMissingArgument" });
1773
+ }
1774
+ missingMandatoryOptionValue(option) {
1775
+ const message = `error: required option '${option.flags}' not specified`;
1776
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
1777
+ }
1778
+ _conflictingOption(option, conflictingOption) {
1779
+ const findBestOptionFromValue = (option2) => {
1780
+ const optionKey = option2.attributeName();
1781
+ const optionValue = this.getOptionValue(optionKey);
1782
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
1783
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
1784
+ if (negativeOption && (negativeOption.presetArg === undefined && optionValue === false || negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)) {
1785
+ return negativeOption;
1786
+ }
1787
+ return positiveOption || option2;
1788
+ };
1789
+ const getErrorMessage = (option2) => {
1790
+ const bestOption = findBestOptionFromValue(option2);
1791
+ const optionKey = bestOption.attributeName();
1792
+ const source = this.getOptionValueSource(optionKey);
1793
+ if (source === "env") {
1794
+ return `environment variable '${bestOption.envVar}'`;
1795
+ }
1796
+ return `option '${bestOption.flags}'`;
1797
+ };
1798
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
1799
+ this.error(message, { code: "commander.conflictingOption" });
1800
+ }
1801
+ unknownOption(flag) {
1802
+ if (this._allowUnknownOption)
1803
+ return;
1804
+ let suggestion = "";
1805
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
1806
+ let candidateFlags = [];
1807
+ let command = this;
1808
+ do {
1809
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
1810
+ candidateFlags = candidateFlags.concat(moreFlags);
1811
+ command = command.parent;
1812
+ } while (command && !command._enablePositionalOptions);
1813
+ suggestion = suggestSimilar(flag, candidateFlags);
1814
+ }
1815
+ const message = `error: unknown option '${flag}'${suggestion}`;
1816
+ this.error(message, { code: "commander.unknownOption" });
1817
+ }
1818
+ _excessArguments(receivedArgs) {
1819
+ if (this._allowExcessArguments)
1820
+ return;
1821
+ const expected = this.registeredArguments.length;
1822
+ const s = expected === 1 ? "" : "s";
1823
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
1824
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
1825
+ this.error(message, { code: "commander.excessArguments" });
1826
+ }
1827
+ unknownCommand() {
1828
+ const unknownName = this.args[0];
1829
+ let suggestion = "";
1830
+ if (this._showSuggestionAfterError) {
1831
+ const candidateNames = [];
1832
+ this.createHelp().visibleCommands(this).forEach((command) => {
1833
+ candidateNames.push(command.name());
1834
+ if (command.alias())
1835
+ candidateNames.push(command.alias());
1836
+ });
1837
+ suggestion = suggestSimilar(unknownName, candidateNames);
1838
+ }
1839
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
1840
+ this.error(message, { code: "commander.unknownCommand" });
1841
+ }
1842
+ version(str, flags, description) {
1843
+ if (str === undefined)
1844
+ return this._version;
1845
+ this._version = str;
1846
+ flags = flags || "-V, --version";
1847
+ description = description || "output the version number";
1848
+ const versionOption = this.createOption(flags, description);
1849
+ this._versionOptionName = versionOption.attributeName();
1850
+ this._registerOption(versionOption);
1851
+ this.on("option:" + versionOption.name(), () => {
1852
+ this._outputConfiguration.writeOut(`${str}
1853
+ `);
1854
+ this._exit(0, "commander.version", str);
1855
+ });
1856
+ return this;
1857
+ }
1858
+ description(str, argsDescription) {
1859
+ if (str === undefined && argsDescription === undefined)
1860
+ return this._description;
1861
+ this._description = str;
1862
+ if (argsDescription) {
1863
+ this._argsDescription = argsDescription;
1864
+ }
1865
+ return this;
1866
+ }
1867
+ summary(str) {
1868
+ if (str === undefined)
1869
+ return this._summary;
1870
+ this._summary = str;
1871
+ return this;
1872
+ }
1873
+ alias(alias) {
1874
+ if (alias === undefined)
1875
+ return this._aliases[0];
1876
+ let command = this;
1877
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
1878
+ command = this.commands[this.commands.length - 1];
1879
+ }
1880
+ if (alias === command._name)
1881
+ throw new Error("Command alias can't be the same as its name");
1882
+ const matchingCommand = this.parent?._findCommand(alias);
1883
+ if (matchingCommand) {
1884
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
1885
+ throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
1886
+ }
1887
+ command._aliases.push(alias);
1888
+ return this;
1889
+ }
1890
+ aliases(aliases) {
1891
+ if (aliases === undefined)
1892
+ return this._aliases;
1893
+ aliases.forEach((alias) => this.alias(alias));
1894
+ return this;
1895
+ }
1896
+ usage(str) {
1897
+ if (str === undefined) {
1898
+ if (this._usage)
1899
+ return this._usage;
1900
+ const args = this.registeredArguments.map((arg) => {
1901
+ return humanReadableArgName(arg);
1902
+ });
1903
+ return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
1904
+ }
1905
+ this._usage = str;
1906
+ return this;
1907
+ }
1908
+ name(str) {
1909
+ if (str === undefined)
1910
+ return this._name;
1911
+ this._name = str;
1912
+ return this;
1913
+ }
1914
+ helpGroup(heading) {
1915
+ if (heading === undefined)
1916
+ return this._helpGroupHeading ?? "";
1917
+ this._helpGroupHeading = heading;
1918
+ return this;
1919
+ }
1920
+ commandsGroup(heading) {
1921
+ if (heading === undefined)
1922
+ return this._defaultCommandGroup ?? "";
1923
+ this._defaultCommandGroup = heading;
1924
+ return this;
1925
+ }
1926
+ optionsGroup(heading) {
1927
+ if (heading === undefined)
1928
+ return this._defaultOptionGroup ?? "";
1929
+ this._defaultOptionGroup = heading;
1930
+ return this;
1931
+ }
1932
+ _initOptionGroup(option) {
1933
+ if (this._defaultOptionGroup && !option.helpGroupHeading)
1934
+ option.helpGroup(this._defaultOptionGroup);
1935
+ }
1936
+ _initCommandGroup(cmd) {
1937
+ if (this._defaultCommandGroup && !cmd.helpGroup())
1938
+ cmd.helpGroup(this._defaultCommandGroup);
1939
+ }
1940
+ nameFromFilename(filename) {
1941
+ this._name = path.basename(filename, path.extname(filename));
1942
+ return this;
1943
+ }
1944
+ executableDir(path2) {
1945
+ if (path2 === undefined)
1946
+ return this._executableDir;
1947
+ this._executableDir = path2;
1948
+ return this;
1949
+ }
1950
+ helpInformation(contextOptions) {
1951
+ const helper = this.createHelp();
1952
+ const context = this._getOutputContext(contextOptions);
1953
+ helper.prepareContext({
1954
+ error: context.error,
1955
+ helpWidth: context.helpWidth,
1956
+ outputHasColors: context.hasColors
1957
+ });
1958
+ const text = helper.formatHelp(this, helper);
1959
+ if (context.hasColors)
1960
+ return text;
1961
+ return this._outputConfiguration.stripColor(text);
1962
+ }
1963
+ _getOutputContext(contextOptions) {
1964
+ contextOptions = contextOptions || {};
1965
+ const error = !!contextOptions.error;
1966
+ let baseWrite;
1967
+ let hasColors;
1968
+ let helpWidth;
1969
+ if (error) {
1970
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
1971
+ hasColors = this._outputConfiguration.getErrHasColors();
1972
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
1973
+ } else {
1974
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
1975
+ hasColors = this._outputConfiguration.getOutHasColors();
1976
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
1977
+ }
1978
+ const write = (str) => {
1979
+ if (!hasColors)
1980
+ str = this._outputConfiguration.stripColor(str);
1981
+ return baseWrite(str);
1982
+ };
1983
+ return { error, write, hasColors, helpWidth };
1984
+ }
1985
+ outputHelp(contextOptions) {
1986
+ let deprecatedCallback;
1987
+ if (typeof contextOptions === "function") {
1988
+ deprecatedCallback = contextOptions;
1989
+ contextOptions = undefined;
1990
+ }
1991
+ const outputContext = this._getOutputContext(contextOptions);
1992
+ const eventContext = {
1993
+ error: outputContext.error,
1994
+ write: outputContext.write,
1995
+ command: this
1996
+ };
1997
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
1998
+ this.emit("beforeHelp", eventContext);
1999
+ let helpInformation = this.helpInformation({ error: outputContext.error });
2000
+ if (deprecatedCallback) {
2001
+ helpInformation = deprecatedCallback(helpInformation);
2002
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
2003
+ throw new Error("outputHelp callback must return a string or a Buffer");
2004
+ }
2005
+ }
2006
+ outputContext.write(helpInformation);
2007
+ if (this._getHelpOption()?.long) {
2008
+ this.emit(this._getHelpOption().long);
2009
+ }
2010
+ this.emit("afterHelp", eventContext);
2011
+ this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
2012
+ }
2013
+ helpOption(flags, description) {
2014
+ if (typeof flags === "boolean") {
2015
+ if (flags) {
2016
+ if (this._helpOption === null)
2017
+ this._helpOption = undefined;
2018
+ if (this._defaultOptionGroup) {
2019
+ this._initOptionGroup(this._getHelpOption());
2020
+ }
2021
+ } else {
2022
+ this._helpOption = null;
2023
+ }
2024
+ return this;
2025
+ }
2026
+ this._helpOption = this.createOption(flags ?? "-h, --help", description ?? "display help for command");
2027
+ if (flags || description)
2028
+ this._initOptionGroup(this._helpOption);
2029
+ return this;
2030
+ }
2031
+ _getHelpOption() {
2032
+ if (this._helpOption === undefined) {
2033
+ this.helpOption(undefined, undefined);
2034
+ }
2035
+ return this._helpOption;
2036
+ }
2037
+ addHelpOption(option) {
2038
+ this._helpOption = option;
2039
+ this._initOptionGroup(option);
2040
+ return this;
2041
+ }
2042
+ help(contextOptions) {
2043
+ this.outputHelp(contextOptions);
2044
+ let exitCode = Number(process2.exitCode ?? 0);
2045
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
2046
+ exitCode = 1;
2047
+ }
2048
+ this._exit(exitCode, "commander.help", "(outputHelp)");
2049
+ }
2050
+ addHelpText(position, text) {
2051
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
2052
+ if (!allowedValues.includes(position)) {
2053
+ throw new Error(`Unexpected value for position to addHelpText.
2054
+ Expecting one of '${allowedValues.join("', '")}'`);
2055
+ }
2056
+ const helpEvent = `${position}Help`;
2057
+ this.on(helpEvent, (context) => {
2058
+ let helpStr;
2059
+ if (typeof text === "function") {
2060
+ helpStr = text({ error: context.error, command: context.command });
2061
+ } else {
2062
+ helpStr = text;
2063
+ }
2064
+ if (helpStr) {
2065
+ context.write(`${helpStr}
2066
+ `);
2067
+ }
2068
+ });
2069
+ return this;
2070
+ }
2071
+ _outputHelpIfRequested(args) {
2072
+ const helpOption = this._getHelpOption();
2073
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
2074
+ if (helpRequested) {
2075
+ this.outputHelp();
2076
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
2077
+ }
2078
+ }
2079
+ }
2080
+ function incrementNodeInspectorPort(args) {
2081
+ return args.map((arg) => {
2082
+ if (!arg.startsWith("--inspect")) {
2083
+ return arg;
2084
+ }
2085
+ let debugOption;
2086
+ let debugHost = "127.0.0.1";
2087
+ let debugPort = "9229";
2088
+ let match;
2089
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
2090
+ debugOption = match[1];
2091
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2092
+ debugOption = match[1];
2093
+ if (/^\d+$/.test(match[3])) {
2094
+ debugPort = match[3];
2095
+ } else {
2096
+ debugHost = match[3];
2097
+ }
2098
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
2099
+ debugOption = match[1];
2100
+ debugHost = match[3];
2101
+ debugPort = match[4];
2102
+ }
2103
+ if (debugOption && debugPort !== "0") {
2104
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2105
+ }
2106
+ return arg;
2107
+ });
2108
+ }
2109
+ function useColor() {
2110
+ if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
2111
+ return false;
2112
+ if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== undefined)
2113
+ return true;
2114
+ return;
2115
+ }
2116
+ exports.Command = Command;
2117
+ exports.useColor = useColor;
2118
+ });
2119
+
2120
+ // ../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/index.js
2121
+ var require_commander = __commonJS((exports) => {
2122
+ var { Argument } = require_argument();
2123
+ var { Command } = require_command();
2124
+ var { CommanderError, InvalidArgumentError } = require_error();
2125
+ var { Help } = require_help();
2126
+ var { Option } = require_option();
2127
+ exports.program = new Command;
2128
+ exports.createCommand = (name) => new Command(name);
2129
+ exports.createOption = (flags, description) => new Option(flags, description);
2130
+ exports.createArgument = (name, description) => new Argument(name, description);
2131
+ exports.Command = Command;
2132
+ exports.Option = Option;
2133
+ exports.Argument = Argument;
2134
+ exports.Help = Help;
2135
+ exports.CommanderError = CommanderError;
2136
+ exports.InvalidArgumentError = InvalidArgumentError;
2137
+ exports.InvalidOptionArgumentError = InvalidArgumentError;
2138
+ });
2139
+
2140
+ // ../../node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js
2141
+ var require_ms = __commonJS((exports, module) => {
2142
+ var s = 1000;
2143
+ var m = s * 60;
2144
+ var h = m * 60;
2145
+ var d = h * 24;
2146
+ var w = d * 7;
2147
+ var y = d * 365.25;
2148
+ module.exports = function(val, options) {
2149
+ options = options || {};
2150
+ var type = typeof val;
2151
+ if (type === "string" && val.length > 0) {
2152
+ return parse(val);
2153
+ } else if (type === "number" && isFinite(val)) {
2154
+ return options.long ? fmtLong(val) : fmtShort(val);
2155
+ }
2156
+ throw new Error("val is not a non-empty string or a valid number. val=" + JSON.stringify(val));
2157
+ };
2158
+ function parse(str) {
2159
+ str = String(str);
2160
+ if (str.length > 100) {
2161
+ return;
2162
+ }
2163
+ var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str);
2164
+ if (!match) {
2165
+ return;
2166
+ }
2167
+ var n = parseFloat(match[1]);
2168
+ var type = (match[2] || "ms").toLowerCase();
2169
+ switch (type) {
2170
+ case "years":
2171
+ case "year":
2172
+ case "yrs":
2173
+ case "yr":
2174
+ case "y":
2175
+ return n * y;
2176
+ case "weeks":
2177
+ case "week":
2178
+ case "w":
2179
+ return n * w;
2180
+ case "days":
2181
+ case "day":
2182
+ case "d":
2183
+ return n * d;
2184
+ case "hours":
2185
+ case "hour":
2186
+ case "hrs":
2187
+ case "hr":
2188
+ case "h":
2189
+ return n * h;
2190
+ case "minutes":
2191
+ case "minute":
2192
+ case "mins":
2193
+ case "min":
2194
+ case "m":
2195
+ return n * m;
2196
+ case "seconds":
2197
+ case "second":
2198
+ case "secs":
2199
+ case "sec":
2200
+ case "s":
2201
+ return n * s;
2202
+ case "milliseconds":
2203
+ case "millisecond":
2204
+ case "msecs":
2205
+ case "msec":
2206
+ case "ms":
2207
+ return n;
2208
+ default:
2209
+ return;
2210
+ }
2211
+ }
2212
+ function fmtShort(ms) {
2213
+ var msAbs = Math.abs(ms);
2214
+ if (msAbs >= d) {
2215
+ return Math.round(ms / d) + "d";
2216
+ }
2217
+ if (msAbs >= h) {
2218
+ return Math.round(ms / h) + "h";
2219
+ }
2220
+ if (msAbs >= m) {
2221
+ return Math.round(ms / m) + "m";
2222
+ }
2223
+ if (msAbs >= s) {
2224
+ return Math.round(ms / s) + "s";
2225
+ }
2226
+ return ms + "ms";
2227
+ }
2228
+ function fmtLong(ms) {
2229
+ var msAbs = Math.abs(ms);
2230
+ if (msAbs >= d) {
2231
+ return plural(ms, msAbs, d, "day");
2232
+ }
2233
+ if (msAbs >= h) {
2234
+ return plural(ms, msAbs, h, "hour");
2235
+ }
2236
+ if (msAbs >= m) {
2237
+ return plural(ms, msAbs, m, "minute");
2238
+ }
2239
+ if (msAbs >= s) {
2240
+ return plural(ms, msAbs, s, "second");
2241
+ }
2242
+ return ms + " ms";
2243
+ }
2244
+ function plural(ms, msAbs, n, name) {
2245
+ var isPlural = msAbs >= n * 1.5;
2246
+ return Math.round(ms / n) + " " + name + (isPlural ? "s" : "");
2247
+ }
2248
+ });
2249
+
2250
+ // ../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/common.js
2251
+ var require_common = __commonJS((exports, module) => {
2252
+ function setup(env) {
2253
+ createDebug.debug = createDebug;
2254
+ createDebug.default = createDebug;
2255
+ createDebug.coerce = coerce;
2256
+ createDebug.disable = disable;
2257
+ createDebug.enable = enable;
2258
+ createDebug.enabled = enabled;
2259
+ createDebug.humanize = require_ms();
2260
+ createDebug.destroy = destroy;
2261
+ Object.keys(env).forEach((key) => {
2262
+ createDebug[key] = env[key];
2263
+ });
2264
+ createDebug.names = [];
2265
+ createDebug.skips = [];
2266
+ createDebug.formatters = {};
2267
+ function selectColor(namespace) {
2268
+ let hash = 0;
2269
+ for (let i = 0;i < namespace.length; i++) {
2270
+ hash = (hash << 5) - hash + namespace.charCodeAt(i);
2271
+ hash |= 0;
2272
+ }
2273
+ return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
2274
+ }
2275
+ createDebug.selectColor = selectColor;
2276
+ function createDebug(namespace) {
2277
+ let prevTime;
2278
+ let enableOverride = null;
2279
+ let namespacesCache;
2280
+ let enabledCache;
2281
+ function debug(...args) {
2282
+ if (!debug.enabled) {
2283
+ return;
2284
+ }
2285
+ const self = debug;
2286
+ const curr = Number(new Date);
2287
+ const ms = curr - (prevTime || curr);
2288
+ self.diff = ms;
2289
+ self.prev = prevTime;
2290
+ self.curr = curr;
2291
+ prevTime = curr;
2292
+ args[0] = createDebug.coerce(args[0]);
2293
+ if (typeof args[0] !== "string") {
2294
+ args.unshift("%O");
2295
+ }
2296
+ let index = 0;
2297
+ args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
2298
+ if (match === "%%") {
2299
+ return "%";
2300
+ }
2301
+ index++;
2302
+ const formatter = createDebug.formatters[format];
2303
+ if (typeof formatter === "function") {
2304
+ const val = args[index];
2305
+ match = formatter.call(self, val);
2306
+ args.splice(index, 1);
2307
+ index--;
2308
+ }
2309
+ return match;
2310
+ });
2311
+ createDebug.formatArgs.call(self, args);
2312
+ const logFn = self.log || createDebug.log;
2313
+ logFn.apply(self, args);
2314
+ }
2315
+ debug.namespace = namespace;
2316
+ debug.useColors = createDebug.useColors();
2317
+ debug.color = createDebug.selectColor(namespace);
2318
+ debug.extend = extend;
2319
+ debug.destroy = createDebug.destroy;
2320
+ Object.defineProperty(debug, "enabled", {
2321
+ enumerable: true,
2322
+ configurable: false,
2323
+ get: () => {
2324
+ if (enableOverride !== null) {
2325
+ return enableOverride;
2326
+ }
2327
+ if (namespacesCache !== createDebug.namespaces) {
2328
+ namespacesCache = createDebug.namespaces;
2329
+ enabledCache = createDebug.enabled(namespace);
2330
+ }
2331
+ return enabledCache;
2332
+ },
2333
+ set: (v) => {
2334
+ enableOverride = v;
2335
+ }
2336
+ });
2337
+ if (typeof createDebug.init === "function") {
2338
+ createDebug.init(debug);
2339
+ }
2340
+ return debug;
2341
+ }
2342
+ function extend(namespace, delimiter) {
2343
+ const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace);
2344
+ newDebug.log = this.log;
2345
+ return newDebug;
2346
+ }
2347
+ function enable(namespaces) {
2348
+ createDebug.save(namespaces);
2349
+ createDebug.namespaces = namespaces;
2350
+ createDebug.names = [];
2351
+ createDebug.skips = [];
2352
+ const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean);
2353
+ for (const ns of split) {
2354
+ if (ns[0] === "-") {
2355
+ createDebug.skips.push(ns.slice(1));
2356
+ } else {
2357
+ createDebug.names.push(ns);
2358
+ }
2359
+ }
2360
+ }
2361
+ function matchesTemplate(search, template) {
2362
+ let searchIndex = 0;
2363
+ let templateIndex = 0;
2364
+ let starIndex = -1;
2365
+ let matchIndex = 0;
2366
+ while (searchIndex < search.length) {
2367
+ if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) {
2368
+ if (template[templateIndex] === "*") {
2369
+ starIndex = templateIndex;
2370
+ matchIndex = searchIndex;
2371
+ templateIndex++;
2372
+ } else {
2373
+ searchIndex++;
2374
+ templateIndex++;
2375
+ }
2376
+ } else if (starIndex !== -1) {
2377
+ templateIndex = starIndex + 1;
2378
+ matchIndex++;
2379
+ searchIndex = matchIndex;
2380
+ } else {
2381
+ return false;
2382
+ }
2383
+ }
2384
+ while (templateIndex < template.length && template[templateIndex] === "*") {
2385
+ templateIndex++;
2386
+ }
2387
+ return templateIndex === template.length;
2388
+ }
2389
+ function disable() {
2390
+ const namespaces = [
2391
+ ...createDebug.names,
2392
+ ...createDebug.skips.map((namespace) => "-" + namespace)
2393
+ ].join(",");
2394
+ createDebug.enable("");
2395
+ return namespaces;
2396
+ }
2397
+ function enabled(name) {
2398
+ for (const skip of createDebug.skips) {
2399
+ if (matchesTemplate(name, skip)) {
2400
+ return false;
2401
+ }
2402
+ }
2403
+ for (const ns of createDebug.names) {
2404
+ if (matchesTemplate(name, ns)) {
2405
+ return true;
2406
+ }
2407
+ }
2408
+ return false;
2409
+ }
2410
+ function coerce(val) {
2411
+ if (val instanceof Error) {
2412
+ return val.stack || val.message;
2413
+ }
2414
+ return val;
2415
+ }
2416
+ function destroy() {
2417
+ console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
2418
+ }
2419
+ createDebug.enable(createDebug.load());
2420
+ return createDebug;
2421
+ }
2422
+ module.exports = setup;
2423
+ });
2424
+
2425
+ // ../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/browser.js
2426
+ var require_browser = __commonJS((exports, module) => {
2427
+ exports.formatArgs = formatArgs;
2428
+ exports.save = save;
2429
+ exports.load = load;
2430
+ exports.useColors = useColors;
2431
+ exports.storage = localstorage();
2432
+ exports.destroy = (() => {
2433
+ let warned = false;
2434
+ return () => {
2435
+ if (!warned) {
2436
+ warned = true;
2437
+ console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
2438
+ }
2439
+ };
2440
+ })();
2441
+ exports.colors = [
2442
+ "#0000CC",
2443
+ "#0000FF",
2444
+ "#0033CC",
2445
+ "#0033FF",
2446
+ "#0066CC",
2447
+ "#0066FF",
2448
+ "#0099CC",
2449
+ "#0099FF",
2450
+ "#00CC00",
2451
+ "#00CC33",
2452
+ "#00CC66",
2453
+ "#00CC99",
2454
+ "#00CCCC",
2455
+ "#00CCFF",
2456
+ "#3300CC",
2457
+ "#3300FF",
2458
+ "#3333CC",
2459
+ "#3333FF",
2460
+ "#3366CC",
2461
+ "#3366FF",
2462
+ "#3399CC",
2463
+ "#3399FF",
2464
+ "#33CC00",
2465
+ "#33CC33",
2466
+ "#33CC66",
2467
+ "#33CC99",
2468
+ "#33CCCC",
2469
+ "#33CCFF",
2470
+ "#6600CC",
2471
+ "#6600FF",
2472
+ "#6633CC",
2473
+ "#6633FF",
2474
+ "#66CC00",
2475
+ "#66CC33",
2476
+ "#9900CC",
2477
+ "#9900FF",
2478
+ "#9933CC",
2479
+ "#9933FF",
2480
+ "#99CC00",
2481
+ "#99CC33",
2482
+ "#CC0000",
2483
+ "#CC0033",
2484
+ "#CC0066",
2485
+ "#CC0099",
2486
+ "#CC00CC",
2487
+ "#CC00FF",
2488
+ "#CC3300",
2489
+ "#CC3333",
2490
+ "#CC3366",
2491
+ "#CC3399",
2492
+ "#CC33CC",
2493
+ "#CC33FF",
2494
+ "#CC6600",
2495
+ "#CC6633",
2496
+ "#CC9900",
2497
+ "#CC9933",
2498
+ "#CCCC00",
2499
+ "#CCCC33",
2500
+ "#FF0000",
2501
+ "#FF0033",
2502
+ "#FF0066",
2503
+ "#FF0099",
2504
+ "#FF00CC",
2505
+ "#FF00FF",
2506
+ "#FF3300",
2507
+ "#FF3333",
2508
+ "#FF3366",
2509
+ "#FF3399",
2510
+ "#FF33CC",
2511
+ "#FF33FF",
2512
+ "#FF6600",
2513
+ "#FF6633",
2514
+ "#FF9900",
2515
+ "#FF9933",
2516
+ "#FFCC00",
2517
+ "#FFCC33"
2518
+ ];
2519
+ function useColors() {
2520
+ if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) {
2521
+ return true;
2522
+ }
2523
+ if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
2524
+ return false;
2525
+ }
2526
+ let m;
2527
+ return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
2528
+ }
2529
+ function formatArgs(args) {
2530
+ args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module.exports.humanize(this.diff);
2531
+ if (!this.useColors) {
2532
+ return;
2533
+ }
2534
+ const c = "color: " + this.color;
2535
+ args.splice(1, 0, c, "color: inherit");
2536
+ let index = 0;
2537
+ let lastC = 0;
2538
+ args[0].replace(/%[a-zA-Z%]/g, (match) => {
2539
+ if (match === "%%") {
2540
+ return;
2541
+ }
2542
+ index++;
2543
+ if (match === "%c") {
2544
+ lastC = index;
2545
+ }
2546
+ });
2547
+ args.splice(lastC, 0, c);
2548
+ }
2549
+ exports.log = console.debug || console.log || (() => {});
2550
+ function save(namespaces) {
2551
+ try {
2552
+ if (namespaces) {
2553
+ exports.storage.setItem("debug", namespaces);
2554
+ } else {
2555
+ exports.storage.removeItem("debug");
2556
+ }
2557
+ } catch (error) {}
2558
+ }
2559
+ function load() {
2560
+ let r;
2561
+ try {
2562
+ r = exports.storage.getItem("debug") || exports.storage.getItem("DEBUG");
2563
+ } catch (error) {}
2564
+ if (!r && typeof process !== "undefined" && "env" in process) {
2565
+ r = process.env.DEBUG;
2566
+ }
2567
+ return r;
2568
+ }
2569
+ function localstorage() {
2570
+ try {
2571
+ return localStorage;
2572
+ } catch (error) {}
2573
+ }
2574
+ module.exports = require_common()(exports);
2575
+ var { formatters } = module.exports;
2576
+ formatters.j = function(v) {
2577
+ try {
2578
+ return JSON.stringify(v);
2579
+ } catch (error) {
2580
+ return "[UnexpectedJSONParseError]: " + error.message;
2581
+ }
2582
+ };
2583
+ });
2584
+
2585
+ // ../../node_modules/.pnpm/supports-color@10.2.2/node_modules/supports-color/index.js
2586
+ var exports_supports_color = {};
2587
+ __export(exports_supports_color, {
2588
+ default: () => supports_color_default,
2589
+ createSupportsColor: () => createSupportsColor
2590
+ });
2591
+ import process2 from "process";
2592
+ import os from "os";
2593
+ import tty from "tty";
2594
+ function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process2.argv) {
2595
+ const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
2596
+ const position = argv.indexOf(prefix + flag);
2597
+ const terminatorPosition = argv.indexOf("--");
2598
+ return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
2599
+ }
2600
+ function envForceColor() {
2601
+ if (!("FORCE_COLOR" in env)) {
2602
+ return;
2603
+ }
2604
+ if (env.FORCE_COLOR === "true") {
2605
+ return 1;
2606
+ }
2607
+ if (env.FORCE_COLOR === "false") {
2608
+ return 0;
2609
+ }
2610
+ if (env.FORCE_COLOR.length === 0) {
2611
+ return 1;
2612
+ }
2613
+ const level = Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
2614
+ if (![0, 1, 2, 3].includes(level)) {
2615
+ return;
2616
+ }
2617
+ return level;
2618
+ }
2619
+ function translateLevel(level) {
2620
+ if (level === 0) {
2621
+ return false;
2622
+ }
2623
+ return {
2624
+ level,
2625
+ hasBasic: true,
2626
+ has256: level >= 2,
2627
+ has16m: level >= 3
2628
+ };
2629
+ }
2630
+ function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
2631
+ const noFlagForceColor = envForceColor();
2632
+ if (noFlagForceColor !== undefined) {
2633
+ flagForceColor = noFlagForceColor;
2634
+ }
2635
+ const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
2636
+ if (forceColor === 0) {
2637
+ return 0;
2638
+ }
2639
+ if (sniffFlags) {
2640
+ if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
2641
+ return 3;
2642
+ }
2643
+ if (hasFlag("color=256")) {
2644
+ return 2;
2645
+ }
2646
+ }
2647
+ if ("TF_BUILD" in env && "AGENT_NAME" in env) {
2648
+ return 1;
2649
+ }
2650
+ if (haveStream && !streamIsTTY && forceColor === undefined) {
2651
+ return 0;
2652
+ }
2653
+ const min = forceColor || 0;
2654
+ if (env.TERM === "dumb") {
2655
+ return min;
2656
+ }
2657
+ if (process2.platform === "win32") {
2658
+ const osRelease = os.release().split(".");
2659
+ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
2660
+ return Number(osRelease[2]) >= 14931 ? 3 : 2;
2661
+ }
2662
+ return 1;
2663
+ }
2664
+ if ("CI" in env) {
2665
+ if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => (key in env))) {
2666
+ return 3;
2667
+ }
2668
+ if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => (sign in env)) || env.CI_NAME === "codeship") {
2669
+ return 1;
2670
+ }
2671
+ return min;
2672
+ }
2673
+ if ("TEAMCITY_VERSION" in env) {
2674
+ return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
2675
+ }
2676
+ if (env.COLORTERM === "truecolor") {
2677
+ return 3;
2678
+ }
2679
+ if (env.TERM === "xterm-kitty") {
2680
+ return 3;
2681
+ }
2682
+ if (env.TERM === "xterm-ghostty") {
2683
+ return 3;
2684
+ }
2685
+ if (env.TERM === "wezterm") {
2686
+ return 3;
2687
+ }
2688
+ if ("TERM_PROGRAM" in env) {
2689
+ const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
2690
+ switch (env.TERM_PROGRAM) {
2691
+ case "iTerm.app": {
2692
+ return version >= 3 ? 3 : 2;
2693
+ }
2694
+ case "Apple_Terminal": {
2695
+ return 2;
2696
+ }
2697
+ }
2698
+ }
2699
+ if (/-256(color)?$/i.test(env.TERM)) {
2700
+ return 2;
2701
+ }
2702
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
2703
+ return 1;
2704
+ }
2705
+ if ("COLORTERM" in env) {
2706
+ return 1;
2707
+ }
2708
+ return min;
2709
+ }
2710
+ function createSupportsColor(stream, options = {}) {
2711
+ const level = _supportsColor(stream, {
2712
+ streamIsTTY: stream && stream.isTTY,
2713
+ ...options
2714
+ });
2715
+ return translateLevel(level);
2716
+ }
2717
+ var env, flagForceColor, supportsColor, supports_color_default;
2718
+ var init_supports_color = __esm(() => {
2719
+ ({ env } = process2);
2720
+ if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
2721
+ flagForceColor = 0;
2722
+ } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
2723
+ flagForceColor = 1;
2724
+ }
2725
+ supportsColor = {
2726
+ stdout: createSupportsColor({ isTTY: tty.isatty(1) }),
2727
+ stderr: createSupportsColor({ isTTY: tty.isatty(2) })
2728
+ };
2729
+ supports_color_default = supportsColor;
2730
+ });
2731
+
2732
+ // ../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/node.js
2733
+ var require_node = __commonJS((exports, module) => {
2734
+ var tty2 = __require("tty");
2735
+ var util = __require("util");
2736
+ exports.init = init;
2737
+ exports.log = log;
2738
+ exports.formatArgs = formatArgs;
2739
+ exports.save = save;
2740
+ exports.load = load;
2741
+ exports.useColors = useColors;
2742
+ exports.destroy = util.deprecate(() => {}, "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
2743
+ exports.colors = [6, 2, 3, 4, 5, 1];
2744
+ try {
2745
+ const supportsColor2 = (init_supports_color(), __toCommonJS(exports_supports_color));
2746
+ if (supportsColor2 && (supportsColor2.stderr || supportsColor2).level >= 2) {
2747
+ exports.colors = [
2748
+ 20,
2749
+ 21,
2750
+ 26,
2751
+ 27,
2752
+ 32,
2753
+ 33,
2754
+ 38,
2755
+ 39,
2756
+ 40,
2757
+ 41,
2758
+ 42,
2759
+ 43,
2760
+ 44,
2761
+ 45,
2762
+ 56,
2763
+ 57,
2764
+ 62,
2765
+ 63,
2766
+ 68,
2767
+ 69,
2768
+ 74,
2769
+ 75,
2770
+ 76,
2771
+ 77,
2772
+ 78,
2773
+ 79,
2774
+ 80,
2775
+ 81,
2776
+ 92,
2777
+ 93,
2778
+ 98,
2779
+ 99,
2780
+ 112,
2781
+ 113,
2782
+ 128,
2783
+ 129,
2784
+ 134,
2785
+ 135,
2786
+ 148,
2787
+ 149,
2788
+ 160,
2789
+ 161,
2790
+ 162,
2791
+ 163,
2792
+ 164,
2793
+ 165,
2794
+ 166,
2795
+ 167,
2796
+ 168,
2797
+ 169,
2798
+ 170,
2799
+ 171,
2800
+ 172,
2801
+ 173,
2802
+ 178,
2803
+ 179,
2804
+ 184,
2805
+ 185,
2806
+ 196,
2807
+ 197,
2808
+ 198,
2809
+ 199,
2810
+ 200,
2811
+ 201,
2812
+ 202,
2813
+ 203,
2814
+ 204,
2815
+ 205,
2816
+ 206,
2817
+ 207,
2818
+ 208,
2819
+ 209,
2820
+ 214,
2821
+ 215,
2822
+ 220,
2823
+ 221
2824
+ ];
2825
+ }
2826
+ } catch (error) {}
2827
+ exports.inspectOpts = Object.keys(process.env).filter((key) => {
2828
+ return /^debug_/i.test(key);
2829
+ }).reduce((obj, key) => {
2830
+ const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => {
2831
+ return k.toUpperCase();
2832
+ });
2833
+ let val = process.env[key];
2834
+ if (/^(yes|on|true|enabled)$/i.test(val)) {
2835
+ val = true;
2836
+ } else if (/^(no|off|false|disabled)$/i.test(val)) {
2837
+ val = false;
2838
+ } else if (val === "null") {
2839
+ val = null;
2840
+ } else {
2841
+ val = Number(val);
2842
+ }
2843
+ obj[prop] = val;
2844
+ return obj;
2845
+ }, {});
2846
+ function useColors() {
2847
+ return "colors" in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty2.isatty(process.stderr.fd);
2848
+ }
2849
+ function formatArgs(args) {
2850
+ const { namespace: name, useColors: useColors2 } = this;
2851
+ if (useColors2) {
2852
+ const c = this.color;
2853
+ const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c);
2854
+ const prefix = ` ${colorCode};1m${name} \x1B[0m`;
2855
+ args[0] = prefix + args[0].split(`
2856
+ `).join(`
2857
+ ` + prefix);
2858
+ args.push(colorCode + "m+" + module.exports.humanize(this.diff) + "\x1B[0m");
2859
+ } else {
2860
+ args[0] = getDate() + name + " " + args[0];
2861
+ }
2862
+ }
2863
+ function getDate() {
2864
+ if (exports.inspectOpts.hideDate) {
2865
+ return "";
2866
+ }
2867
+ return new Date().toISOString() + " ";
2868
+ }
2869
+ function log(...args) {
2870
+ return process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + `
2871
+ `);
2872
+ }
2873
+ function save(namespaces) {
2874
+ if (namespaces) {
2875
+ process.env.DEBUG = namespaces;
2876
+ } else {
2877
+ delete process.env.DEBUG;
2878
+ }
2879
+ }
2880
+ function load() {
2881
+ return process.env.DEBUG;
2882
+ }
2883
+ function init(debug) {
2884
+ debug.inspectOpts = {};
2885
+ const keys = Object.keys(exports.inspectOpts);
2886
+ for (let i = 0;i < keys.length; i++) {
2887
+ debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
2888
+ }
2889
+ }
2890
+ module.exports = require_common()(exports);
2891
+ var { formatters } = module.exports;
2892
+ formatters.o = function(v) {
2893
+ this.inspectOpts.colors = this.useColors;
2894
+ return util.inspect(v, this.inspectOpts).split(`
2895
+ `).map((str) => str.trim()).join(" ");
2896
+ };
2897
+ formatters.O = function(v) {
2898
+ this.inspectOpts.colors = this.useColors;
2899
+ return util.inspect(v, this.inspectOpts);
2900
+ };
2901
+ });
2902
+
2903
+ // ../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/index.js
2904
+ var require_src = __commonJS((exports, module) => {
2905
+ if (typeof process === "undefined" || process.type === "renderer" || false || process.__nwjs) {
2906
+ module.exports = require_browser();
2907
+ } else {
2908
+ module.exports = require_node();
2909
+ }
2910
+ });
2911
+
2912
+ // ../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/esm.mjs
2913
+ var import__ = __toESM(require_commander(), 1);
2914
+ var {
2915
+ program,
2916
+ createCommand,
2917
+ createArgument,
2918
+ createOption,
2919
+ CommanderError,
2920
+ InvalidArgumentError,
2921
+ InvalidOptionArgumentError,
2922
+ Command,
2923
+ Argument,
2924
+ Option,
2925
+ Help
2926
+ } = import__.default;
2927
+
2928
+ // ../../node_modules/.pnpm/neverthrow@8.2.0/node_modules/neverthrow/dist/index.es.js
2929
+ var defaultErrorConfig = {
2930
+ withStackTrace: false
2931
+ };
2932
+ var createNeverThrowError = (message, result, config = defaultErrorConfig) => {
2933
+ const data = result.isOk() ? { type: "Ok", value: result.value } : { type: "Err", value: result.error };
2934
+ const maybeStack = config.withStackTrace ? new Error().stack : undefined;
2935
+ return {
2936
+ data,
2937
+ message,
2938
+ stack: maybeStack
2939
+ };
2940
+ };
2941
+ function __awaiter(thisArg, _arguments, P, generator) {
2942
+ function adopt(value) {
2943
+ return value instanceof P ? value : new P(function(resolve) {
2944
+ resolve(value);
2945
+ });
2946
+ }
2947
+ return new (P || (P = Promise))(function(resolve, reject) {
2948
+ function fulfilled(value) {
2949
+ try {
2950
+ step(generator.next(value));
2951
+ } catch (e) {
2952
+ reject(e);
2953
+ }
2954
+ }
2955
+ function rejected(value) {
2956
+ try {
2957
+ step(generator["throw"](value));
2958
+ } catch (e) {
2959
+ reject(e);
2960
+ }
2961
+ }
2962
+ function step(result) {
2963
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
2964
+ }
2965
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
2966
+ });
2967
+ }
2968
+ function __values(o) {
2969
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
2970
+ if (m)
2971
+ return m.call(o);
2972
+ if (o && typeof o.length === "number")
2973
+ return {
2974
+ next: function() {
2975
+ if (o && i >= o.length)
2976
+ o = undefined;
2977
+ return { value: o && o[i++], done: !o };
2978
+ }
2979
+ };
2980
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
2981
+ }
2982
+ function __await(v) {
2983
+ return this instanceof __await ? (this.v = v, this) : new __await(v);
2984
+ }
2985
+ function __asyncGenerator(thisArg, _arguments, generator) {
2986
+ if (!Symbol.asyncIterator)
2987
+ throw new TypeError("Symbol.asyncIterator is not defined.");
2988
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
2989
+ return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() {
2990
+ return this;
2991
+ }, i;
2992
+ function awaitReturn(f) {
2993
+ return function(v) {
2994
+ return Promise.resolve(v).then(f, reject);
2995
+ };
2996
+ }
2997
+ function verb(n, f) {
2998
+ if (g[n]) {
2999
+ i[n] = function(v) {
3000
+ return new Promise(function(a, b) {
3001
+ q.push([n, v, a, b]) > 1 || resume(n, v);
3002
+ });
3003
+ };
3004
+ if (f)
3005
+ i[n] = f(i[n]);
3006
+ }
3007
+ }
3008
+ function resume(n, v) {
3009
+ try {
3010
+ step(g[n](v));
3011
+ } catch (e) {
3012
+ settle(q[0][3], e);
3013
+ }
3014
+ }
3015
+ function step(r) {
3016
+ r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
3017
+ }
3018
+ function fulfill(value) {
3019
+ resume("next", value);
3020
+ }
3021
+ function reject(value) {
3022
+ resume("throw", value);
3023
+ }
3024
+ function settle(f, v) {
3025
+ if (f(v), q.shift(), q.length)
3026
+ resume(q[0][0], q[0][1]);
3027
+ }
3028
+ }
3029
+ function __asyncDelegator(o) {
3030
+ var i, p;
3031
+ return i = {}, verb("next"), verb("throw", function(e) {
3032
+ throw e;
3033
+ }), verb("return"), i[Symbol.iterator] = function() {
3034
+ return this;
3035
+ }, i;
3036
+ function verb(n, f) {
3037
+ i[n] = o[n] ? function(v) {
3038
+ return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v;
3039
+ } : f;
3040
+ }
3041
+ }
3042
+ function __asyncValues(o) {
3043
+ if (!Symbol.asyncIterator)
3044
+ throw new TypeError("Symbol.asyncIterator is not defined.");
3045
+ var m = o[Symbol.asyncIterator], i;
3046
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
3047
+ return this;
3048
+ }, i);
3049
+ function verb(n) {
3050
+ i[n] = o[n] && function(v) {
3051
+ return new Promise(function(resolve, reject) {
3052
+ v = o[n](v), settle(resolve, reject, v.done, v.value);
3053
+ });
3054
+ };
3055
+ }
3056
+ function settle(resolve, reject, d, v) {
3057
+ Promise.resolve(v).then(function(v2) {
3058
+ resolve({ value: v2, done: d });
3059
+ }, reject);
3060
+ }
3061
+ }
3062
+ class ResultAsync {
3063
+ constructor(res) {
3064
+ this._promise = res;
3065
+ }
3066
+ static fromSafePromise(promise) {
3067
+ const newPromise = promise.then((value) => new Ok(value));
3068
+ return new ResultAsync(newPromise);
3069
+ }
3070
+ static fromPromise(promise, errorFn) {
3071
+ const newPromise = promise.then((value) => new Ok(value)).catch((e) => new Err(errorFn(e)));
3072
+ return new ResultAsync(newPromise);
3073
+ }
3074
+ static fromThrowable(fn, errorFn) {
3075
+ return (...args) => {
3076
+ return new ResultAsync((() => __awaiter(this, undefined, undefined, function* () {
3077
+ try {
3078
+ return new Ok(yield fn(...args));
3079
+ } catch (error) {
3080
+ return new Err(errorFn ? errorFn(error) : error);
3081
+ }
3082
+ }))());
3083
+ };
3084
+ }
3085
+ static combine(asyncResultList) {
3086
+ return combineResultAsyncList(asyncResultList);
3087
+ }
3088
+ static combineWithAllErrors(asyncResultList) {
3089
+ return combineResultAsyncListWithAllErrors(asyncResultList);
3090
+ }
3091
+ map(f) {
3092
+ return new ResultAsync(this._promise.then((res) => __awaiter(this, undefined, undefined, function* () {
3093
+ if (res.isErr()) {
3094
+ return new Err(res.error);
3095
+ }
3096
+ return new Ok(yield f(res.value));
3097
+ })));
3098
+ }
3099
+ andThrough(f) {
3100
+ return new ResultAsync(this._promise.then((res) => __awaiter(this, undefined, undefined, function* () {
3101
+ if (res.isErr()) {
3102
+ return new Err(res.error);
3103
+ }
3104
+ const newRes = yield f(res.value);
3105
+ if (newRes.isErr()) {
3106
+ return new Err(newRes.error);
3107
+ }
3108
+ return new Ok(res.value);
3109
+ })));
3110
+ }
3111
+ andTee(f) {
3112
+ return new ResultAsync(this._promise.then((res) => __awaiter(this, undefined, undefined, function* () {
3113
+ if (res.isErr()) {
3114
+ return new Err(res.error);
3115
+ }
3116
+ try {
3117
+ yield f(res.value);
3118
+ } catch (e) {}
3119
+ return new Ok(res.value);
3120
+ })));
3121
+ }
3122
+ orTee(f) {
3123
+ return new ResultAsync(this._promise.then((res) => __awaiter(this, undefined, undefined, function* () {
3124
+ if (res.isOk()) {
3125
+ return new Ok(res.value);
3126
+ }
3127
+ try {
3128
+ yield f(res.error);
3129
+ } catch (e) {}
3130
+ return new Err(res.error);
3131
+ })));
3132
+ }
3133
+ mapErr(f) {
3134
+ return new ResultAsync(this._promise.then((res) => __awaiter(this, undefined, undefined, function* () {
3135
+ if (res.isOk()) {
3136
+ return new Ok(res.value);
3137
+ }
3138
+ return new Err(yield f(res.error));
3139
+ })));
3140
+ }
3141
+ andThen(f) {
3142
+ return new ResultAsync(this._promise.then((res) => {
3143
+ if (res.isErr()) {
3144
+ return new Err(res.error);
3145
+ }
3146
+ const newValue = f(res.value);
3147
+ return newValue instanceof ResultAsync ? newValue._promise : newValue;
3148
+ }));
3149
+ }
3150
+ orElse(f) {
3151
+ return new ResultAsync(this._promise.then((res) => __awaiter(this, undefined, undefined, function* () {
3152
+ if (res.isErr()) {
3153
+ return f(res.error);
3154
+ }
3155
+ return new Ok(res.value);
3156
+ })));
3157
+ }
3158
+ match(ok, _err) {
3159
+ return this._promise.then((res) => res.match(ok, _err));
3160
+ }
3161
+ unwrapOr(t) {
3162
+ return this._promise.then((res) => res.unwrapOr(t));
3163
+ }
3164
+ safeUnwrap() {
3165
+ return __asyncGenerator(this, arguments, function* safeUnwrap_1() {
3166
+ return yield __await(yield __await(yield* __asyncDelegator(__asyncValues(yield __await(this._promise.then((res) => res.safeUnwrap()))))));
3167
+ });
3168
+ }
3169
+ then(successCallback, failureCallback) {
3170
+ return this._promise.then(successCallback, failureCallback);
3171
+ }
3172
+ [Symbol.asyncIterator]() {
3173
+ return __asyncGenerator(this, arguments, function* _a() {
3174
+ const result = yield __await(this._promise);
3175
+ if (result.isErr()) {
3176
+ yield yield __await(errAsync(result.error));
3177
+ }
3178
+ return yield __await(result.value);
3179
+ });
3180
+ }
3181
+ }
3182
+ function okAsync(value) {
3183
+ return new ResultAsync(Promise.resolve(new Ok(value)));
3184
+ }
3185
+ function errAsync(err) {
3186
+ return new ResultAsync(Promise.resolve(new Err(err)));
3187
+ }
3188
+ var fromPromise = ResultAsync.fromPromise;
3189
+ var fromSafePromise = ResultAsync.fromSafePromise;
3190
+ var fromAsyncThrowable = ResultAsync.fromThrowable;
3191
+ var combineResultList = (resultList) => {
3192
+ let acc = ok([]);
3193
+ for (const result of resultList) {
3194
+ if (result.isErr()) {
3195
+ acc = err(result.error);
3196
+ break;
3197
+ } else {
3198
+ acc.map((list) => list.push(result.value));
3199
+ }
3200
+ }
3201
+ return acc;
3202
+ };
3203
+ var combineResultAsyncList = (asyncResultList) => ResultAsync.fromSafePromise(Promise.all(asyncResultList)).andThen(combineResultList);
3204
+ var combineResultListWithAllErrors = (resultList) => {
3205
+ let acc = ok([]);
3206
+ for (const result of resultList) {
3207
+ if (result.isErr() && acc.isErr()) {
3208
+ acc.error.push(result.error);
3209
+ } else if (result.isErr() && acc.isOk()) {
3210
+ acc = err([result.error]);
3211
+ } else if (result.isOk() && acc.isOk()) {
3212
+ acc.value.push(result.value);
3213
+ }
3214
+ }
3215
+ return acc;
3216
+ };
3217
+ var combineResultAsyncListWithAllErrors = (asyncResultList) => ResultAsync.fromSafePromise(Promise.all(asyncResultList)).andThen(combineResultListWithAllErrors);
3218
+ var Result;
3219
+ (function(Result2) {
3220
+ function fromThrowable(fn, errorFn) {
3221
+ return (...args) => {
3222
+ try {
3223
+ const result = fn(...args);
3224
+ return ok(result);
3225
+ } catch (e) {
3226
+ return err(errorFn ? errorFn(e) : e);
3227
+ }
3228
+ };
3229
+ }
3230
+ Result2.fromThrowable = fromThrowable;
3231
+ function combine(resultList) {
3232
+ return combineResultList(resultList);
3233
+ }
3234
+ Result2.combine = combine;
3235
+ function combineWithAllErrors(resultList) {
3236
+ return combineResultListWithAllErrors(resultList);
3237
+ }
3238
+ Result2.combineWithAllErrors = combineWithAllErrors;
3239
+ })(Result || (Result = {}));
3240
+ function ok(value) {
3241
+ return new Ok(value);
3242
+ }
3243
+ function err(err2) {
3244
+ return new Err(err2);
3245
+ }
3246
+ function safeTry(body) {
3247
+ const n = body().next();
3248
+ if (n instanceof Promise) {
3249
+ return new ResultAsync(n.then((r) => r.value));
3250
+ }
3251
+ return n.value;
3252
+ }
3253
+
3254
+ class Ok {
3255
+ constructor(value) {
3256
+ this.value = value;
3257
+ }
3258
+ isOk() {
3259
+ return true;
3260
+ }
3261
+ isErr() {
3262
+ return !this.isOk();
3263
+ }
3264
+ map(f) {
3265
+ return ok(f(this.value));
3266
+ }
3267
+ mapErr(_f) {
3268
+ return ok(this.value);
3269
+ }
3270
+ andThen(f) {
3271
+ return f(this.value);
3272
+ }
3273
+ andThrough(f) {
3274
+ return f(this.value).map((_value) => this.value);
3275
+ }
3276
+ andTee(f) {
3277
+ try {
3278
+ f(this.value);
3279
+ } catch (e) {}
3280
+ return ok(this.value);
3281
+ }
3282
+ orTee(_f) {
3283
+ return ok(this.value);
3284
+ }
3285
+ orElse(_f) {
3286
+ return ok(this.value);
3287
+ }
3288
+ asyncAndThen(f) {
3289
+ return f(this.value);
3290
+ }
3291
+ asyncAndThrough(f) {
3292
+ return f(this.value).map(() => this.value);
3293
+ }
3294
+ asyncMap(f) {
3295
+ return ResultAsync.fromSafePromise(f(this.value));
3296
+ }
3297
+ unwrapOr(_v) {
3298
+ return this.value;
3299
+ }
3300
+ match(ok2, _err) {
3301
+ return ok2(this.value);
3302
+ }
3303
+ safeUnwrap() {
3304
+ const value = this.value;
3305
+ return function* () {
3306
+ return value;
3307
+ }();
3308
+ }
3309
+ _unsafeUnwrap(_) {
3310
+ return this.value;
3311
+ }
3312
+ _unsafeUnwrapErr(config) {
3313
+ throw createNeverThrowError("Called `_unsafeUnwrapErr` on an Ok", this, config);
3314
+ }
3315
+ *[Symbol.iterator]() {
3316
+ return this.value;
3317
+ }
3318
+ }
3319
+
3320
+ class Err {
3321
+ constructor(error) {
3322
+ this.error = error;
3323
+ }
3324
+ isOk() {
3325
+ return false;
3326
+ }
3327
+ isErr() {
3328
+ return !this.isOk();
3329
+ }
3330
+ map(_f) {
3331
+ return err(this.error);
3332
+ }
3333
+ mapErr(f) {
3334
+ return err(f(this.error));
3335
+ }
3336
+ andThrough(_f) {
3337
+ return err(this.error);
3338
+ }
3339
+ andTee(_f) {
3340
+ return err(this.error);
3341
+ }
3342
+ orTee(f) {
3343
+ try {
3344
+ f(this.error);
3345
+ } catch (e) {}
3346
+ return err(this.error);
3347
+ }
3348
+ andThen(_f) {
3349
+ return err(this.error);
3350
+ }
3351
+ orElse(f) {
3352
+ return f(this.error);
3353
+ }
3354
+ asyncAndThen(_f) {
3355
+ return errAsync(this.error);
3356
+ }
3357
+ asyncAndThrough(_f) {
3358
+ return errAsync(this.error);
3359
+ }
3360
+ asyncMap(_f) {
3361
+ return errAsync(this.error);
3362
+ }
3363
+ unwrapOr(v) {
3364
+ return v;
3365
+ }
3366
+ match(_ok, err2) {
3367
+ return err2(this.error);
3368
+ }
3369
+ safeUnwrap() {
3370
+ const error = this.error;
3371
+ return function* () {
3372
+ yield err(error);
3373
+ throw new Error("Do not use this generator out of `safeTry`");
3374
+ }();
3375
+ }
3376
+ _unsafeUnwrap(config) {
3377
+ throw createNeverThrowError("Called `_unsafeUnwrap` on an Err", this, config);
3378
+ }
3379
+ _unsafeUnwrapErr(_) {
3380
+ return this.error;
3381
+ }
3382
+ *[Symbol.iterator]() {
3383
+ const self = this;
3384
+ yield self;
3385
+ return self;
3386
+ }
3387
+ }
3388
+ var fromThrowable = Result.fromThrowable;
3389
+
3390
+ // src/utils/logger.ts
3391
+ var import_debug = __toESM(require_src(), 1);
3392
+ var BASE_NAMESPACE = "residue";
3393
+ function formatMessage(value) {
3394
+ if (typeof value === "string")
3395
+ return value;
3396
+ return value.message;
3397
+ }
3398
+ function createLogger(namespace) {
3399
+ const debug = import_debug.default(`${BASE_NAMESPACE}:${namespace}`);
3400
+ return {
3401
+ debug,
3402
+ info(message) {
3403
+ process.stderr.write(`${message}
3404
+ `);
3405
+ },
3406
+ warn(value) {
3407
+ process.stderr.write(`Warning: ${formatMessage(value)}
3408
+ `);
3409
+ },
3410
+ error(value) {
3411
+ process.stderr.write(`Error: ${formatMessage(value)}
3412
+ `);
3413
+ }
3414
+ };
3415
+ }
3416
+
3417
+ // src/utils/errors.ts
3418
+ var log = createLogger("cli");
3419
+
3420
+ class CliError extends Error {
3421
+ _tag = "CliError";
3422
+ code;
3423
+ constructor(opts) {
3424
+ super(opts.message, { cause: opts.cause });
3425
+ this.name = "CliError";
3426
+ this.code = opts.code;
3427
+ }
3428
+ }
3429
+ var toCliError = (opts) => (cause) => new CliError({ ...opts, cause });
3430
+ function wrapCommand(fn, opts) {
3431
+ const exitCode = opts?.exitCode ?? 1;
3432
+ return async (...args) => {
3433
+ const result = await fn(...args);
3434
+ if (result.isErr()) {
3435
+ log.error(result.error);
3436
+ process.exit(exitCode);
3437
+ }
3438
+ };
3439
+ }
3440
+ function wrapHookCommand(fn) {
3441
+ return wrapCommand(fn, { exitCode: 0 });
3442
+ }
3443
+
3444
+ // src/lib/git.ts
3445
+ function runGitCommand(opts) {
3446
+ return ResultAsync.fromPromise((async () => {
3447
+ const proc = Bun.spawn(["git", ...opts.args], {
3448
+ stdout: "pipe",
3449
+ stderr: "pipe"
3450
+ });
3451
+ const exitCode = await proc.exited;
3452
+ if (exitCode !== 0) {
3453
+ const stderr = await new Response(proc.stderr).text();
3454
+ throw new Error(stderr.trim() || `exit code ${exitCode}`);
3455
+ }
3456
+ return (await new Response(proc.stdout).text()).trim();
3457
+ })(), toCliError({ message: opts.errorMessage, code: "GIT_ERROR" }));
3458
+ }
3459
+ function parseRemote(remoteUrl) {
3460
+ const match = remoteUrl.match(/[:/]([^/]+)\/([^/]+?)(?:\.git)?$/);
3461
+ if (!match) {
3462
+ return err(new CliError({
3463
+ message: `Cannot parse git remote URL: ${remoteUrl}`,
3464
+ code: "GIT_PARSE_ERROR"
3465
+ }));
3466
+ }
3467
+ return ok({ org: match[1], repo: match[2] });
3468
+ }
3469
+ function getRemoteUrl() {
3470
+ return runGitCommand({
3471
+ args: ["remote", "get-url", "origin"],
3472
+ errorMessage: "Failed to get git remote URL"
3473
+ });
3474
+ }
3475
+ function getCurrentBranch() {
3476
+ return runGitCommand({
3477
+ args: ["rev-parse", "--abbrev-ref", "HEAD"],
3478
+ errorMessage: "Failed to get current branch"
3479
+ });
3480
+ }
3481
+ function getCurrentSha() {
3482
+ return runGitCommand({
3483
+ args: ["rev-parse", "HEAD"],
3484
+ errorMessage: "Failed to get current commit SHA"
3485
+ });
3486
+ }
3487
+ function getCommitMeta(sha) {
3488
+ return runGitCommand({
3489
+ args: ["log", "-1", "--format=%s%n%an%n%ct", sha],
3490
+ errorMessage: `Failed to get commit metadata for ${sha}`
3491
+ }).map((text) => {
3492
+ const lines = text.split(`
3493
+ `);
3494
+ return {
3495
+ message: lines[0] || "",
3496
+ author: lines[1] || "",
3497
+ committed_at: parseInt(lines[2] || "0", 10)
3498
+ };
3499
+ });
3500
+ }
3501
+ function isGitRepo() {
3502
+ return ResultAsync.fromPromise((async () => {
3503
+ const proc = Bun.spawn(["git", "rev-parse", "--git-dir"], {
3504
+ stdout: "pipe",
3505
+ stderr: "pipe"
3506
+ });
3507
+ const exitCode = await proc.exited;
3508
+ return exitCode === 0;
3509
+ })(), toCliError({ message: "Failed to check git repo", code: "GIT_ERROR" }));
3510
+ }
3511
+
3512
+ // src/lib/pending.ts
3513
+ import { mkdir } from "fs/promises";
3514
+ import { join } from "path";
3515
+ function getProjectRoot() {
3516
+ return ResultAsync.fromPromise((async () => {
3517
+ const proc = Bun.spawn(["git", "rev-parse", "--show-toplevel"], {
3518
+ stdout: "pipe",
3519
+ stderr: "pipe"
3520
+ });
3521
+ const exitCode = await proc.exited;
3522
+ if (exitCode !== 0) {
3523
+ throw new Error("not a git repository");
3524
+ }
3525
+ return (await new Response(proc.stdout).text()).trim();
3526
+ })(), toCliError({ message: "Not a git repository", code: "GIT_ERROR" }));
3527
+ }
3528
+ function getResidueDir(projectRoot) {
3529
+ const residueDir = join(projectRoot, ".residue");
3530
+ return ResultAsync.fromPromise((async () => {
3531
+ await mkdir(residueDir, { recursive: true });
3532
+ return residueDir;
3533
+ })(), toCliError({
3534
+ message: "Failed to create .residue directory",
3535
+ code: "IO_ERROR"
3536
+ }));
3537
+ }
3538
+ function getPendingPath(projectRoot) {
3539
+ return getResidueDir(projectRoot).map((residueDir) => join(residueDir, "pending.json"));
3540
+ }
3541
+ function migratePending(sessions) {
3542
+ for (const session of sessions) {
3543
+ if (session.commits.length > 0 && typeof session.commits[0] === "string") {
3544
+ session.commits = session.commits.map((sha) => ({
3545
+ sha,
3546
+ branch: "unknown"
3547
+ }));
3548
+ }
3549
+ }
3550
+ return sessions;
3551
+ }
3552
+ function readPending(pendingPath) {
3553
+ return ResultAsync.fromPromise((async () => {
3554
+ const file = Bun.file(pendingPath);
3555
+ const isExists = await file.exists();
3556
+ if (!isExists)
3557
+ return [];
3558
+ const text = await file.text();
3559
+ const sessions = JSON.parse(text);
3560
+ return migratePending(sessions);
3561
+ })(), toCliError({
3562
+ message: "Failed to read pending queue",
3563
+ code: "STATE_ERROR"
3564
+ }));
3565
+ }
3566
+ function writePending(opts) {
3567
+ return ResultAsync.fromPromise((async () => {
3568
+ await Bun.write(opts.path, JSON.stringify(opts.sessions, null, 2));
3569
+ })(), toCliError({
3570
+ message: "Failed to write pending queue",
3571
+ code: "STATE_ERROR"
3572
+ }));
3573
+ }
3574
+ function addSession(opts) {
3575
+ return readPending(opts.path).andThen((sessions) => {
3576
+ sessions.push(opts.session);
3577
+ return writePending({ path: opts.path, sessions });
3578
+ });
3579
+ }
3580
+ function updateSession(opts) {
3581
+ return readPending(opts.path).andThen((sessions) => {
3582
+ const index = sessions.findIndex((s) => s.id === opts.id);
3583
+ if (index === -1) {
3584
+ return errAsync(new CliError({
3585
+ message: `Session not found: ${opts.id}`,
3586
+ code: "SESSION_NOT_FOUND"
3587
+ }));
3588
+ }
3589
+ sessions[index] = { ...sessions[index], ...opts.updates };
3590
+ return writePending({ path: opts.path, sessions });
3591
+ });
3592
+ }
3593
+ function getSession(opts) {
3594
+ return readPending(opts.path).map((sessions) => sessions.find((s) => s.id === opts.id));
3595
+ }
3596
+
3597
+ // src/commands/capture.ts
3598
+ function shouldTag(session) {
3599
+ if (session.status === "open")
3600
+ return true;
3601
+ return session.commits.length === 0;
3602
+ }
3603
+ function capture() {
3604
+ return safeTry(async function* () {
3605
+ const [sha, branch] = yield* ResultAsync.combine([
3606
+ getCurrentSha(),
3607
+ getCurrentBranch()
3608
+ ]);
3609
+ const projectRoot = yield* getProjectRoot();
3610
+ const pendingPath = yield* getPendingPath(projectRoot);
3611
+ const sessions = yield* readPending(pendingPath);
3612
+ for (const session of sessions) {
3613
+ if (!shouldTag(session))
3614
+ continue;
3615
+ const isAlreadyTagged = session.commits.some((c) => c.sha === sha);
3616
+ if (!isAlreadyTagged) {
3617
+ session.commits.push({ sha, branch });
3618
+ }
3619
+ }
3620
+ yield* writePending({ path: pendingPath, sessions });
3621
+ return ok(undefined);
3622
+ });
3623
+ }
3624
+
3625
+ // src/commands/hook.ts
3626
+ import { mkdir as mkdir2, readFile, rm, stat, writeFile } from "fs/promises";
3627
+ import { join as join2 } from "path";
3628
+ var log2 = createLogger("hook");
3629
+ function readStdin() {
3630
+ return ResultAsync.fromPromise((async () => {
3631
+ const chunks = [];
3632
+ const reader = Bun.stdin.stream().getReader();
3633
+ while (true) {
3634
+ const { done, value } = await reader.read();
3635
+ if (done)
3636
+ break;
3637
+ chunks.push(value);
3638
+ }
3639
+ return Buffer.concat(chunks).toString("utf-8");
3640
+ })(), toCliError({ message: "Failed to read stdin", code: "IO_ERROR" }));
3641
+ }
3642
+ function parseInput(raw) {
3643
+ return Result.fromThrowable((input) => JSON.parse(input), toCliError({
3644
+ message: "Failed to parse hook input JSON",
3645
+ code: "PARSE_ERROR"
3646
+ }))(raw);
3647
+ }
3648
+ function detectClaudeVersion() {
3649
+ return ResultAsync.fromPromise((async () => {
3650
+ const proc = Bun.spawn(["claude", "--version"], {
3651
+ stdout: "pipe",
3652
+ stderr: "pipe"
3653
+ });
3654
+ const exitCode = await proc.exited;
3655
+ if (exitCode !== 0)
3656
+ return "unknown";
3657
+ const output = await new Response(proc.stdout).text();
3658
+ return output.trim() || "unknown";
3659
+ })(), toCliError({
3660
+ message: "Failed to detect Claude version",
3661
+ code: "IO_ERROR"
3662
+ })).orElse(() => okAsync("unknown"));
3663
+ }
3664
+ function getHooksDir(projectRoot) {
3665
+ const hooksDir = join2(projectRoot, ".residue", "hooks");
3666
+ return ResultAsync.fromPromise((async () => {
3667
+ await mkdir2(hooksDir, { recursive: true });
3668
+ return hooksDir;
3669
+ })(), toCliError({
3670
+ message: "Failed to create hooks state directory",
3671
+ code: "IO_ERROR"
3672
+ }));
3673
+ }
3674
+ function fileExists(path) {
3675
+ return ResultAsync.fromPromise((async () => {
3676
+ try {
3677
+ await stat(path);
3678
+ return true;
3679
+ } catch {
3680
+ return false;
3681
+ }
3682
+ })(), toCliError({
3683
+ message: "Failed to check file existence",
3684
+ code: "IO_ERROR"
3685
+ }));
3686
+ }
3687
+ function readFileContent(path) {
3688
+ return ResultAsync.fromPromise(readFile(path, "utf-8"), toCliError({ message: "Failed to read file", code: "IO_ERROR" }));
3689
+ }
3690
+ function handleSessionStart(opts) {
3691
+ const { input, projectRoot } = opts;
3692
+ if (input.source !== "startup")
3693
+ return okAsync(undefined);
3694
+ if (!input.transcript_path)
3695
+ return okAsync(undefined);
3696
+ if (!input.session_id)
3697
+ return okAsync(undefined);
3698
+ const residueSessionId = crypto.randomUUID();
3699
+ const claudeSessionId = input.session_id;
3700
+ return safeTry(async function* () {
3701
+ const pendingPath = yield* getPendingPath(projectRoot);
3702
+ yield* addSession({
3703
+ path: pendingPath,
3704
+ session: {
3705
+ id: residueSessionId,
3706
+ agent: "claude-code",
3707
+ agent_version: "unknown",
3708
+ status: "open",
3709
+ data_path: input.transcript_path,
3710
+ commits: []
3711
+ }
3712
+ });
3713
+ const version = yield* detectClaudeVersion();
3714
+ yield* updateSession({
3715
+ path: pendingPath,
3716
+ id: residueSessionId,
3717
+ updates: { agent_version: version }
3718
+ });
3719
+ const hooksDir = yield* getHooksDir(projectRoot);
3720
+ const stateFile = join2(hooksDir, `${claudeSessionId}.state`);
3721
+ yield* ResultAsync.fromPromise(writeFile(stateFile, residueSessionId), toCliError({
3722
+ message: "Failed to write hook state file",
3723
+ code: "IO_ERROR"
3724
+ }));
3725
+ log2.debug("session started for claude-code");
3726
+ return ok(undefined);
3727
+ });
3728
+ }
3729
+ function handleSessionEnd(opts) {
3730
+ const { input, projectRoot } = opts;
3731
+ const claudeSessionId = input.session_id;
3732
+ if (!claudeSessionId)
3733
+ return okAsync(undefined);
3734
+ return safeTry(async function* () {
3735
+ const hooksDir = yield* getHooksDir(projectRoot);
3736
+ const stateFile = join2(hooksDir, `${claudeSessionId}.state`);
3737
+ const isExists = yield* fileExists(stateFile);
3738
+ if (!isExists)
3739
+ return ok(undefined);
3740
+ const rawId = yield* readFileContent(stateFile);
3741
+ const trimmedId = rawId.trim();
3742
+ if (!trimmedId)
3743
+ return ok(undefined);
3744
+ const pendingPath = yield* getPendingPath(projectRoot);
3745
+ const session = yield* getSession({ path: pendingPath, id: trimmedId });
3746
+ if (session) {
3747
+ yield* updateSession({
3748
+ path: pendingPath,
3749
+ id: trimmedId,
3750
+ updates: { status: "ended" }
3751
+ });
3752
+ }
3753
+ yield* ResultAsync.fromPromise(rm(stateFile, { force: true }), toCliError({
3754
+ message: "Failed to remove hook state file",
3755
+ code: "IO_ERROR"
3756
+ }));
3757
+ log2.debug("session %s ended", trimmedId);
3758
+ return ok(undefined);
3759
+ });
3760
+ }
3761
+ function hookClaudeCode() {
3762
+ return safeTry(async function* () {
3763
+ const raw = yield* readStdin();
3764
+ const input = yield* parseInput(raw);
3765
+ const projectRoot = yield* getProjectRoot();
3766
+ switch (input.hook_event_name) {
3767
+ case "SessionStart":
3768
+ yield* handleSessionStart({ input, projectRoot });
3769
+ break;
3770
+ case "SessionEnd":
3771
+ yield* handleSessionEnd({ input, projectRoot });
3772
+ break;
3773
+ }
3774
+ return ok(undefined);
3775
+ });
3776
+ }
3777
+
3778
+ // src/commands/init.ts
3779
+ import {
3780
+ appendFile,
3781
+ chmod,
3782
+ mkdir as mkdir3,
3783
+ readFile as readFile2,
3784
+ stat as stat2,
3785
+ writeFile as writeFile2
3786
+ } from "fs/promises";
3787
+ import { join as join3 } from "path";
3788
+ var log3 = createLogger("init");
3789
+ var POST_COMMIT_LINE = "residue capture >/dev/null 2>&1 &";
3790
+ var PRE_PUSH_LINE = 'residue sync --remote-url "$2"';
3791
+ function installHook(opts) {
3792
+ const hookPath = join3(opts.hooksDir, opts.filename);
3793
+ return ResultAsync.fromPromise((async () => {
3794
+ let isExisting = false;
3795
+ try {
3796
+ await stat2(hookPath);
3797
+ isExisting = true;
3798
+ } catch {}
3799
+ if (isExisting) {
3800
+ const content = await readFile2(hookPath, "utf-8");
3801
+ if (content.includes(opts.line)) {
3802
+ return `${opts.filename}: already installed`;
3803
+ }
3804
+ await writeFile2(hookPath, content.trimEnd() + `
3805
+ ` + opts.line + `
3806
+ `);
3807
+ await chmod(hookPath, 493);
3808
+ return `${opts.filename}: appended`;
3809
+ }
3810
+ await writeFile2(hookPath, `#!/bin/sh
3811
+ ${opts.line}
3812
+ `);
3813
+ await chmod(hookPath, 493);
3814
+ return `${opts.filename}: created`;
3815
+ })(), toCliError({
3816
+ message: `Failed to install hook ${opts.filename}`,
3817
+ code: "IO_ERROR"
3818
+ }));
3819
+ }
3820
+ function getGitDirForInit() {
3821
+ return ResultAsync.fromPromise((async () => {
3822
+ const proc = Bun.spawn(["git", "rev-parse", "--git-dir"], {
3823
+ stdout: "pipe",
3824
+ stderr: "pipe"
3825
+ });
3826
+ await proc.exited;
3827
+ return (await new Response(proc.stdout).text()).trim();
3828
+ })(), toCliError({ message: "Failed to get git directory", code: "GIT_ERROR" }));
3829
+ }
3830
+ function ensureGitignore(projectRoot) {
3831
+ const gitignorePath = join3(projectRoot, ".gitignore");
3832
+ return ResultAsync.fromPromise((async () => {
3833
+ let content = "";
3834
+ try {
3835
+ content = await readFile2(gitignorePath, "utf-8");
3836
+ } catch {}
3837
+ if (content.includes(".residue")) {
3838
+ return;
3839
+ }
3840
+ const line = content.length > 0 && !content.endsWith(`
3841
+ `) ? `
3842
+ .residue/
3843
+ ` : `.residue/
3844
+ `;
3845
+ await appendFile(gitignorePath, line);
3846
+ })(), toCliError({ message: "Failed to update .gitignore", code: "IO_ERROR" }));
3847
+ }
3848
+ function init() {
3849
+ return safeTry(async function* () {
3850
+ const isRepo = yield* isGitRepo();
3851
+ if (!isRepo) {
3852
+ return err(new CliError({ message: "not a git repository", code: "GIT_ERROR" }));
3853
+ }
3854
+ const [projectRoot, gitDir] = yield* ResultAsync.combine([
3855
+ getProjectRoot(),
3856
+ getGitDirForInit()
3857
+ ]);
3858
+ const hooksDir = join3(gitDir, "hooks");
3859
+ yield* ResultAsync.combine([
3860
+ getResidueDir(projectRoot),
3861
+ ResultAsync.fromPromise(mkdir3(hooksDir, { recursive: true }), toCliError({
3862
+ message: "Failed to create hooks directory",
3863
+ code: "IO_ERROR"
3864
+ }))
3865
+ ]);
3866
+ const [postCommit, prePush] = yield* ResultAsync.combine([
3867
+ installHook({
3868
+ hooksDir,
3869
+ filename: "post-commit",
3870
+ line: POST_COMMIT_LINE
3871
+ }),
3872
+ installHook({
3873
+ hooksDir,
3874
+ filename: "pre-push",
3875
+ line: PRE_PUSH_LINE
3876
+ }),
3877
+ ensureGitignore(projectRoot)
3878
+ ]);
3879
+ log3.info("Initialized residue in this repository.");
3880
+ log3.info(` ${postCommit}`);
3881
+ log3.info(` ${prePush}`);
3882
+ return ok(undefined);
3883
+ });
3884
+ }
3885
+
3886
+ // src/lib/config.ts
3887
+ import { mkdir as mkdir4 } from "fs/promises";
3888
+ import { join as join4 } from "path";
3889
+ function home() {
3890
+ return process.env.HOME || process.env.USERPROFILE || "/";
3891
+ }
3892
+ function getConfigDir() {
3893
+ return join4(home(), ".residue");
3894
+ }
3895
+ function getConfigPath() {
3896
+ return join4(getConfigDir(), "config");
3897
+ }
3898
+ function readConfig() {
3899
+ return ResultAsync.fromPromise((async () => {
3900
+ const path = getConfigPath();
3901
+ const file = Bun.file(path);
3902
+ const isExists = await file.exists();
3903
+ if (!isExists)
3904
+ return null;
3905
+ const text = await file.text();
3906
+ return JSON.parse(text);
3907
+ })(), toCliError({ message: "Failed to read config", code: "CONFIG_ERROR" }));
3908
+ }
3909
+ function writeConfig(config) {
3910
+ return ResultAsync.fromPromise((async () => {
3911
+ const dir = getConfigDir();
3912
+ await mkdir4(dir, { recursive: true });
3913
+ await Bun.write(getConfigPath(), JSON.stringify(config, null, 2));
3914
+ })(), toCliError({ message: "Failed to write config", code: "CONFIG_ERROR" }));
3915
+ }
3916
+
3917
+ // src/commands/login.ts
3918
+ var log4 = createLogger("login");
3919
+ function login(opts) {
3920
+ if (!opts.url.startsWith("http://") && !opts.url.startsWith("https://")) {
3921
+ return errAsync(new CliError({
3922
+ message: "URL must start with http:// or https://",
3923
+ code: "VALIDATION_ERROR"
3924
+ }));
3925
+ }
3926
+ const cleanUrl = opts.url.replace(/\/+$/, "");
3927
+ return writeConfig({ worker_url: cleanUrl, token: opts.token }).map(() => {
3928
+ log4.info(`Logged in to ${cleanUrl}`);
3929
+ });
3930
+ }
3931
+
3932
+ // src/commands/sync.ts
3933
+ import { stat as stat3 } from "fs/promises";
3934
+ var log5 = createLogger("sync");
3935
+ var STALE_THRESHOLD_MS = 30 * 60 * 1000;
3936
+ function requestUploadUrl(opts) {
3937
+ return ResultAsync.fromPromise(fetch(`${opts.workerUrl}/api/sessions/upload-url`, {
3938
+ method: "POST",
3939
+ headers: {
3940
+ "Content-Type": "application/json",
3941
+ Authorization: `Bearer ${opts.token}`
3942
+ },
3943
+ body: JSON.stringify({ session_id: opts.sessionId })
3944
+ }).then(async (response) => {
3945
+ if (!response.ok) {
3946
+ throw new Error(`HTTP ${response.status}`);
3947
+ }
3948
+ return response.json();
3949
+ }), toCliError({
3950
+ message: "Failed to request upload URL",
3951
+ code: "NETWORK_ERROR"
3952
+ }));
3953
+ }
3954
+ function uploadToPresignedUrl(opts) {
3955
+ return ResultAsync.fromPromise(fetch(opts.url, {
3956
+ method: "PUT",
3957
+ headers: { "Content-Type": "application/json" },
3958
+ body: opts.data
3959
+ }).then((response) => {
3960
+ if (!response.ok) {
3961
+ throw new Error(`R2 upload failed: HTTP ${response.status}`);
3962
+ }
3963
+ }), toCliError({ message: "Direct R2 upload failed", code: "NETWORK_ERROR" }));
3964
+ }
3965
+ function postSessionMetadata(opts) {
3966
+ return ResultAsync.fromPromise(fetch(`${opts.workerUrl}/api/sessions`, {
3967
+ method: "POST",
3968
+ headers: {
3969
+ "Content-Type": "application/json",
3970
+ Authorization: `Bearer ${opts.token}`
3971
+ },
3972
+ body: JSON.stringify({
3973
+ session: opts.session,
3974
+ commits: opts.commits
3975
+ })
3976
+ }).then((response) => {
3977
+ if (!response.ok) {
3978
+ throw new Error(`HTTP ${response.status}`);
3979
+ }
3980
+ }), toCliError({ message: "Metadata upload failed", code: "NETWORK_ERROR" }));
3981
+ }
3982
+ function readSessionData(dataPath) {
3983
+ return ResultAsync.fromPromise((async () => {
3984
+ const file = Bun.file(dataPath);
3985
+ const isExists = await file.exists();
3986
+ if (!isExists)
3987
+ return null;
3988
+ return file.text();
3989
+ })(), toCliError({ message: "Failed to read session data", code: "IO_ERROR" }));
3990
+ }
3991
+ function buildCommitMeta(opts) {
3992
+ return ResultAsync.fromSafePromise((async () => {
3993
+ const commits = [];
3994
+ for (const ref of opts.commitRefs) {
3995
+ const metaResult = await getCommitMeta(ref.sha);
3996
+ if (metaResult.isErr()) {
3997
+ log5.warn(metaResult.error);
3998
+ continue;
3999
+ }
4000
+ commits.push({
4001
+ sha: ref.sha,
4002
+ org: opts.org,
4003
+ repo: opts.repo,
4004
+ message: metaResult.value.message,
4005
+ author: metaResult.value.author,
4006
+ committed_at: metaResult.value.committed_at,
4007
+ branch: ref.branch
4008
+ });
4009
+ }
4010
+ return commits;
4011
+ })());
4012
+ }
4013
+ function getFileMtimeMs(path) {
4014
+ return ResultAsync.fromPromise(stat3(path).then((s) => s.mtimeMs), toCliError({ message: "Failed to stat file", code: "IO_ERROR" })).orElse(() => okAsync(null));
4015
+ }
4016
+ function closeStaleOpenSessions(opts) {
4017
+ const now = Date.now();
4018
+ const openSessions = opts.sessions.filter((s) => s.status === "open");
4019
+ if (openSessions.length === 0) {
4020
+ return okAsync(opts.sessions);
4021
+ }
4022
+ const checks = openSessions.map((session) => getFileMtimeMs(session.data_path).map((mtimeMs) => {
4023
+ if (mtimeMs === null) {
4024
+ session.status = "ended";
4025
+ log5.debug("auto-closed session %s (data file not accessible)", session.id);
4026
+ } else {
4027
+ const msSinceModified = now - mtimeMs;
4028
+ if (msSinceModified > STALE_THRESHOLD_MS) {
4029
+ session.status = "ended";
4030
+ log5.debug("auto-closed stale session %s (data file unchanged for %dm)", session.id, Math.round(msSinceModified / 60000));
4031
+ }
4032
+ }
4033
+ }));
4034
+ return ResultAsync.combine(checks).map(() => opts.sessions);
4035
+ }
4036
+ function syncSessions(opts) {
4037
+ return ResultAsync.fromSafePromise((async () => {
4038
+ const remaining = [];
4039
+ for (const session of opts.sessions) {
4040
+ if (session.commits.length === 0) {
4041
+ remaining.push(session);
4042
+ continue;
4043
+ }
4044
+ const dataResult = await readSessionData(session.data_path);
4045
+ if (dataResult.isErr()) {
4046
+ log5.warn(dataResult.error);
4047
+ remaining.push(session);
4048
+ continue;
4049
+ }
4050
+ const data = dataResult.value;
4051
+ if (data === null) {
4052
+ log5.warn(`dropping session ${session.id}: data file missing at ${session.data_path}`);
4053
+ continue;
4054
+ }
4055
+ const commitsResult = await buildCommitMeta({
4056
+ commitRefs: session.commits,
4057
+ org: opts.org,
4058
+ repo: opts.repo
4059
+ });
4060
+ if (commitsResult.isErr()) {
4061
+ log5.warn(commitsResult.error);
4062
+ remaining.push(session);
4063
+ continue;
4064
+ }
4065
+ const uploadUrlResult = await requestUploadUrl({
4066
+ workerUrl: opts.workerUrl,
4067
+ token: opts.token,
4068
+ sessionId: session.id
4069
+ });
4070
+ if (uploadUrlResult.isErr()) {
4071
+ log5.warn(`failed to get upload URL for session ${session.id}: ${uploadUrlResult.error.message}`);
4072
+ remaining.push(session);
4073
+ continue;
4074
+ }
4075
+ const directUploadResult = await uploadToPresignedUrl({
4076
+ url: uploadUrlResult.value.url,
4077
+ data
4078
+ });
4079
+ if (directUploadResult.isErr()) {
4080
+ log5.warn(`R2 upload failed for session ${session.id}: ${directUploadResult.error.message}`);
4081
+ remaining.push(session);
4082
+ continue;
4083
+ }
4084
+ log5.debug("uploaded session %s data directly to R2", session.id);
4085
+ const metadataResult = await postSessionMetadata({
4086
+ workerUrl: opts.workerUrl,
4087
+ token: opts.token,
4088
+ session: {
4089
+ id: session.id,
4090
+ agent: session.agent,
4091
+ agent_version: session.agent_version,
4092
+ status: session.status
4093
+ },
4094
+ commits: commitsResult.value
4095
+ });
4096
+ if (metadataResult.isErr()) {
4097
+ log5.warn(`metadata upload failed for session ${session.id}: ${metadataResult.error.message}`);
4098
+ remaining.push(session);
4099
+ continue;
4100
+ }
4101
+ if (session.status === "open") {
4102
+ remaining.push(session);
4103
+ }
4104
+ log5.debug("synced session %s", session.id);
4105
+ }
4106
+ return remaining;
4107
+ })());
4108
+ }
4109
+ function resolveRemote(remoteUrl) {
4110
+ if (remoteUrl && remoteUrl.length > 0) {
4111
+ const result = parseRemote(remoteUrl);
4112
+ if (result.isOk()) {
4113
+ return okAsync(result.value);
4114
+ }
4115
+ }
4116
+ return getRemoteUrl().andThen(parseRemote);
4117
+ }
4118
+ function sync(opts) {
4119
+ return safeTry(async function* () {
4120
+ const config = yield* readConfig();
4121
+ if (!config) {
4122
+ return err(new CliError({
4123
+ message: "Not configured. Run 'residue login' first.",
4124
+ code: "CONFIG_MISSING"
4125
+ }));
4126
+ }
4127
+ const projectRoot = yield* getProjectRoot();
4128
+ const pendingPath = yield* getPendingPath(projectRoot);
4129
+ const sessions = yield* readPending(pendingPath);
4130
+ if (sessions.length === 0) {
4131
+ return ok(undefined);
4132
+ }
4133
+ const updatedSessions = yield* closeStaleOpenSessions({ sessions });
4134
+ const { org, repo } = yield* resolveRemote(opts?.remoteUrl);
4135
+ const remaining = yield* syncSessions({
4136
+ sessions: updatedSessions,
4137
+ workerUrl: config.worker_url,
4138
+ token: config.token,
4139
+ org,
4140
+ repo
4141
+ });
4142
+ yield* writePending({ path: pendingPath, sessions: remaining });
4143
+ return ok(undefined);
4144
+ });
4145
+ }
4146
+
4147
+ // src/commands/push.ts
4148
+ var push = sync;
4149
+
4150
+ // src/commands/session-end.ts
4151
+ var log6 = createLogger("session");
4152
+ function sessionEnd(opts) {
4153
+ return safeTry(async function* () {
4154
+ const projectRoot = yield* getProjectRoot();
4155
+ const pendingPath = yield* getPendingPath(projectRoot);
4156
+ const session = yield* getSession({ path: pendingPath, id: opts.id });
4157
+ if (!session) {
4158
+ return err(new CliError({
4159
+ message: `Session not found: ${opts.id}`,
4160
+ code: "SESSION_NOT_FOUND"
4161
+ }));
4162
+ }
4163
+ yield* updateSession({
4164
+ path: pendingPath,
4165
+ id: opts.id,
4166
+ updates: { status: "ended" }
4167
+ });
4168
+ log6.debug("session %s ended", opts.id);
4169
+ return ok(undefined);
4170
+ });
4171
+ }
4172
+
4173
+ // src/commands/session-start.ts
4174
+ var log7 = createLogger("session");
4175
+ function sessionStart(opts) {
4176
+ const id = crypto.randomUUID();
4177
+ return getProjectRoot().andThen(getPendingPath).andThen((pendingPath) => addSession({
4178
+ path: pendingPath,
4179
+ session: {
4180
+ id,
4181
+ agent: opts.agent,
4182
+ agent_version: opts.agentVersion,
4183
+ status: "open",
4184
+ data_path: opts.data,
4185
+ commits: []
4186
+ }
4187
+ })).map(() => {
4188
+ process.stdout.write(id);
4189
+ log7.debug("session started for %s", opts.agent);
4190
+ });
4191
+ }
4192
+
4193
+ // src/commands/setup.ts
4194
+ import { mkdir as mkdir5, readFile as readFile3, stat as stat4, writeFile as writeFile3 } from "fs/promises";
4195
+ import { join as join5 } from "path";
4196
+
4197
+ // adapters/pi/extension.ts.txt
4198
+ var extension_ts_default = `/**
4199
+ * Residue adapter for pi coding agent.
4200
+ *
4201
+ * Hooks into pi's session lifecycle to call the residue CLI,
4202
+ * linking AI conversations to git commits.
4203
+ *
4204
+ * Uses a persistent state file (.residue/hooks/pi.state) to survive
4205
+ * process crashes. On startup, any leftover state from a previous
4206
+ * run is cleaned up automatically.
4207
+ *
4208
+ * Lifecycle:
4209
+ * session_start -> end stale session (if any), then residue session start
4210
+ * session_switch -> residue session end + session start (swap tracked session)
4211
+ * session_shutdown -> residue session end (marks session as ended)
4212
+ */
4213
+
4214
+ import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
4215
+
4216
+ const STATE_FILE = ".residue/hooks/pi.state";
4217
+
4218
+ export default function (pi: ExtensionAPI) {
4219
+ let piVersion = "unknown";
4220
+ let isResidueAvailable = true;
4221
+
4222
+ async function detectPiVersion(): Promise<string> {
4223
+ const result = await pi.exec("pi", ["--version"]);
4224
+ if (result.code === 0 && result.stdout.trim()) {
4225
+ return result.stdout.trim();
4226
+ }
4227
+ return "unknown";
4228
+ }
4229
+
4230
+ async function checkResidueAvailable(): Promise<boolean> {
4231
+ const result = await pi.exec("which", ["residue"]);
4232
+ return result.code === 0;
4233
+ }
4234
+
4235
+ async function readStateFile(): Promise<string | undefined> {
4236
+ const result = await pi.exec("cat", [STATE_FILE]);
4237
+ if (result.code === 0 && result.stdout.trim()) {
4238
+ return result.stdout.trim();
4239
+ }
4240
+ return undefined;
4241
+ }
4242
+
4243
+ async function writeStateFile(params: {
4244
+ sessionId: string;
4245
+ }): Promise<void> {
4246
+ await pi.exec("mkdir", ["-p", ".residue/hooks"]);
4247
+ // Use sh -c to write via redirect since pi.exec may not support shell features
4248
+ await pi.exec("sh", ["-c", \`printf '%s' '\${params.sessionId}' > \${STATE_FILE}\`]);
4249
+ }
4250
+
4251
+ async function removeStateFile(): Promise<void> {
4252
+ await pi.exec("rm", ["-f", STATE_FILE]);
4253
+ }
4254
+
4255
+ /**
4256
+ * End a session by ID. Does not touch the state file.
4257
+ */
4258
+ async function endSessionById(params: {
4259
+ sessionId: string;
4260
+ }): Promise<void> {
4261
+ if (!isResidueAvailable) return;
4262
+ await pi.exec("residue", ["session", "end", "--id", params.sessionId]);
4263
+ }
4264
+
4265
+ /**
4266
+ * End whatever session is recorded in the state file, then remove
4267
+ * the state file. This cleans up after crashes / missed shutdowns.
4268
+ */
4269
+ async function endStaleSession(): Promise<void> {
4270
+ const staleId = await readStateFile();
4271
+ if (!staleId) return;
4272
+ await endSessionById({ sessionId: staleId });
4273
+ await removeStateFile();
4274
+ }
4275
+
4276
+ async function startResidueSession(params: {
4277
+ sessionFile: string | undefined;
4278
+ }): Promise<void> {
4279
+ if (!params.sessionFile) return;
4280
+ if (!isResidueAvailable) return;
4281
+
4282
+ const result = await pi.exec("residue", [
4283
+ "session",
4284
+ "start",
4285
+ "--agent",
4286
+ "pi",
4287
+ "--data",
4288
+ params.sessionFile,
4289
+ "--agent-version",
4290
+ piVersion,
4291
+ ]);
4292
+
4293
+ if (result.code === 0 && result.stdout.trim()) {
4294
+ const sessionId = result.stdout.trim();
4295
+ await writeStateFile({ sessionId });
4296
+ }
4297
+ }
4298
+
4299
+ async function endResidueSession(): Promise<void> {
4300
+ const sessionId = await readStateFile();
4301
+ if (!sessionId) return;
4302
+ if (!isResidueAvailable) return;
4303
+
4304
+ await endSessionById({ sessionId });
4305
+ await removeStateFile();
4306
+ }
4307
+
4308
+ pi.on("session_start", async (_event, ctx) => {
4309
+ isResidueAvailable = await checkResidueAvailable();
4310
+ if (!isResidueAvailable) return;
4311
+
4312
+ piVersion = await detectPiVersion();
4313
+
4314
+ // Clean up any leftover session from a previous run that
4315
+ // did not shut down cleanly.
4316
+ await endStaleSession();
4317
+
4318
+ const sessionFile = ctx.sessionManager.getSessionFile();
4319
+ await startResidueSession({ sessionFile });
4320
+ });
4321
+
4322
+ pi.on("session_switch", async (_event, ctx) => {
4323
+ if (!isResidueAvailable) return;
4324
+
4325
+ await endResidueSession();
4326
+
4327
+ const sessionFile = ctx.sessionManager.getSessionFile();
4328
+ await startResidueSession({ sessionFile });
4329
+ });
4330
+
4331
+ pi.on("session_shutdown", async () => {
4332
+ await endResidueSession();
4333
+ });
4334
+ }
4335
+ `;
4336
+
4337
+ // src/commands/setup.ts
4338
+ var log8 = createLogger("setup");
4339
+ var CLAUDE_HOOK_COMMAND = "residue hook claude-code";
4340
+ function hasResidueHook(entries) {
4341
+ return entries.some((entry) => entry.hooks.some((h) => h.command === CLAUDE_HOOK_COMMAND));
4342
+ }
4343
+ function setupClaudeCode(projectRoot) {
4344
+ const claudeDir = join5(projectRoot, ".claude");
4345
+ const settingsPath = join5(claudeDir, "settings.json");
4346
+ return ResultAsync.fromPromise((async () => {
4347
+ await mkdir5(claudeDir, { recursive: true });
4348
+ let settings = {};
4349
+ try {
4350
+ await stat4(settingsPath);
4351
+ const raw = await readFile3(settingsPath, "utf-8");
4352
+ settings = JSON.parse(raw);
4353
+ } catch {}
4354
+ if (!settings.hooks) {
4355
+ settings.hooks = {};
4356
+ }
4357
+ let isChanged = false;
4358
+ if (!settings.hooks.SessionStart) {
4359
+ settings.hooks.SessionStart = [];
4360
+ }
4361
+ if (!hasResidueHook(settings.hooks.SessionStart)) {
4362
+ settings.hooks.SessionStart.push({
4363
+ matcher: "startup",
4364
+ hooks: [
4365
+ { type: "command", command: CLAUDE_HOOK_COMMAND, timeout: 10 }
4366
+ ]
4367
+ });
4368
+ isChanged = true;
4369
+ }
4370
+ if (!settings.hooks.SessionEnd) {
4371
+ settings.hooks.SessionEnd = [];
4372
+ }
4373
+ if (!hasResidueHook(settings.hooks.SessionEnd)) {
4374
+ settings.hooks.SessionEnd.push({
4375
+ matcher: "",
4376
+ hooks: [
4377
+ { type: "command", command: CLAUDE_HOOK_COMMAND, timeout: 10 }
4378
+ ]
4379
+ });
4380
+ isChanged = true;
4381
+ }
4382
+ if (!isChanged) {
4383
+ log8.info("residue hooks already configured in .claude/settings.json");
4384
+ return;
4385
+ }
4386
+ await writeFile3(settingsPath, JSON.stringify(settings, null, 2) + `
4387
+ `);
4388
+ log8.info("Configured Claude Code hooks in .claude/settings.json");
4389
+ })(), toCliError({ message: "Failed to setup Claude Code", code: "IO_ERROR" }));
4390
+ }
4391
+ function setupPi(projectRoot) {
4392
+ const extensionDir = join5(projectRoot, ".pi", "extensions");
4393
+ const targetPath = join5(extensionDir, "residue.ts");
4394
+ return ResultAsync.fromPromise((async () => {
4395
+ await mkdir5(extensionDir, { recursive: true });
4396
+ let isExisting = false;
4397
+ try {
4398
+ await stat4(targetPath);
4399
+ isExisting = true;
4400
+ } catch {}
4401
+ if (isExisting) {
4402
+ log8.info("residue extension already exists at .pi/extensions/residue.ts");
4403
+ return;
4404
+ }
4405
+ await writeFile3(targetPath, extension_ts_default);
4406
+ log8.info("Installed pi extension at .pi/extensions/residue.ts");
4407
+ })(), toCliError({ message: "Failed to setup pi", code: "IO_ERROR" }));
4408
+ }
4409
+ function setup(opts) {
4410
+ return getProjectRoot().andThen((projectRoot) => {
4411
+ switch (opts.agent) {
4412
+ case "claude-code":
4413
+ return setupClaudeCode(projectRoot);
4414
+ case "pi":
4415
+ return setupPi(projectRoot);
4416
+ default:
4417
+ return errAsync(new CliError({
4418
+ message: `Unknown agent: ${opts.agent}. Supported: claude-code, pi`,
4419
+ code: "VALIDATION_ERROR"
4420
+ }));
4421
+ }
4422
+ });
4423
+ }
4424
+
4425
+ // src/index.ts
4426
+ var program2 = new Command;
4427
+ program2.name("residue").description("Capture AI agent conversations linked to git commits").version("0.0.1");
4428
+ program2.command("login").description("Save worker URL and auth token").requiredOption("--url <worker_url>", "Worker URL").requiredOption("--token <auth_token>", "Auth token").action(wrapCommand((opts) => login({ url: opts.url, token: opts.token })));
4429
+ program2.command("init").description("Install git hooks in current repo").action(wrapCommand(() => init()));
4430
+ program2.command("setup").description("Configure an agent adapter for this project").argument("<agent>", "Agent to set up (claude-code, pi)").action(wrapCommand((agent) => setup({ agent })));
4431
+ var hook = program2.command("hook").description("Agent hook handlers (called by agent plugins)");
4432
+ hook.command("claude-code").description("Handle Claude Code hook events (reads JSON from stdin)").action(wrapHookCommand(() => hookClaudeCode()));
4433
+ var session = program2.command("session").description("Manage agent sessions");
4434
+ session.command("start").description("Start tracking an agent session").requiredOption("--agent <name>", "Agent name").requiredOption("--data <path>", "Path to raw session file").option("--agent-version <semver>", "Agent version", "unknown").action(wrapCommand((opts) => sessionStart({
4435
+ agent: opts.agent,
4436
+ data: opts.data,
4437
+ agentVersion: opts.agentVersion
4438
+ })));
4439
+ session.command("end").description("Mark an agent session as ended").requiredOption("--id <session-id>", "Session ID to end").action(wrapCommand((opts) => sessionEnd({ id: opts.id })));
4440
+ program2.command("capture").description("Tag pending sessions with current commit SHA (called by post-commit hook)").action(wrapHookCommand(() => capture()));
4441
+ program2.command("sync").description("Upload pending sessions to worker (called by pre-push hook)").option("--remote-url <url>", "Remote URL (passed by pre-push hook)").action(wrapHookCommand((opts) => sync({ remoteUrl: opts.remoteUrl })));
4442
+ program2.command("push").description("Upload pending sessions to worker (manual trigger)").action(wrapCommand(() => push()));
4443
+ program2.parse();