@dccxx/auggiegw 1.0.19 → 1.0.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,555 +1,2696 @@
1
1
  #!/usr/bin/env node
2
- import { exec, spawn } from 'node:child_process';
3
- import * as fs from 'node:fs/promises';
4
- import { createRequire } from 'node:module';
5
- import * as os from 'node:os';
6
- import * as path from 'node:path';
7
- import * as readline from 'node:readline/promises';
8
- import { promisify } from 'node:util';
9
- import { Command } from 'commander';
10
- import { v4 as uuidv4 } from 'uuid';
11
- const require = createRequire(import.meta.url);
12
- const ora = require('ora');
13
- const execAsync = promisify(exec);
14
- const AUTH_DIR = path.join(os.homedir(), '.auggiegw');
15
- const AUTH_FILE = path.join(AUTH_DIR, 'auth.json');
16
- const AUGMENT_DIR = path.join(os.homedir(), '.augment');
17
- const AUGMENT_SESSION_FILE = path.join(AUGMENT_DIR, 'session.json');
18
- const AUGMENT_COMMANDS_DIR = path.join(AUGMENT_DIR, 'commands');
19
- function loadConfig() {
20
- const apiUrl = process.env.AUGMENT_GATEWAY_URL || 'https://augmentgateway.1app.space';
21
- return { apiUrl };
22
- }
23
- function getSessionOptions(opts) {
24
- const sessionOptions = {};
25
- // CLI flags take precedence
26
- if (opts.preserveSession) {
27
- sessionOptions.deleteSession = false;
2
+ import { createRequire } from "node:module";
3
+ var __create = Object.create;
4
+ var __getProtoOf = Object.getPrototypeOf;
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __toESM = (mod, isNodeMode, target) => {
9
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
10
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
11
+ for (let key of __getOwnPropNames(mod))
12
+ if (!__hasOwnProp.call(to, key))
13
+ __defProp(to, key, {
14
+ get: () => mod[key],
15
+ enumerable: true
16
+ });
17
+ return to;
18
+ };
19
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
20
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
21
+
22
+ // node_modules/commander/lib/error.js
23
+ var require_error = __commonJS((exports) => {
24
+ class CommanderError extends Error {
25
+ constructor(exitCode, code, message) {
26
+ super(message);
27
+ Error.captureStackTrace(this, this.constructor);
28
+ this.name = this.constructor.name;
29
+ this.code = code;
30
+ this.exitCode = exitCode;
31
+ this.nestedError = undefined;
28
32
  }
29
- else if (opts.deleteSession) {
30
- sessionOptions.deleteSession = true;
33
+ }
34
+
35
+ class InvalidArgumentError extends CommanderError {
36
+ constructor(message) {
37
+ super(1, "commander.invalidArgument", message);
38
+ Error.captureStackTrace(this, this.constructor);
39
+ this.name = this.constructor.name;
31
40
  }
32
- if (opts.authOnly) {
33
- sessionOptions.authOnly = true;
41
+ }
42
+ exports.CommanderError = CommanderError;
43
+ exports.InvalidArgumentError = InvalidArgumentError;
44
+ });
45
+
46
+ // node_modules/commander/lib/argument.js
47
+ var require_argument = __commonJS((exports) => {
48
+ var { InvalidArgumentError } = require_error();
49
+
50
+ class Argument {
51
+ constructor(name, description) {
52
+ this.description = description || "";
53
+ this.variadic = false;
54
+ this.parseArg = undefined;
55
+ this.defaultValue = undefined;
56
+ this.defaultValueDescription = undefined;
57
+ this.argChoices = undefined;
58
+ switch (name[0]) {
59
+ case "<":
60
+ this.required = true;
61
+ this._name = name.slice(1, -1);
62
+ break;
63
+ case "[":
64
+ this.required = false;
65
+ this._name = name.slice(1, -1);
66
+ break;
67
+ default:
68
+ this.required = true;
69
+ this._name = name;
70
+ break;
71
+ }
72
+ if (this._name.endsWith("...")) {
73
+ this.variadic = true;
74
+ this._name = this._name.slice(0, -3);
75
+ }
34
76
  }
35
- return sessionOptions;
36
- }
37
- function shouldDeleteSession(options) {
38
- // Priority: CLI flag > Environment variable > Default (true)
39
- if (options?.deleteSession !== undefined) {
40
- return options.deleteSession;
77
+ name() {
78
+ return this._name;
41
79
  }
42
- // Check environment variable
43
- if (process.env.AUGGIEGW_DELETE_SESSION !== undefined) {
44
- return process.env.AUGGIEGW_DELETE_SESSION !== 'false';
80
+ _collectValue(value, previous) {
81
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
82
+ return [value];
83
+ }
84
+ previous.push(value);
85
+ return previous;
45
86
  }
46
- // Default behavior: delete session
47
- return true;
48
- }
49
- async function ensureAuthDirectory() {
50
- try {
51
- await fs.mkdir(AUTH_DIR, { recursive: true });
87
+ default(value, description) {
88
+ this.defaultValue = value;
89
+ this.defaultValueDescription = description;
90
+ return this;
52
91
  }
53
- catch (error) {
54
- throw new Error(`Failed to create auth directory: ${error}`);
92
+ argParser(fn) {
93
+ this.parseArg = fn;
94
+ return this;
55
95
  }
56
- }
57
- async function saveAuthData(data) {
58
- await ensureAuthDirectory();
59
- await fs.writeFile(AUTH_FILE, JSON.stringify(data, null, 2), 'utf-8');
60
- }
61
- async function getAuthToken() {
62
- const envToken = process.env.AUGGIEGW_AUTH_TOKEN;
63
- if (envToken) {
64
- return envToken;
96
+ choices(values) {
97
+ this.argChoices = values.slice();
98
+ this.parseArg = (arg, previous) => {
99
+ if (!this.argChoices.includes(arg)) {
100
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
101
+ }
102
+ if (this.variadic) {
103
+ return this._collectValue(arg, previous);
104
+ }
105
+ return arg;
106
+ };
107
+ return this;
65
108
  }
66
- const authData = await loadAuthData();
67
- return authData.token;
68
- }
69
- async function loadAuthData() {
70
- try {
71
- const data = await fs.readFile(AUTH_FILE, 'utf-8');
72
- return JSON.parse(data);
109
+ argRequired() {
110
+ this.required = true;
111
+ return this;
73
112
  }
74
- catch (error) {
75
- if (error.code === 'ENOENT') {
76
- throw new Error('Not logged in. Please run "auggiegw login" first.');
113
+ argOptional() {
114
+ this.required = false;
115
+ return this;
116
+ }
117
+ }
118
+ function humanReadableArgName(arg) {
119
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
120
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
121
+ }
122
+ exports.Argument = Argument;
123
+ exports.humanReadableArgName = humanReadableArgName;
124
+ });
125
+
126
+ // node_modules/commander/lib/help.js
127
+ var require_help = __commonJS((exports) => {
128
+ var { humanReadableArgName } = require_argument();
129
+
130
+ class Help {
131
+ constructor() {
132
+ this.helpWidth = undefined;
133
+ this.minWidthToWrap = 40;
134
+ this.sortSubcommands = false;
135
+ this.sortOptions = false;
136
+ this.showGlobalOptions = false;
137
+ }
138
+ prepareContext(contextOptions) {
139
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
140
+ }
141
+ visibleCommands(cmd) {
142
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
143
+ const helpCommand = cmd._getHelpCommand();
144
+ if (helpCommand && !helpCommand._hidden) {
145
+ visibleCommands.push(helpCommand);
146
+ }
147
+ if (this.sortSubcommands) {
148
+ visibleCommands.sort((a, b) => {
149
+ return a.name().localeCompare(b.name());
150
+ });
151
+ }
152
+ return visibleCommands;
153
+ }
154
+ compareOptions(a, b) {
155
+ const getSortKey = (option) => {
156
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
157
+ };
158
+ return getSortKey(a).localeCompare(getSortKey(b));
159
+ }
160
+ visibleOptions(cmd) {
161
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
162
+ const helpOption = cmd._getHelpOption();
163
+ if (helpOption && !helpOption.hidden) {
164
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
165
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
166
+ if (!removeShort && !removeLong) {
167
+ visibleOptions.push(helpOption);
168
+ } else if (helpOption.long && !removeLong) {
169
+ visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
170
+ } else if (helpOption.short && !removeShort) {
171
+ visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
77
172
  }
78
- throw new Error(`Failed to load auth data: ${error}`);
173
+ }
174
+ if (this.sortOptions) {
175
+ visibleOptions.sort(this.compareOptions);
176
+ }
177
+ return visibleOptions;
79
178
  }
80
- }
81
- async function deleteAuthData() {
82
- try {
83
- await fs.unlink(AUTH_FILE);
179
+ visibleGlobalOptions(cmd) {
180
+ if (!this.showGlobalOptions)
181
+ return [];
182
+ const globalOptions = [];
183
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
184
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
185
+ globalOptions.push(...visibleOptions);
186
+ }
187
+ if (this.sortOptions) {
188
+ globalOptions.sort(this.compareOptions);
189
+ }
190
+ return globalOptions;
191
+ }
192
+ visibleArguments(cmd) {
193
+ if (cmd._argsDescription) {
194
+ cmd.registeredArguments.forEach((argument) => {
195
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
196
+ });
197
+ }
198
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
199
+ return cmd.registeredArguments;
200
+ }
201
+ return [];
202
+ }
203
+ subcommandTerm(cmd) {
204
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
205
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
206
+ }
207
+ optionTerm(option) {
208
+ return option.flags;
84
209
  }
85
- catch (error) {
86
- if (error.code !== 'ENOENT') {
87
- throw new Error(`Failed to delete auth file: ${error}`);
210
+ argumentTerm(argument) {
211
+ return argument.name();
212
+ }
213
+ longestSubcommandTermLength(cmd, helper) {
214
+ return helper.visibleCommands(cmd).reduce((max, command) => {
215
+ return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
216
+ }, 0);
217
+ }
218
+ longestOptionTermLength(cmd, helper) {
219
+ return helper.visibleOptions(cmd).reduce((max, option) => {
220
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
221
+ }, 0);
222
+ }
223
+ longestGlobalOptionTermLength(cmd, helper) {
224
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
225
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
226
+ }, 0);
227
+ }
228
+ longestArgumentTermLength(cmd, helper) {
229
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
230
+ return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
231
+ }, 0);
232
+ }
233
+ commandUsage(cmd) {
234
+ let cmdName = cmd._name;
235
+ if (cmd._aliases[0]) {
236
+ cmdName = cmdName + "|" + cmd._aliases[0];
237
+ }
238
+ let ancestorCmdNames = "";
239
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
240
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
241
+ }
242
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
243
+ }
244
+ commandDescription(cmd) {
245
+ return cmd.description();
246
+ }
247
+ subcommandDescription(cmd) {
248
+ return cmd.summary() || cmd.description();
249
+ }
250
+ optionDescription(option) {
251
+ const extraInfo = [];
252
+ if (option.argChoices) {
253
+ extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
254
+ }
255
+ if (option.defaultValue !== undefined) {
256
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
257
+ if (showDefault) {
258
+ extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
88
259
  }
260
+ }
261
+ if (option.presetArg !== undefined && option.optional) {
262
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
263
+ }
264
+ if (option.envVar !== undefined) {
265
+ extraInfo.push(`env: ${option.envVar}`);
266
+ }
267
+ if (extraInfo.length > 0) {
268
+ const extraDescription = `(${extraInfo.join(", ")})`;
269
+ if (option.description) {
270
+ return `${option.description} ${extraDescription}`;
271
+ }
272
+ return extraDescription;
273
+ }
274
+ return option.description;
89
275
  }
90
- }
91
- async function saveAugmentSession(session) {
92
- try {
93
- await fs.mkdir(AUGMENT_DIR, { recursive: true });
94
- await fs.writeFile(AUGMENT_SESSION_FILE, JSON.stringify(session, null, 2), 'utf-8');
276
+ argumentDescription(argument) {
277
+ const extraInfo = [];
278
+ if (argument.argChoices) {
279
+ extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
280
+ }
281
+ if (argument.defaultValue !== undefined) {
282
+ extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
283
+ }
284
+ if (extraInfo.length > 0) {
285
+ const extraDescription = `(${extraInfo.join(", ")})`;
286
+ if (argument.description) {
287
+ return `${argument.description} ${extraDescription}`;
288
+ }
289
+ return extraDescription;
290
+ }
291
+ return argument.description;
95
292
  }
96
- catch (error) {
97
- throw new Error(`Failed to save Augment session: ${error}`);
293
+ formatItemList(heading, items, helper) {
294
+ if (items.length === 0)
295
+ return [];
296
+ return [helper.styleTitle(heading), ...items, ""];
98
297
  }
99
- }
100
- async function getPrompts(token, apiUrl, page, limit) {
101
- const response = await fetch(`${apiUrl}/prompts?page=${page}&limit=${limit}`, {
102
- method: 'GET',
103
- headers: {
104
- Authorization: `Bearer ${token}`,
105
- },
298
+ groupItems(unsortedItems, visibleItems, getGroup) {
299
+ const result = new Map;
300
+ unsortedItems.forEach((item) => {
301
+ const group = getGroup(item);
302
+ if (!result.has(group))
303
+ result.set(group, []);
304
+ });
305
+ visibleItems.forEach((item) => {
306
+ const group = getGroup(item);
307
+ if (!result.has(group)) {
308
+ result.set(group, []);
309
+ }
310
+ result.get(group).push(item);
311
+ });
312
+ return result;
313
+ }
314
+ formatHelp(cmd, helper) {
315
+ const termWidth = helper.padWidth(cmd, helper);
316
+ const helpWidth = helper.helpWidth ?? 80;
317
+ function callFormatItem(term, description) {
318
+ return helper.formatItem(term, termWidth, description, helper);
319
+ }
320
+ let output = [
321
+ `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
322
+ ""
323
+ ];
324
+ const commandDescription = helper.commandDescription(cmd);
325
+ if (commandDescription.length > 0) {
326
+ output = output.concat([
327
+ helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth),
328
+ ""
329
+ ]);
330
+ }
331
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
332
+ return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
333
+ });
334
+ output = output.concat(this.formatItemList("Arguments:", argumentList, helper));
335
+ const optionGroups = this.groupItems(cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? "Options:");
336
+ optionGroups.forEach((options, group) => {
337
+ const optionList = options.map((option) => {
338
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
339
+ });
340
+ output = output.concat(this.formatItemList(group, optionList, helper));
341
+ });
342
+ if (helper.showGlobalOptions) {
343
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
344
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
345
+ });
346
+ output = output.concat(this.formatItemList("Global Options:", globalOptionList, helper));
347
+ }
348
+ const commandGroups = this.groupItems(cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || "Commands:");
349
+ commandGroups.forEach((commands, group) => {
350
+ const commandList = commands.map((sub) => {
351
+ return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)));
352
+ });
353
+ output = output.concat(this.formatItemList(group, commandList, helper));
354
+ });
355
+ return output.join(`
356
+ `);
357
+ }
358
+ displayWidth(str) {
359
+ return stripColor(str).length;
360
+ }
361
+ styleTitle(str) {
362
+ return str;
363
+ }
364
+ styleUsage(str) {
365
+ return str.split(" ").map((word) => {
366
+ if (word === "[options]")
367
+ return this.styleOptionText(word);
368
+ if (word === "[command]")
369
+ return this.styleSubcommandText(word);
370
+ if (word[0] === "[" || word[0] === "<")
371
+ return this.styleArgumentText(word);
372
+ return this.styleCommandText(word);
373
+ }).join(" ");
374
+ }
375
+ styleCommandDescription(str) {
376
+ return this.styleDescriptionText(str);
377
+ }
378
+ styleOptionDescription(str) {
379
+ return this.styleDescriptionText(str);
380
+ }
381
+ styleSubcommandDescription(str) {
382
+ return this.styleDescriptionText(str);
383
+ }
384
+ styleArgumentDescription(str) {
385
+ return this.styleDescriptionText(str);
386
+ }
387
+ styleDescriptionText(str) {
388
+ return str;
389
+ }
390
+ styleOptionTerm(str) {
391
+ return this.styleOptionText(str);
392
+ }
393
+ styleSubcommandTerm(str) {
394
+ return str.split(" ").map((word) => {
395
+ if (word === "[options]")
396
+ return this.styleOptionText(word);
397
+ if (word[0] === "[" || word[0] === "<")
398
+ return this.styleArgumentText(word);
399
+ return this.styleSubcommandText(word);
400
+ }).join(" ");
401
+ }
402
+ styleArgumentTerm(str) {
403
+ return this.styleArgumentText(str);
404
+ }
405
+ styleOptionText(str) {
406
+ return str;
407
+ }
408
+ styleArgumentText(str) {
409
+ return str;
410
+ }
411
+ styleSubcommandText(str) {
412
+ return str;
413
+ }
414
+ styleCommandText(str) {
415
+ return str;
416
+ }
417
+ padWidth(cmd, helper) {
418
+ return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
419
+ }
420
+ preformatted(str) {
421
+ return /\n[^\S\r\n]/.test(str);
422
+ }
423
+ formatItem(term, termWidth, description, helper) {
424
+ const itemIndent = 2;
425
+ const itemIndentStr = " ".repeat(itemIndent);
426
+ if (!description)
427
+ return itemIndentStr + term;
428
+ const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
429
+ const spacerWidth = 2;
430
+ const helpWidth = this.helpWidth ?? 80;
431
+ const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
432
+ let formattedDescription;
433
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
434
+ formattedDescription = description;
435
+ } else {
436
+ const wrappedDescription = helper.boxWrap(description, remainingWidth);
437
+ formattedDescription = wrappedDescription.replace(/\n/g, `
438
+ ` + " ".repeat(termWidth + spacerWidth));
439
+ }
440
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
441
+ ${itemIndentStr}`);
442
+ }
443
+ boxWrap(str, width) {
444
+ if (width < this.minWidthToWrap)
445
+ return str;
446
+ const rawLines = str.split(/\r\n|\n/);
447
+ const chunkPattern = /[\s]*[^\s]+/g;
448
+ const wrappedLines = [];
449
+ rawLines.forEach((line) => {
450
+ const chunks = line.match(chunkPattern);
451
+ if (chunks === null) {
452
+ wrappedLines.push("");
453
+ return;
454
+ }
455
+ let sumChunks = [chunks.shift()];
456
+ let sumWidth = this.displayWidth(sumChunks[0]);
457
+ chunks.forEach((chunk) => {
458
+ const visibleWidth = this.displayWidth(chunk);
459
+ if (sumWidth + visibleWidth <= width) {
460
+ sumChunks.push(chunk);
461
+ sumWidth += visibleWidth;
462
+ return;
463
+ }
464
+ wrappedLines.push(sumChunks.join(""));
465
+ const nextChunk = chunk.trimStart();
466
+ sumChunks = [nextChunk];
467
+ sumWidth = this.displayWidth(nextChunk);
468
+ });
469
+ wrappedLines.push(sumChunks.join(""));
470
+ });
471
+ return wrappedLines.join(`
472
+ `);
473
+ }
474
+ }
475
+ function stripColor(str) {
476
+ const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
477
+ return str.replace(sgrPattern, "");
478
+ }
479
+ exports.Help = Help;
480
+ exports.stripColor = stripColor;
481
+ });
482
+
483
+ // node_modules/commander/lib/option.js
484
+ var require_option = __commonJS((exports) => {
485
+ var { InvalidArgumentError } = require_error();
486
+
487
+ class Option {
488
+ constructor(flags, description) {
489
+ this.flags = flags;
490
+ this.description = description || "";
491
+ this.required = flags.includes("<");
492
+ this.optional = flags.includes("[");
493
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
494
+ this.mandatory = false;
495
+ const optionFlags = splitOptionFlags(flags);
496
+ this.short = optionFlags.shortFlag;
497
+ this.long = optionFlags.longFlag;
498
+ this.negate = false;
499
+ if (this.long) {
500
+ this.negate = this.long.startsWith("--no-");
501
+ }
502
+ this.defaultValue = undefined;
503
+ this.defaultValueDescription = undefined;
504
+ this.presetArg = undefined;
505
+ this.envVar = undefined;
506
+ this.parseArg = undefined;
507
+ this.hidden = false;
508
+ this.argChoices = undefined;
509
+ this.conflictsWith = [];
510
+ this.implied = undefined;
511
+ this.helpGroupHeading = undefined;
512
+ }
513
+ default(value, description) {
514
+ this.defaultValue = value;
515
+ this.defaultValueDescription = description;
516
+ return this;
517
+ }
518
+ preset(arg) {
519
+ this.presetArg = arg;
520
+ return this;
521
+ }
522
+ conflicts(names) {
523
+ this.conflictsWith = this.conflictsWith.concat(names);
524
+ return this;
525
+ }
526
+ implies(impliedOptionValues) {
527
+ let newImplied = impliedOptionValues;
528
+ if (typeof impliedOptionValues === "string") {
529
+ newImplied = { [impliedOptionValues]: true };
530
+ }
531
+ this.implied = Object.assign(this.implied || {}, newImplied);
532
+ return this;
533
+ }
534
+ env(name) {
535
+ this.envVar = name;
536
+ return this;
537
+ }
538
+ argParser(fn) {
539
+ this.parseArg = fn;
540
+ return this;
541
+ }
542
+ makeOptionMandatory(mandatory = true) {
543
+ this.mandatory = !!mandatory;
544
+ return this;
545
+ }
546
+ hideHelp(hide = true) {
547
+ this.hidden = !!hide;
548
+ return this;
549
+ }
550
+ _collectValue(value, previous) {
551
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
552
+ return [value];
553
+ }
554
+ previous.push(value);
555
+ return previous;
556
+ }
557
+ choices(values) {
558
+ this.argChoices = values.slice();
559
+ this.parseArg = (arg, previous) => {
560
+ if (!this.argChoices.includes(arg)) {
561
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
562
+ }
563
+ if (this.variadic) {
564
+ return this._collectValue(arg, previous);
565
+ }
566
+ return arg;
567
+ };
568
+ return this;
569
+ }
570
+ name() {
571
+ if (this.long) {
572
+ return this.long.replace(/^--/, "");
573
+ }
574
+ return this.short.replace(/^-/, "");
575
+ }
576
+ attributeName() {
577
+ if (this.negate) {
578
+ return camelcase(this.name().replace(/^no-/, ""));
579
+ }
580
+ return camelcase(this.name());
581
+ }
582
+ helpGroup(heading) {
583
+ this.helpGroupHeading = heading;
584
+ return this;
585
+ }
586
+ is(arg) {
587
+ return this.short === arg || this.long === arg;
588
+ }
589
+ isBoolean() {
590
+ return !this.required && !this.optional && !this.negate;
591
+ }
592
+ }
593
+
594
+ class DualOptions {
595
+ constructor(options) {
596
+ this.positiveOptions = new Map;
597
+ this.negativeOptions = new Map;
598
+ this.dualOptions = new Set;
599
+ options.forEach((option) => {
600
+ if (option.negate) {
601
+ this.negativeOptions.set(option.attributeName(), option);
602
+ } else {
603
+ this.positiveOptions.set(option.attributeName(), option);
604
+ }
605
+ });
606
+ this.negativeOptions.forEach((value, key) => {
607
+ if (this.positiveOptions.has(key)) {
608
+ this.dualOptions.add(key);
609
+ }
610
+ });
611
+ }
612
+ valueFromOption(value, option) {
613
+ const optionKey = option.attributeName();
614
+ if (!this.dualOptions.has(optionKey))
615
+ return true;
616
+ const preset = this.negativeOptions.get(optionKey).presetArg;
617
+ const negativeValue = preset !== undefined ? preset : false;
618
+ return option.negate === (negativeValue === value);
619
+ }
620
+ }
621
+ function camelcase(str) {
622
+ return str.split("-").reduce((str2, word) => {
623
+ return str2 + word[0].toUpperCase() + word.slice(1);
106
624
  });
107
- if (!response.ok) {
108
- throw new Error(`HTTP error! status: ${response.status}`);
625
+ }
626
+ function splitOptionFlags(flags) {
627
+ let shortFlag;
628
+ let longFlag;
629
+ const shortFlagExp = /^-[^-]$/;
630
+ const longFlagExp = /^--[^-]/;
631
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
632
+ if (shortFlagExp.test(flagParts[0]))
633
+ shortFlag = flagParts.shift();
634
+ if (longFlagExp.test(flagParts[0]))
635
+ longFlag = flagParts.shift();
636
+ if (!shortFlag && shortFlagExp.test(flagParts[0]))
637
+ shortFlag = flagParts.shift();
638
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
639
+ shortFlag = longFlag;
640
+ longFlag = flagParts.shift();
109
641
  }
110
- const data = (await response.json());
111
- if (!data.success) {
112
- throw new Error('Failed to get prompts');
642
+ if (flagParts[0].startsWith("-")) {
643
+ const unsupportedFlag = flagParts[0];
644
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
645
+ if (/^-[^-][^-]/.test(unsupportedFlag))
646
+ throw new Error(`${baseError}
647
+ - a short flag is a single dash and a single character
648
+ - either use a single dash and a single character (for a short flag)
649
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
650
+ if (shortFlagExp.test(unsupportedFlag))
651
+ throw new Error(`${baseError}
652
+ - too many short flags`);
653
+ if (longFlagExp.test(unsupportedFlag))
654
+ throw new Error(`${baseError}
655
+ - too many long flags`);
656
+ throw new Error(`${baseError}
657
+ - unrecognised flag format`);
113
658
  }
114
- return data;
115
- }
116
- async function getAllPrompts(token, apiUrl, spinner) {
117
- const allPrompts = [];
118
- const limit = 10;
119
- let currentPage = 1;
120
- let hasMorePages = true;
121
- while (hasMorePages) {
122
- if (spinner) {
123
- spinner.text = `Fetching prompts (page ${currentPage})...`;
124
- }
125
- const response = await getPrompts(token, apiUrl, currentPage, limit);
126
- if (response.data.prompts && response.data.prompts.length > 0) {
127
- allPrompts.push(...response.data.prompts);
128
- if (response.data.totalPages) {
129
- hasMorePages = currentPage < response.data.totalPages;
659
+ if (shortFlag === undefined && longFlag === undefined)
660
+ throw new Error(`option creation failed due to no flags found in '${flags}'.`);
661
+ return { shortFlag, longFlag };
662
+ }
663
+ exports.Option = Option;
664
+ exports.DualOptions = DualOptions;
665
+ });
666
+
667
+ // node_modules/commander/lib/suggestSimilar.js
668
+ var require_suggestSimilar = __commonJS((exports) => {
669
+ var maxDistance = 3;
670
+ function editDistance(a, b) {
671
+ if (Math.abs(a.length - b.length) > maxDistance)
672
+ return Math.max(a.length, b.length);
673
+ const d = [];
674
+ for (let i = 0;i <= a.length; i++) {
675
+ d[i] = [i];
676
+ }
677
+ for (let j = 0;j <= b.length; j++) {
678
+ d[0][j] = j;
679
+ }
680
+ for (let j = 1;j <= b.length; j++) {
681
+ for (let i = 1;i <= a.length; i++) {
682
+ let cost = 1;
683
+ if (a[i - 1] === b[j - 1]) {
684
+ cost = 0;
685
+ } else {
686
+ cost = 1;
687
+ }
688
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
689
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
690
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
691
+ }
692
+ }
693
+ }
694
+ return d[a.length][b.length];
695
+ }
696
+ function suggestSimilar(word, candidates) {
697
+ if (!candidates || candidates.length === 0)
698
+ return "";
699
+ candidates = Array.from(new Set(candidates));
700
+ const searchingOptions = word.startsWith("--");
701
+ if (searchingOptions) {
702
+ word = word.slice(2);
703
+ candidates = candidates.map((candidate) => candidate.slice(2));
704
+ }
705
+ let similar = [];
706
+ let bestDistance = maxDistance;
707
+ const minSimilarity = 0.4;
708
+ candidates.forEach((candidate) => {
709
+ if (candidate.length <= 1)
710
+ return;
711
+ const distance = editDistance(word, candidate);
712
+ const length = Math.max(word.length, candidate.length);
713
+ const similarity = (length - distance) / length;
714
+ if (similarity > minSimilarity) {
715
+ if (distance < bestDistance) {
716
+ bestDistance = distance;
717
+ similar = [candidate];
718
+ } else if (distance === bestDistance) {
719
+ similar.push(candidate);
720
+ }
721
+ }
722
+ });
723
+ similar.sort((a, b) => a.localeCompare(b));
724
+ if (searchingOptions) {
725
+ similar = similar.map((candidate) => `--${candidate}`);
726
+ }
727
+ if (similar.length > 1) {
728
+ return `
729
+ (Did you mean one of ${similar.join(", ")}?)`;
730
+ }
731
+ if (similar.length === 1) {
732
+ return `
733
+ (Did you mean ${similar[0]}?)`;
734
+ }
735
+ return "";
736
+ }
737
+ exports.suggestSimilar = suggestSimilar;
738
+ });
739
+
740
+ // node_modules/commander/lib/command.js
741
+ var require_command = __commonJS((exports) => {
742
+ var EventEmitter = __require("node:events").EventEmitter;
743
+ var childProcess = __require("node:child_process");
744
+ var path = __require("node:path");
745
+ var fs = __require("node:fs");
746
+ var process2 = __require("node:process");
747
+ var { Argument, humanReadableArgName } = require_argument();
748
+ var { CommanderError } = require_error();
749
+ var { Help, stripColor } = require_help();
750
+ var { Option, DualOptions } = require_option();
751
+ var { suggestSimilar } = require_suggestSimilar();
752
+
753
+ class Command extends EventEmitter {
754
+ constructor(name) {
755
+ super();
756
+ this.commands = [];
757
+ this.options = [];
758
+ this.parent = null;
759
+ this._allowUnknownOption = false;
760
+ this._allowExcessArguments = false;
761
+ this.registeredArguments = [];
762
+ this._args = this.registeredArguments;
763
+ this.args = [];
764
+ this.rawArgs = [];
765
+ this.processedArgs = [];
766
+ this._scriptPath = null;
767
+ this._name = name || "";
768
+ this._optionValues = {};
769
+ this._optionValueSources = {};
770
+ this._storeOptionsAsProperties = false;
771
+ this._actionHandler = null;
772
+ this._executableHandler = false;
773
+ this._executableFile = null;
774
+ this._executableDir = null;
775
+ this._defaultCommandName = null;
776
+ this._exitCallback = null;
777
+ this._aliases = [];
778
+ this._combineFlagAndOptionalValue = true;
779
+ this._description = "";
780
+ this._summary = "";
781
+ this._argsDescription = undefined;
782
+ this._enablePositionalOptions = false;
783
+ this._passThroughOptions = false;
784
+ this._lifeCycleHooks = {};
785
+ this._showHelpAfterError = false;
786
+ this._showSuggestionAfterError = true;
787
+ this._savedState = null;
788
+ this._outputConfiguration = {
789
+ writeOut: (str) => process2.stdout.write(str),
790
+ writeErr: (str) => process2.stderr.write(str),
791
+ outputError: (str, write) => write(str),
792
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : undefined,
793
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : undefined,
794
+ getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
795
+ getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
796
+ stripColor: (str) => stripColor(str)
797
+ };
798
+ this._hidden = false;
799
+ this._helpOption = undefined;
800
+ this._addImplicitHelpCommand = undefined;
801
+ this._helpCommand = undefined;
802
+ this._helpConfiguration = {};
803
+ this._helpGroupHeading = undefined;
804
+ this._defaultCommandGroup = undefined;
805
+ this._defaultOptionGroup = undefined;
806
+ }
807
+ copyInheritedSettings(sourceCommand) {
808
+ this._outputConfiguration = sourceCommand._outputConfiguration;
809
+ this._helpOption = sourceCommand._helpOption;
810
+ this._helpCommand = sourceCommand._helpCommand;
811
+ this._helpConfiguration = sourceCommand._helpConfiguration;
812
+ this._exitCallback = sourceCommand._exitCallback;
813
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
814
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
815
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
816
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
817
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
818
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
819
+ return this;
820
+ }
821
+ _getCommandAndAncestors() {
822
+ const result = [];
823
+ for (let command = this;command; command = command.parent) {
824
+ result.push(command);
825
+ }
826
+ return result;
827
+ }
828
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
829
+ let desc = actionOptsOrExecDesc;
830
+ let opts = execOpts;
831
+ if (typeof desc === "object" && desc !== null) {
832
+ opts = desc;
833
+ desc = null;
834
+ }
835
+ opts = opts || {};
836
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
837
+ const cmd = this.createCommand(name);
838
+ if (desc) {
839
+ cmd.description(desc);
840
+ cmd._executableHandler = true;
841
+ }
842
+ if (opts.isDefault)
843
+ this._defaultCommandName = cmd._name;
844
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
845
+ cmd._executableFile = opts.executableFile || null;
846
+ if (args)
847
+ cmd.arguments(args);
848
+ this._registerCommand(cmd);
849
+ cmd.parent = this;
850
+ cmd.copyInheritedSettings(this);
851
+ if (desc)
852
+ return this;
853
+ return cmd;
854
+ }
855
+ createCommand(name) {
856
+ return new Command(name);
857
+ }
858
+ createHelp() {
859
+ return Object.assign(new Help, this.configureHelp());
860
+ }
861
+ configureHelp(configuration) {
862
+ if (configuration === undefined)
863
+ return this._helpConfiguration;
864
+ this._helpConfiguration = configuration;
865
+ return this;
866
+ }
867
+ configureOutput(configuration) {
868
+ if (configuration === undefined)
869
+ return this._outputConfiguration;
870
+ this._outputConfiguration = {
871
+ ...this._outputConfiguration,
872
+ ...configuration
873
+ };
874
+ return this;
875
+ }
876
+ showHelpAfterError(displayHelp = true) {
877
+ if (typeof displayHelp !== "string")
878
+ displayHelp = !!displayHelp;
879
+ this._showHelpAfterError = displayHelp;
880
+ return this;
881
+ }
882
+ showSuggestionAfterError(displaySuggestion = true) {
883
+ this._showSuggestionAfterError = !!displaySuggestion;
884
+ return this;
885
+ }
886
+ addCommand(cmd, opts) {
887
+ if (!cmd._name) {
888
+ throw new Error(`Command passed to .addCommand() must have a name
889
+ - specify the name in Command constructor or using .name()`);
890
+ }
891
+ opts = opts || {};
892
+ if (opts.isDefault)
893
+ this._defaultCommandName = cmd._name;
894
+ if (opts.noHelp || opts.hidden)
895
+ cmd._hidden = true;
896
+ this._registerCommand(cmd);
897
+ cmd.parent = this;
898
+ cmd._checkForBrokenPassThrough();
899
+ return this;
900
+ }
901
+ createArgument(name, description) {
902
+ return new Argument(name, description);
903
+ }
904
+ argument(name, description, parseArg, defaultValue) {
905
+ const argument = this.createArgument(name, description);
906
+ if (typeof parseArg === "function") {
907
+ argument.default(defaultValue).argParser(parseArg);
908
+ } else {
909
+ argument.default(parseArg);
910
+ }
911
+ this.addArgument(argument);
912
+ return this;
913
+ }
914
+ arguments(names) {
915
+ names.trim().split(/ +/).forEach((detail) => {
916
+ this.argument(detail);
917
+ });
918
+ return this;
919
+ }
920
+ addArgument(argument) {
921
+ const previousArgument = this.registeredArguments.slice(-1)[0];
922
+ if (previousArgument?.variadic) {
923
+ throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
924
+ }
925
+ if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {
926
+ throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
927
+ }
928
+ this.registeredArguments.push(argument);
929
+ return this;
930
+ }
931
+ helpCommand(enableOrNameAndArgs, description) {
932
+ if (typeof enableOrNameAndArgs === "boolean") {
933
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
934
+ if (enableOrNameAndArgs && this._defaultCommandGroup) {
935
+ this._initCommandGroup(this._getHelpCommand());
936
+ }
937
+ return this;
938
+ }
939
+ const nameAndArgs = enableOrNameAndArgs ?? "help [command]";
940
+ const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
941
+ const helpDescription = description ?? "display help for command";
942
+ const helpCommand = this.createCommand(helpName);
943
+ helpCommand.helpOption(false);
944
+ if (helpArgs)
945
+ helpCommand.arguments(helpArgs);
946
+ if (helpDescription)
947
+ helpCommand.description(helpDescription);
948
+ this._addImplicitHelpCommand = true;
949
+ this._helpCommand = helpCommand;
950
+ if (enableOrNameAndArgs || description)
951
+ this._initCommandGroup(helpCommand);
952
+ return this;
953
+ }
954
+ addHelpCommand(helpCommand, deprecatedDescription) {
955
+ if (typeof helpCommand !== "object") {
956
+ this.helpCommand(helpCommand, deprecatedDescription);
957
+ return this;
958
+ }
959
+ this._addImplicitHelpCommand = true;
960
+ this._helpCommand = helpCommand;
961
+ this._initCommandGroup(helpCommand);
962
+ return this;
963
+ }
964
+ _getHelpCommand() {
965
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
966
+ if (hasImplicitHelpCommand) {
967
+ if (this._helpCommand === undefined) {
968
+ this.helpCommand(undefined, undefined);
969
+ }
970
+ return this._helpCommand;
971
+ }
972
+ return null;
973
+ }
974
+ hook(event, listener) {
975
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
976
+ if (!allowedValues.includes(event)) {
977
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
978
+ Expecting one of '${allowedValues.join("', '")}'`);
979
+ }
980
+ if (this._lifeCycleHooks[event]) {
981
+ this._lifeCycleHooks[event].push(listener);
982
+ } else {
983
+ this._lifeCycleHooks[event] = [listener];
984
+ }
985
+ return this;
986
+ }
987
+ exitOverride(fn) {
988
+ if (fn) {
989
+ this._exitCallback = fn;
990
+ } else {
991
+ this._exitCallback = (err) => {
992
+ if (err.code !== "commander.executeSubCommandAsync") {
993
+ throw err;
994
+ } else {}
995
+ };
996
+ }
997
+ return this;
998
+ }
999
+ _exit(exitCode, code, message) {
1000
+ if (this._exitCallback) {
1001
+ this._exitCallback(new CommanderError(exitCode, code, message));
1002
+ }
1003
+ process2.exit(exitCode);
1004
+ }
1005
+ action(fn) {
1006
+ const listener = (args) => {
1007
+ const expectedArgsCount = this.registeredArguments.length;
1008
+ const actionArgs = args.slice(0, expectedArgsCount);
1009
+ if (this._storeOptionsAsProperties) {
1010
+ actionArgs[expectedArgsCount] = this;
1011
+ } else {
1012
+ actionArgs[expectedArgsCount] = this.opts();
1013
+ }
1014
+ actionArgs.push(this);
1015
+ return fn.apply(this, actionArgs);
1016
+ };
1017
+ this._actionHandler = listener;
1018
+ return this;
1019
+ }
1020
+ createOption(flags, description) {
1021
+ return new Option(flags, description);
1022
+ }
1023
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1024
+ try {
1025
+ return target.parseArg(value, previous);
1026
+ } catch (err) {
1027
+ if (err.code === "commander.invalidArgument") {
1028
+ const message = `${invalidArgumentMessage} ${err.message}`;
1029
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1030
+ }
1031
+ throw err;
1032
+ }
1033
+ }
1034
+ _registerOption(option) {
1035
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1036
+ if (matchingOption) {
1037
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1038
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1039
+ - already used by option '${matchingOption.flags}'`);
1040
+ }
1041
+ this._initOptionGroup(option);
1042
+ this.options.push(option);
1043
+ }
1044
+ _registerCommand(command) {
1045
+ const knownBy = (cmd) => {
1046
+ return [cmd.name()].concat(cmd.aliases());
1047
+ };
1048
+ const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
1049
+ if (alreadyUsed) {
1050
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1051
+ const newCmd = knownBy(command).join("|");
1052
+ throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
1053
+ }
1054
+ this._initCommandGroup(command);
1055
+ this.commands.push(command);
1056
+ }
1057
+ addOption(option) {
1058
+ this._registerOption(option);
1059
+ const oname = option.name();
1060
+ const name = option.attributeName();
1061
+ if (option.negate) {
1062
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1063
+ if (!this._findOption(positiveLongFlag)) {
1064
+ this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, "default");
1065
+ }
1066
+ } else if (option.defaultValue !== undefined) {
1067
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
1068
+ }
1069
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1070
+ if (val == null && option.presetArg !== undefined) {
1071
+ val = option.presetArg;
1072
+ }
1073
+ const oldValue = this.getOptionValue(name);
1074
+ if (val !== null && option.parseArg) {
1075
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1076
+ } else if (val !== null && option.variadic) {
1077
+ val = option._collectValue(val, oldValue);
1078
+ }
1079
+ if (val == null) {
1080
+ if (option.negate) {
1081
+ val = false;
1082
+ } else if (option.isBoolean() || option.optional) {
1083
+ val = true;
1084
+ } else {
1085
+ val = "";
1086
+ }
1087
+ }
1088
+ this.setOptionValueWithSource(name, val, valueSource);
1089
+ };
1090
+ this.on("option:" + oname, (val) => {
1091
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1092
+ handleOptionValue(val, invalidValueMessage, "cli");
1093
+ });
1094
+ if (option.envVar) {
1095
+ this.on("optionEnv:" + oname, (val) => {
1096
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1097
+ handleOptionValue(val, invalidValueMessage, "env");
1098
+ });
1099
+ }
1100
+ return this;
1101
+ }
1102
+ _optionEx(config, flags, description, fn, defaultValue) {
1103
+ if (typeof flags === "object" && flags instanceof Option) {
1104
+ throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
1105
+ }
1106
+ const option = this.createOption(flags, description);
1107
+ option.makeOptionMandatory(!!config.mandatory);
1108
+ if (typeof fn === "function") {
1109
+ option.default(defaultValue).argParser(fn);
1110
+ } else if (fn instanceof RegExp) {
1111
+ const regex = fn;
1112
+ fn = (val, def) => {
1113
+ const m = regex.exec(val);
1114
+ return m ? m[0] : def;
1115
+ };
1116
+ option.default(defaultValue).argParser(fn);
1117
+ } else {
1118
+ option.default(fn);
1119
+ }
1120
+ return this.addOption(option);
1121
+ }
1122
+ option(flags, description, parseArg, defaultValue) {
1123
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1124
+ }
1125
+ requiredOption(flags, description, parseArg, defaultValue) {
1126
+ return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
1127
+ }
1128
+ combineFlagAndOptionalValue(combine = true) {
1129
+ this._combineFlagAndOptionalValue = !!combine;
1130
+ return this;
1131
+ }
1132
+ allowUnknownOption(allowUnknown = true) {
1133
+ this._allowUnknownOption = !!allowUnknown;
1134
+ return this;
1135
+ }
1136
+ allowExcessArguments(allowExcess = true) {
1137
+ this._allowExcessArguments = !!allowExcess;
1138
+ return this;
1139
+ }
1140
+ enablePositionalOptions(positional = true) {
1141
+ this._enablePositionalOptions = !!positional;
1142
+ return this;
1143
+ }
1144
+ passThroughOptions(passThrough = true) {
1145
+ this._passThroughOptions = !!passThrough;
1146
+ this._checkForBrokenPassThrough();
1147
+ return this;
1148
+ }
1149
+ _checkForBrokenPassThrough() {
1150
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1151
+ throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
1152
+ }
1153
+ }
1154
+ storeOptionsAsProperties(storeAsProperties = true) {
1155
+ if (this.options.length) {
1156
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1157
+ }
1158
+ if (Object.keys(this._optionValues).length) {
1159
+ throw new Error("call .storeOptionsAsProperties() before setting option values");
1160
+ }
1161
+ this._storeOptionsAsProperties = !!storeAsProperties;
1162
+ return this;
1163
+ }
1164
+ getOptionValue(key) {
1165
+ if (this._storeOptionsAsProperties) {
1166
+ return this[key];
1167
+ }
1168
+ return this._optionValues[key];
1169
+ }
1170
+ setOptionValue(key, value) {
1171
+ return this.setOptionValueWithSource(key, value, undefined);
1172
+ }
1173
+ setOptionValueWithSource(key, value, source) {
1174
+ if (this._storeOptionsAsProperties) {
1175
+ this[key] = value;
1176
+ } else {
1177
+ this._optionValues[key] = value;
1178
+ }
1179
+ this._optionValueSources[key] = source;
1180
+ return this;
1181
+ }
1182
+ getOptionValueSource(key) {
1183
+ return this._optionValueSources[key];
1184
+ }
1185
+ getOptionValueSourceWithGlobals(key) {
1186
+ let source;
1187
+ this._getCommandAndAncestors().forEach((cmd) => {
1188
+ if (cmd.getOptionValueSource(key) !== undefined) {
1189
+ source = cmd.getOptionValueSource(key);
1190
+ }
1191
+ });
1192
+ return source;
1193
+ }
1194
+ _prepareUserArgs(argv, parseOptions) {
1195
+ if (argv !== undefined && !Array.isArray(argv)) {
1196
+ throw new Error("first parameter to parse must be array or undefined");
1197
+ }
1198
+ parseOptions = parseOptions || {};
1199
+ if (argv === undefined && parseOptions.from === undefined) {
1200
+ if (process2.versions?.electron) {
1201
+ parseOptions.from = "electron";
1202
+ }
1203
+ const execArgv = process2.execArgv ?? [];
1204
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1205
+ parseOptions.from = "eval";
1206
+ }
1207
+ }
1208
+ if (argv === undefined) {
1209
+ argv = process2.argv;
1210
+ }
1211
+ this.rawArgs = argv.slice();
1212
+ let userArgs;
1213
+ switch (parseOptions.from) {
1214
+ case undefined:
1215
+ case "node":
1216
+ this._scriptPath = argv[1];
1217
+ userArgs = argv.slice(2);
1218
+ break;
1219
+ case "electron":
1220
+ if (process2.defaultApp) {
1221
+ this._scriptPath = argv[1];
1222
+ userArgs = argv.slice(2);
1223
+ } else {
1224
+ userArgs = argv.slice(1);
1225
+ }
1226
+ break;
1227
+ case "user":
1228
+ userArgs = argv.slice(0);
1229
+ break;
1230
+ case "eval":
1231
+ userArgs = argv.slice(1);
1232
+ break;
1233
+ default:
1234
+ throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1235
+ }
1236
+ if (!this._name && this._scriptPath)
1237
+ this.nameFromFilename(this._scriptPath);
1238
+ this._name = this._name || "program";
1239
+ return userArgs;
1240
+ }
1241
+ parse(argv, parseOptions) {
1242
+ this._prepareForParse();
1243
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1244
+ this._parseCommand([], userArgs);
1245
+ return this;
1246
+ }
1247
+ async parseAsync(argv, parseOptions) {
1248
+ this._prepareForParse();
1249
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1250
+ await this._parseCommand([], userArgs);
1251
+ return this;
1252
+ }
1253
+ _prepareForParse() {
1254
+ if (this._savedState === null) {
1255
+ this.saveStateBeforeParse();
1256
+ } else {
1257
+ this.restoreStateBeforeParse();
1258
+ }
1259
+ }
1260
+ saveStateBeforeParse() {
1261
+ this._savedState = {
1262
+ _name: this._name,
1263
+ _optionValues: { ...this._optionValues },
1264
+ _optionValueSources: { ...this._optionValueSources }
1265
+ };
1266
+ }
1267
+ restoreStateBeforeParse() {
1268
+ if (this._storeOptionsAsProperties)
1269
+ throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
1270
+ - either make a new Command for each call to parse, or stop storing options as properties`);
1271
+ this._name = this._savedState._name;
1272
+ this._scriptPath = null;
1273
+ this.rawArgs = [];
1274
+ this._optionValues = { ...this._savedState._optionValues };
1275
+ this._optionValueSources = { ...this._savedState._optionValueSources };
1276
+ this.args = [];
1277
+ this.processedArgs = [];
1278
+ }
1279
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
1280
+ if (fs.existsSync(executableFile))
1281
+ return;
1282
+ 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";
1283
+ const executableMissing = `'${executableFile}' does not exist
1284
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1285
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1286
+ - ${executableDirMessage}`;
1287
+ throw new Error(executableMissing);
1288
+ }
1289
+ _executeSubCommand(subcommand, args) {
1290
+ args = args.slice();
1291
+ let launchWithNode = false;
1292
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1293
+ function findFile(baseDir, baseName) {
1294
+ const localBin = path.resolve(baseDir, baseName);
1295
+ if (fs.existsSync(localBin))
1296
+ return localBin;
1297
+ if (sourceExt.includes(path.extname(baseName)))
1298
+ return;
1299
+ const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
1300
+ if (foundExt)
1301
+ return `${localBin}${foundExt}`;
1302
+ return;
1303
+ }
1304
+ this._checkForMissingMandatoryOptions();
1305
+ this._checkForConflictingOptions();
1306
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1307
+ let executableDir = this._executableDir || "";
1308
+ if (this._scriptPath) {
1309
+ let resolvedScriptPath;
1310
+ try {
1311
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1312
+ } catch {
1313
+ resolvedScriptPath = this._scriptPath;
1314
+ }
1315
+ executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
1316
+ }
1317
+ if (executableDir) {
1318
+ let localFile = findFile(executableDir, executableFile);
1319
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1320
+ const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
1321
+ if (legacyName !== this._name) {
1322
+ localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1323
+ }
1324
+ }
1325
+ executableFile = localFile || executableFile;
1326
+ }
1327
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
1328
+ let proc;
1329
+ if (process2.platform !== "win32") {
1330
+ if (launchWithNode) {
1331
+ args.unshift(executableFile);
1332
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1333
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
1334
+ } else {
1335
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1336
+ }
1337
+ } else {
1338
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1339
+ args.unshift(executableFile);
1340
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1341
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
1342
+ }
1343
+ if (!proc.killed) {
1344
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1345
+ signals.forEach((signal) => {
1346
+ process2.on(signal, () => {
1347
+ if (proc.killed === false && proc.exitCode === null) {
1348
+ proc.kill(signal);
130
1349
  }
131
- else if (response.data.total) {
132
- const calculatedTotalPages = Math.ceil(response.data.total / limit);
133
- hasMorePages = currentPage < calculatedTotalPages;
1350
+ });
1351
+ });
1352
+ }
1353
+ const exitCallback = this._exitCallback;
1354
+ proc.on("close", (code) => {
1355
+ code = code ?? 1;
1356
+ if (!exitCallback) {
1357
+ process2.exit(code);
1358
+ } else {
1359
+ exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
1360
+ }
1361
+ });
1362
+ proc.on("error", (err) => {
1363
+ if (err.code === "ENOENT") {
1364
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1365
+ } else if (err.code === "EACCES") {
1366
+ throw new Error(`'${executableFile}' not executable`);
1367
+ }
1368
+ if (!exitCallback) {
1369
+ process2.exit(1);
1370
+ } else {
1371
+ const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
1372
+ wrappedError.nestedError = err;
1373
+ exitCallback(wrappedError);
1374
+ }
1375
+ });
1376
+ this.runningCommand = proc;
1377
+ }
1378
+ _dispatchSubcommand(commandName, operands, unknown) {
1379
+ const subCommand = this._findCommand(commandName);
1380
+ if (!subCommand)
1381
+ this.help({ error: true });
1382
+ subCommand._prepareForParse();
1383
+ let promiseChain;
1384
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
1385
+ promiseChain = this._chainOrCall(promiseChain, () => {
1386
+ if (subCommand._executableHandler) {
1387
+ this._executeSubCommand(subCommand, operands.concat(unknown));
1388
+ } else {
1389
+ return subCommand._parseCommand(operands, unknown);
1390
+ }
1391
+ });
1392
+ return promiseChain;
1393
+ }
1394
+ _dispatchHelpCommand(subcommandName) {
1395
+ if (!subcommandName) {
1396
+ this.help();
1397
+ }
1398
+ const subCommand = this._findCommand(subcommandName);
1399
+ if (subCommand && !subCommand._executableHandler) {
1400
+ subCommand.help();
1401
+ }
1402
+ return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
1403
+ }
1404
+ _checkNumberOfArguments() {
1405
+ this.registeredArguments.forEach((arg, i) => {
1406
+ if (arg.required && this.args[i] == null) {
1407
+ this.missingArgument(arg.name());
1408
+ }
1409
+ });
1410
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
1411
+ return;
1412
+ }
1413
+ if (this.args.length > this.registeredArguments.length) {
1414
+ this._excessArguments(this.args);
1415
+ }
1416
+ }
1417
+ _processArguments() {
1418
+ const myParseArg = (argument, value, previous) => {
1419
+ let parsedValue = value;
1420
+ if (value !== null && argument.parseArg) {
1421
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
1422
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
1423
+ }
1424
+ return parsedValue;
1425
+ };
1426
+ this._checkNumberOfArguments();
1427
+ const processedArgs = [];
1428
+ this.registeredArguments.forEach((declaredArg, index) => {
1429
+ let value = declaredArg.defaultValue;
1430
+ if (declaredArg.variadic) {
1431
+ if (index < this.args.length) {
1432
+ value = this.args.slice(index);
1433
+ if (declaredArg.parseArg) {
1434
+ value = value.reduce((processed, v) => {
1435
+ return myParseArg(declaredArg, v, processed);
1436
+ }, declaredArg.defaultValue);
134
1437
  }
135
- else {
136
- hasMorePages = response.data.prompts.length === limit;
1438
+ } else if (value === undefined) {
1439
+ value = [];
1440
+ }
1441
+ } else if (index < this.args.length) {
1442
+ value = this.args[index];
1443
+ if (declaredArg.parseArg) {
1444
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
1445
+ }
1446
+ }
1447
+ processedArgs[index] = value;
1448
+ });
1449
+ this.processedArgs = processedArgs;
1450
+ }
1451
+ _chainOrCall(promise, fn) {
1452
+ if (promise?.then && typeof promise.then === "function") {
1453
+ return promise.then(() => fn());
1454
+ }
1455
+ return fn();
1456
+ }
1457
+ _chainOrCallHooks(promise, event) {
1458
+ let result = promise;
1459
+ const hooks = [];
1460
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== undefined).forEach((hookedCommand) => {
1461
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
1462
+ hooks.push({ hookedCommand, callback });
1463
+ });
1464
+ });
1465
+ if (event === "postAction") {
1466
+ hooks.reverse();
1467
+ }
1468
+ hooks.forEach((hookDetail) => {
1469
+ result = this._chainOrCall(result, () => {
1470
+ return hookDetail.callback(hookDetail.hookedCommand, this);
1471
+ });
1472
+ });
1473
+ return result;
1474
+ }
1475
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
1476
+ let result = promise;
1477
+ if (this._lifeCycleHooks[event] !== undefined) {
1478
+ this._lifeCycleHooks[event].forEach((hook) => {
1479
+ result = this._chainOrCall(result, () => {
1480
+ return hook(this, subCommand);
1481
+ });
1482
+ });
1483
+ }
1484
+ return result;
1485
+ }
1486
+ _parseCommand(operands, unknown) {
1487
+ const parsed = this.parseOptions(unknown);
1488
+ this._parseOptionsEnv();
1489
+ this._parseOptionsImplied();
1490
+ operands = operands.concat(parsed.operands);
1491
+ unknown = parsed.unknown;
1492
+ this.args = operands.concat(unknown);
1493
+ if (operands && this._findCommand(operands[0])) {
1494
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
1495
+ }
1496
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
1497
+ return this._dispatchHelpCommand(operands[1]);
1498
+ }
1499
+ if (this._defaultCommandName) {
1500
+ this._outputHelpIfRequested(unknown);
1501
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
1502
+ }
1503
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
1504
+ this.help({ error: true });
1505
+ }
1506
+ this._outputHelpIfRequested(parsed.unknown);
1507
+ this._checkForMissingMandatoryOptions();
1508
+ this._checkForConflictingOptions();
1509
+ const checkForUnknownOptions = () => {
1510
+ if (parsed.unknown.length > 0) {
1511
+ this.unknownOption(parsed.unknown[0]);
1512
+ }
1513
+ };
1514
+ const commandEvent = `command:${this.name()}`;
1515
+ if (this._actionHandler) {
1516
+ checkForUnknownOptions();
1517
+ this._processArguments();
1518
+ let promiseChain;
1519
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
1520
+ promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
1521
+ if (this.parent) {
1522
+ promiseChain = this._chainOrCall(promiseChain, () => {
1523
+ this.parent.emit(commandEvent, operands, unknown);
1524
+ });
1525
+ }
1526
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
1527
+ return promiseChain;
1528
+ }
1529
+ if (this.parent?.listenerCount(commandEvent)) {
1530
+ checkForUnknownOptions();
1531
+ this._processArguments();
1532
+ this.parent.emit(commandEvent, operands, unknown);
1533
+ } else if (operands.length) {
1534
+ if (this._findCommand("*")) {
1535
+ return this._dispatchSubcommand("*", operands, unknown);
1536
+ }
1537
+ if (this.listenerCount("command:*")) {
1538
+ this.emit("command:*", operands, unknown);
1539
+ } else if (this.commands.length) {
1540
+ this.unknownCommand();
1541
+ } else {
1542
+ checkForUnknownOptions();
1543
+ this._processArguments();
1544
+ }
1545
+ } else if (this.commands.length) {
1546
+ checkForUnknownOptions();
1547
+ this.help({ error: true });
1548
+ } else {
1549
+ checkForUnknownOptions();
1550
+ this._processArguments();
1551
+ }
1552
+ }
1553
+ _findCommand(name) {
1554
+ if (!name)
1555
+ return;
1556
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
1557
+ }
1558
+ _findOption(arg) {
1559
+ return this.options.find((option) => option.is(arg));
1560
+ }
1561
+ _checkForMissingMandatoryOptions() {
1562
+ this._getCommandAndAncestors().forEach((cmd) => {
1563
+ cmd.options.forEach((anOption) => {
1564
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === undefined) {
1565
+ cmd.missingMandatoryOptionValue(anOption);
1566
+ }
1567
+ });
1568
+ });
1569
+ }
1570
+ _checkForConflictingLocalOptions() {
1571
+ const definedNonDefaultOptions = this.options.filter((option) => {
1572
+ const optionKey = option.attributeName();
1573
+ if (this.getOptionValue(optionKey) === undefined) {
1574
+ return false;
1575
+ }
1576
+ return this.getOptionValueSource(optionKey) !== "default";
1577
+ });
1578
+ const optionsWithConflicting = definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0);
1579
+ optionsWithConflicting.forEach((option) => {
1580
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
1581
+ if (conflictingAndDefined) {
1582
+ this._conflictingOption(option, conflictingAndDefined);
1583
+ }
1584
+ });
1585
+ }
1586
+ _checkForConflictingOptions() {
1587
+ this._getCommandAndAncestors().forEach((cmd) => {
1588
+ cmd._checkForConflictingLocalOptions();
1589
+ });
1590
+ }
1591
+ parseOptions(args) {
1592
+ const operands = [];
1593
+ const unknown = [];
1594
+ let dest = operands;
1595
+ function maybeOption(arg) {
1596
+ return arg.length > 1 && arg[0] === "-";
1597
+ }
1598
+ const negativeNumberArg = (arg) => {
1599
+ if (!/^-\d*\.?\d+(e[+-]?\d+)?$/.test(arg))
1600
+ return false;
1601
+ return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short)));
1602
+ };
1603
+ let activeVariadicOption = null;
1604
+ let activeGroup = null;
1605
+ let i = 0;
1606
+ while (i < args.length || activeGroup) {
1607
+ const arg = activeGroup ?? args[i++];
1608
+ activeGroup = null;
1609
+ if (arg === "--") {
1610
+ if (dest === unknown)
1611
+ dest.push(arg);
1612
+ dest.push(...args.slice(i));
1613
+ break;
1614
+ }
1615
+ if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
1616
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
1617
+ continue;
1618
+ }
1619
+ activeVariadicOption = null;
1620
+ if (maybeOption(arg)) {
1621
+ const option = this._findOption(arg);
1622
+ if (option) {
1623
+ if (option.required) {
1624
+ const value = args[i++];
1625
+ if (value === undefined)
1626
+ this.optionMissingArgument(option);
1627
+ this.emit(`option:${option.name()}`, value);
1628
+ } else if (option.optional) {
1629
+ let value = null;
1630
+ if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) {
1631
+ value = args[i++];
1632
+ }
1633
+ this.emit(`option:${option.name()}`, value);
1634
+ } else {
1635
+ this.emit(`option:${option.name()}`);
1636
+ }
1637
+ activeVariadicOption = option.variadic ? option : null;
1638
+ continue;
1639
+ }
1640
+ }
1641
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
1642
+ const option = this._findOption(`-${arg[1]}`);
1643
+ if (option) {
1644
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
1645
+ this.emit(`option:${option.name()}`, arg.slice(2));
1646
+ } else {
1647
+ this.emit(`option:${option.name()}`);
1648
+ activeGroup = `-${arg.slice(2)}`;
137
1649
  }
138
- if (hasMorePages) {
139
- await new Promise((resolve) => setTimeout(resolve, 500));
1650
+ continue;
1651
+ }
1652
+ }
1653
+ if (/^--[^=]+=/.test(arg)) {
1654
+ const index = arg.indexOf("=");
1655
+ const option = this._findOption(arg.slice(0, index));
1656
+ if (option && (option.required || option.optional)) {
1657
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
1658
+ continue;
1659
+ }
1660
+ }
1661
+ if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) {
1662
+ dest = unknown;
1663
+ }
1664
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
1665
+ if (this._findCommand(arg)) {
1666
+ operands.push(arg);
1667
+ unknown.push(...args.slice(i));
1668
+ break;
1669
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
1670
+ operands.push(arg, ...args.slice(i));
1671
+ break;
1672
+ } else if (this._defaultCommandName) {
1673
+ unknown.push(arg, ...args.slice(i));
1674
+ break;
1675
+ }
1676
+ }
1677
+ if (this._passThroughOptions) {
1678
+ dest.push(arg, ...args.slice(i));
1679
+ break;
1680
+ }
1681
+ dest.push(arg);
1682
+ }
1683
+ return { operands, unknown };
1684
+ }
1685
+ opts() {
1686
+ if (this._storeOptionsAsProperties) {
1687
+ const result = {};
1688
+ const len = this.options.length;
1689
+ for (let i = 0;i < len; i++) {
1690
+ const key = this.options[i].attributeName();
1691
+ result[key] = key === this._versionOptionName ? this._version : this[key];
1692
+ }
1693
+ return result;
1694
+ }
1695
+ return this._optionValues;
1696
+ }
1697
+ optsWithGlobals() {
1698
+ return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
1699
+ }
1700
+ error(message, errorOptions) {
1701
+ this._outputConfiguration.outputError(`${message}
1702
+ `, this._outputConfiguration.writeErr);
1703
+ if (typeof this._showHelpAfterError === "string") {
1704
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
1705
+ `);
1706
+ } else if (this._showHelpAfterError) {
1707
+ this._outputConfiguration.writeErr(`
1708
+ `);
1709
+ this.outputHelp({ error: true });
1710
+ }
1711
+ const config = errorOptions || {};
1712
+ const exitCode = config.exitCode || 1;
1713
+ const code = config.code || "commander.error";
1714
+ this._exit(exitCode, code, message);
1715
+ }
1716
+ _parseOptionsEnv() {
1717
+ this.options.forEach((option) => {
1718
+ if (option.envVar && option.envVar in process2.env) {
1719
+ const optionKey = option.attributeName();
1720
+ if (this.getOptionValue(optionKey) === undefined || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
1721
+ if (option.required || option.optional) {
1722
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
1723
+ } else {
1724
+ this.emit(`optionEnv:${option.name()}`);
140
1725
  }
141
- currentPage++;
1726
+ }
1727
+ }
1728
+ });
1729
+ }
1730
+ _parseOptionsImplied() {
1731
+ const dualHelper = new DualOptions(this.options);
1732
+ const hasCustomOptionValue = (optionKey) => {
1733
+ return this.getOptionValue(optionKey) !== undefined && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
1734
+ };
1735
+ this.options.filter((option) => option.implied !== undefined && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
1736
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
1737
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
1738
+ });
1739
+ });
1740
+ }
1741
+ missingArgument(name) {
1742
+ const message = `error: missing required argument '${name}'`;
1743
+ this.error(message, { code: "commander.missingArgument" });
1744
+ }
1745
+ optionMissingArgument(option) {
1746
+ const message = `error: option '${option.flags}' argument missing`;
1747
+ this.error(message, { code: "commander.optionMissingArgument" });
1748
+ }
1749
+ missingMandatoryOptionValue(option) {
1750
+ const message = `error: required option '${option.flags}' not specified`;
1751
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
1752
+ }
1753
+ _conflictingOption(option, conflictingOption) {
1754
+ const findBestOptionFromValue = (option2) => {
1755
+ const optionKey = option2.attributeName();
1756
+ const optionValue = this.getOptionValue(optionKey);
1757
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
1758
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
1759
+ if (negativeOption && (negativeOption.presetArg === undefined && optionValue === false || negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)) {
1760
+ return negativeOption;
142
1761
  }
143
- else {
144
- hasMorePages = false;
1762
+ return positiveOption || option2;
1763
+ };
1764
+ const getErrorMessage = (option2) => {
1765
+ const bestOption = findBestOptionFromValue(option2);
1766
+ const optionKey = bestOption.attributeName();
1767
+ const source = this.getOptionValueSource(optionKey);
1768
+ if (source === "env") {
1769
+ return `environment variable '${bestOption.envVar}'`;
145
1770
  }
1771
+ return `option '${bestOption.flags}'`;
1772
+ };
1773
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
1774
+ this.error(message, { code: "commander.conflictingOption" });
1775
+ }
1776
+ unknownOption(flag) {
1777
+ if (this._allowUnknownOption)
1778
+ return;
1779
+ let suggestion = "";
1780
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
1781
+ let candidateFlags = [];
1782
+ let command = this;
1783
+ do {
1784
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
1785
+ candidateFlags = candidateFlags.concat(moreFlags);
1786
+ command = command.parent;
1787
+ } while (command && !command._enablePositionalOptions);
1788
+ suggestion = suggestSimilar(flag, candidateFlags);
1789
+ }
1790
+ const message = `error: unknown option '${flag}'${suggestion}`;
1791
+ this.error(message, { code: "commander.unknownOption" });
1792
+ }
1793
+ _excessArguments(receivedArgs) {
1794
+ if (this._allowExcessArguments)
1795
+ return;
1796
+ const expected = this.registeredArguments.length;
1797
+ const s = expected === 1 ? "" : "s";
1798
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
1799
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
1800
+ this.error(message, { code: "commander.excessArguments" });
1801
+ }
1802
+ unknownCommand() {
1803
+ const unknownName = this.args[0];
1804
+ let suggestion = "";
1805
+ if (this._showSuggestionAfterError) {
1806
+ const candidateNames = [];
1807
+ this.createHelp().visibleCommands(this).forEach((command) => {
1808
+ candidateNames.push(command.name());
1809
+ if (command.alias())
1810
+ candidateNames.push(command.alias());
1811
+ });
1812
+ suggestion = suggestSimilar(unknownName, candidateNames);
1813
+ }
1814
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
1815
+ this.error(message, { code: "commander.unknownCommand" });
1816
+ }
1817
+ version(str, flags, description) {
1818
+ if (str === undefined)
1819
+ return this._version;
1820
+ this._version = str;
1821
+ flags = flags || "-V, --version";
1822
+ description = description || "output the version number";
1823
+ const versionOption = this.createOption(flags, description);
1824
+ this._versionOptionName = versionOption.attributeName();
1825
+ this._registerOption(versionOption);
1826
+ this.on("option:" + versionOption.name(), () => {
1827
+ this._outputConfiguration.writeOut(`${str}
1828
+ `);
1829
+ this._exit(0, "commander.version", str);
1830
+ });
1831
+ return this;
1832
+ }
1833
+ description(str, argsDescription) {
1834
+ if (str === undefined && argsDescription === undefined)
1835
+ return this._description;
1836
+ this._description = str;
1837
+ if (argsDescription) {
1838
+ this._argsDescription = argsDescription;
1839
+ }
1840
+ return this;
1841
+ }
1842
+ summary(str) {
1843
+ if (str === undefined)
1844
+ return this._summary;
1845
+ this._summary = str;
1846
+ return this;
1847
+ }
1848
+ alias(alias) {
1849
+ if (alias === undefined)
1850
+ return this._aliases[0];
1851
+ let command = this;
1852
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
1853
+ command = this.commands[this.commands.length - 1];
1854
+ }
1855
+ if (alias === command._name)
1856
+ throw new Error("Command alias can't be the same as its name");
1857
+ const matchingCommand = this.parent?._findCommand(alias);
1858
+ if (matchingCommand) {
1859
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
1860
+ throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
1861
+ }
1862
+ command._aliases.push(alias);
1863
+ return this;
1864
+ }
1865
+ aliases(aliases) {
1866
+ if (aliases === undefined)
1867
+ return this._aliases;
1868
+ aliases.forEach((alias) => this.alias(alias));
1869
+ return this;
1870
+ }
1871
+ usage(str) {
1872
+ if (str === undefined) {
1873
+ if (this._usage)
1874
+ return this._usage;
1875
+ const args = this.registeredArguments.map((arg) => {
1876
+ return humanReadableArgName(arg);
1877
+ });
1878
+ return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
1879
+ }
1880
+ this._usage = str;
1881
+ return this;
1882
+ }
1883
+ name(str) {
1884
+ if (str === undefined)
1885
+ return this._name;
1886
+ this._name = str;
1887
+ return this;
146
1888
  }
147
- return allPrompts;
1889
+ helpGroup(heading) {
1890
+ if (heading === undefined)
1891
+ return this._helpGroupHeading ?? "";
1892
+ this._helpGroupHeading = heading;
1893
+ return this;
1894
+ }
1895
+ commandsGroup(heading) {
1896
+ if (heading === undefined)
1897
+ return this._defaultCommandGroup ?? "";
1898
+ this._defaultCommandGroup = heading;
1899
+ return this;
1900
+ }
1901
+ optionsGroup(heading) {
1902
+ if (heading === undefined)
1903
+ return this._defaultOptionGroup ?? "";
1904
+ this._defaultOptionGroup = heading;
1905
+ return this;
1906
+ }
1907
+ _initOptionGroup(option) {
1908
+ if (this._defaultOptionGroup && !option.helpGroupHeading)
1909
+ option.helpGroup(this._defaultOptionGroup);
1910
+ }
1911
+ _initCommandGroup(cmd) {
1912
+ if (this._defaultCommandGroup && !cmd.helpGroup())
1913
+ cmd.helpGroup(this._defaultCommandGroup);
1914
+ }
1915
+ nameFromFilename(filename) {
1916
+ this._name = path.basename(filename, path.extname(filename));
1917
+ return this;
1918
+ }
1919
+ executableDir(path2) {
1920
+ if (path2 === undefined)
1921
+ return this._executableDir;
1922
+ this._executableDir = path2;
1923
+ return this;
1924
+ }
1925
+ helpInformation(contextOptions) {
1926
+ const helper = this.createHelp();
1927
+ const context = this._getOutputContext(contextOptions);
1928
+ helper.prepareContext({
1929
+ error: context.error,
1930
+ helpWidth: context.helpWidth,
1931
+ outputHasColors: context.hasColors
1932
+ });
1933
+ const text = helper.formatHelp(this, helper);
1934
+ if (context.hasColors)
1935
+ return text;
1936
+ return this._outputConfiguration.stripColor(text);
1937
+ }
1938
+ _getOutputContext(contextOptions) {
1939
+ contextOptions = contextOptions || {};
1940
+ const error = !!contextOptions.error;
1941
+ let baseWrite;
1942
+ let hasColors;
1943
+ let helpWidth;
1944
+ if (error) {
1945
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
1946
+ hasColors = this._outputConfiguration.getErrHasColors();
1947
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
1948
+ } else {
1949
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
1950
+ hasColors = this._outputConfiguration.getOutHasColors();
1951
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
1952
+ }
1953
+ const write = (str) => {
1954
+ if (!hasColors)
1955
+ str = this._outputConfiguration.stripColor(str);
1956
+ return baseWrite(str);
1957
+ };
1958
+ return { error, write, hasColors, helpWidth };
1959
+ }
1960
+ outputHelp(contextOptions) {
1961
+ let deprecatedCallback;
1962
+ if (typeof contextOptions === "function") {
1963
+ deprecatedCallback = contextOptions;
1964
+ contextOptions = undefined;
1965
+ }
1966
+ const outputContext = this._getOutputContext(contextOptions);
1967
+ const eventContext = {
1968
+ error: outputContext.error,
1969
+ write: outputContext.write,
1970
+ command: this
1971
+ };
1972
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
1973
+ this.emit("beforeHelp", eventContext);
1974
+ let helpInformation = this.helpInformation({ error: outputContext.error });
1975
+ if (deprecatedCallback) {
1976
+ helpInformation = deprecatedCallback(helpInformation);
1977
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
1978
+ throw new Error("outputHelp callback must return a string or a Buffer");
1979
+ }
1980
+ }
1981
+ outputContext.write(helpInformation);
1982
+ if (this._getHelpOption()?.long) {
1983
+ this.emit(this._getHelpOption().long);
1984
+ }
1985
+ this.emit("afterHelp", eventContext);
1986
+ this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
1987
+ }
1988
+ helpOption(flags, description) {
1989
+ if (typeof flags === "boolean") {
1990
+ if (flags) {
1991
+ if (this._helpOption === null)
1992
+ this._helpOption = undefined;
1993
+ if (this._defaultOptionGroup) {
1994
+ this._initOptionGroup(this._getHelpOption());
1995
+ }
1996
+ } else {
1997
+ this._helpOption = null;
1998
+ }
1999
+ return this;
2000
+ }
2001
+ this._helpOption = this.createOption(flags ?? "-h, --help", description ?? "display help for command");
2002
+ if (flags || description)
2003
+ this._initOptionGroup(this._helpOption);
2004
+ return this;
2005
+ }
2006
+ _getHelpOption() {
2007
+ if (this._helpOption === undefined) {
2008
+ this.helpOption(undefined, undefined);
2009
+ }
2010
+ return this._helpOption;
2011
+ }
2012
+ addHelpOption(option) {
2013
+ this._helpOption = option;
2014
+ this._initOptionGroup(option);
2015
+ return this;
2016
+ }
2017
+ help(contextOptions) {
2018
+ this.outputHelp(contextOptions);
2019
+ let exitCode = Number(process2.exitCode ?? 0);
2020
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
2021
+ exitCode = 1;
2022
+ }
2023
+ this._exit(exitCode, "commander.help", "(outputHelp)");
2024
+ }
2025
+ addHelpText(position, text) {
2026
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
2027
+ if (!allowedValues.includes(position)) {
2028
+ throw new Error(`Unexpected value for position to addHelpText.
2029
+ Expecting one of '${allowedValues.join("', '")}'`);
2030
+ }
2031
+ const helpEvent = `${position}Help`;
2032
+ this.on(helpEvent, (context) => {
2033
+ let helpStr;
2034
+ if (typeof text === "function") {
2035
+ helpStr = text({ error: context.error, command: context.command });
2036
+ } else {
2037
+ helpStr = text;
2038
+ }
2039
+ if (helpStr) {
2040
+ context.write(`${helpStr}
2041
+ `);
2042
+ }
2043
+ });
2044
+ return this;
2045
+ }
2046
+ _outputHelpIfRequested(args) {
2047
+ const helpOption = this._getHelpOption();
2048
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
2049
+ if (helpRequested) {
2050
+ this.outputHelp();
2051
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
2052
+ }
2053
+ }
2054
+ }
2055
+ function incrementNodeInspectorPort(args) {
2056
+ return args.map((arg) => {
2057
+ if (!arg.startsWith("--inspect")) {
2058
+ return arg;
2059
+ }
2060
+ let debugOption;
2061
+ let debugHost = "127.0.0.1";
2062
+ let debugPort = "9229";
2063
+ let match;
2064
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
2065
+ debugOption = match[1];
2066
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2067
+ debugOption = match[1];
2068
+ if (/^\d+$/.test(match[3])) {
2069
+ debugPort = match[3];
2070
+ } else {
2071
+ debugHost = match[3];
2072
+ }
2073
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
2074
+ debugOption = match[1];
2075
+ debugHost = match[3];
2076
+ debugPort = match[4];
2077
+ }
2078
+ if (debugOption && debugPort !== "0") {
2079
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2080
+ }
2081
+ return arg;
2082
+ });
2083
+ }
2084
+ function useColor() {
2085
+ if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
2086
+ return false;
2087
+ if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== undefined)
2088
+ return true;
2089
+ return;
2090
+ }
2091
+ exports.Command = Command;
2092
+ exports.useColor = useColor;
2093
+ });
2094
+
2095
+ // node_modules/commander/index.js
2096
+ var require_commander = __commonJS((exports) => {
2097
+ var { Argument } = require_argument();
2098
+ var { Command } = require_command();
2099
+ var { CommanderError, InvalidArgumentError } = require_error();
2100
+ var { Help } = require_help();
2101
+ var { Option } = require_option();
2102
+ exports.program = new Command;
2103
+ exports.createCommand = (name) => new Command(name);
2104
+ exports.createOption = (flags, description) => new Option(flags, description);
2105
+ exports.createArgument = (name, description) => new Argument(name, description);
2106
+ exports.Command = Command;
2107
+ exports.Option = Option;
2108
+ exports.Argument = Argument;
2109
+ exports.Help = Help;
2110
+ exports.CommanderError = CommanderError;
2111
+ exports.InvalidArgumentError = InvalidArgumentError;
2112
+ exports.InvalidOptionArgumentError = InvalidArgumentError;
2113
+ });
2114
+
2115
+ // src/cli.ts
2116
+ import { exec, spawn } from "node:child_process";
2117
+ import * as fs from "node:fs/promises";
2118
+ import { createRequire as createRequire2 } from "node:module";
2119
+ import * as os from "node:os";
2120
+ import * as path from "node:path";
2121
+ import * as readline from "node:readline/promises";
2122
+ import { promisify } from "node:util";
2123
+
2124
+ // node_modules/commander/esm.mjs
2125
+ var import__ = __toESM(require_commander(), 1);
2126
+ var {
2127
+ program,
2128
+ createCommand,
2129
+ createArgument,
2130
+ createOption,
2131
+ CommanderError,
2132
+ InvalidArgumentError,
2133
+ InvalidOptionArgumentError,
2134
+ Command,
2135
+ Argument,
2136
+ Option,
2137
+ Help
2138
+ } = import__.default;
2139
+
2140
+ // node_modules/uuid/dist-node/stringify.js
2141
+ var byteToHex = [];
2142
+ for (let i = 0;i < 256; ++i) {
2143
+ byteToHex.push((i + 256).toString(16).slice(1));
2144
+ }
2145
+ function unsafeStringify(arr, offset = 0) {
2146
+ return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
2147
+ }
2148
+
2149
+ // node_modules/uuid/dist-node/rng.js
2150
+ import { randomFillSync } from "node:crypto";
2151
+ var rnds8Pool = new Uint8Array(256);
2152
+ var poolPtr = rnds8Pool.length;
2153
+ function rng() {
2154
+ if (poolPtr > rnds8Pool.length - 16) {
2155
+ randomFillSync(rnds8Pool);
2156
+ poolPtr = 0;
2157
+ }
2158
+ return rnds8Pool.slice(poolPtr, poolPtr += 16);
2159
+ }
2160
+
2161
+ // node_modules/uuid/dist-node/native.js
2162
+ import { randomUUID } from "node:crypto";
2163
+ var native_default = { randomUUID };
2164
+
2165
+ // node_modules/uuid/dist-node/v4.js
2166
+ function _v4(options, buf, offset) {
2167
+ options = options || {};
2168
+ const rnds = options.random ?? options.rng?.() ?? rng();
2169
+ if (rnds.length < 16) {
2170
+ throw new Error("Random bytes length must be >= 16");
2171
+ }
2172
+ rnds[6] = rnds[6] & 15 | 64;
2173
+ rnds[8] = rnds[8] & 63 | 128;
2174
+ if (buf) {
2175
+ offset = offset || 0;
2176
+ if (offset < 0 || offset + 16 > buf.length) {
2177
+ throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);
2178
+ }
2179
+ for (let i = 0;i < 16; ++i) {
2180
+ buf[offset + i] = rnds[i];
2181
+ }
2182
+ return buf;
2183
+ }
2184
+ return unsafeStringify(rnds);
2185
+ }
2186
+ function v4(options, buf, offset) {
2187
+ if (native_default.randomUUID && !buf && !options) {
2188
+ return native_default.randomUUID();
2189
+ }
2190
+ return _v4(options, buf, offset);
2191
+ }
2192
+ var v4_default = v4;
2193
+ // src/cli.ts
2194
+ var require2 = createRequire2(import.meta.url);
2195
+ var ora = require2("ora");
2196
+ var execAsync = promisify(exec);
2197
+ var AUTH_DIR = path.join(os.homedir(), ".auggiegw");
2198
+ var AUTH_FILE = path.join(AUTH_DIR, "auth.json");
2199
+ var AUGMENT_DIR = path.join(os.homedir(), ".augment");
2200
+ var AUGMENT_SESSION_FILE = path.join(AUGMENT_DIR, "session.json");
2201
+ var AUGMENT_COMMANDS_DIR = path.join(AUGMENT_DIR, "commands");
2202
+ function loadConfig() {
2203
+ const apiUrl = process.env.AUGMENT_GATEWAY_URL || "https://augmentgateway.1app.space";
2204
+ return { apiUrl };
2205
+ }
2206
+ function getSessionOptions(opts) {
2207
+ const sessionOptions = {};
2208
+ if (opts.preserveSession) {
2209
+ sessionOptions.deleteSession = false;
2210
+ } else if (opts.deleteSession) {
2211
+ sessionOptions.deleteSession = true;
2212
+ }
2213
+ if (opts.authOnly) {
2214
+ sessionOptions.authOnly = true;
2215
+ }
2216
+ if (opts.refreshCommands) {
2217
+ sessionOptions.refreshCommands = true;
2218
+ }
2219
+ return sessionOptions;
2220
+ }
2221
+ function shouldDeleteSession(options) {
2222
+ if (options?.deleteSession !== undefined) {
2223
+ return options.deleteSession;
2224
+ }
2225
+ if (process.env.AUGGIEGW_DELETE_SESSION !== undefined) {
2226
+ return process.env.AUGGIEGW_DELETE_SESSION !== "false";
2227
+ }
2228
+ return true;
2229
+ }
2230
+ async function ensureAuthDirectory() {
2231
+ try {
2232
+ await fs.mkdir(AUTH_DIR, { recursive: true });
2233
+ } catch (error) {
2234
+ throw new Error(`Failed to create auth directory: ${error}`);
2235
+ }
2236
+ }
2237
+ async function saveAuthData(data) {
2238
+ await ensureAuthDirectory();
2239
+ await fs.writeFile(AUTH_FILE, JSON.stringify(data, null, 2), "utf-8");
2240
+ }
2241
+ async function getAuthToken() {
2242
+ const envToken = process.env.AUGGIEGW_AUTH_TOKEN;
2243
+ if (envToken) {
2244
+ return envToken;
2245
+ }
2246
+ const authData = await loadAuthData();
2247
+ return authData.token;
2248
+ }
2249
+ async function loadAuthData() {
2250
+ try {
2251
+ const data = await fs.readFile(AUTH_FILE, "utf-8");
2252
+ return JSON.parse(data);
2253
+ } catch (error) {
2254
+ if (error.code === "ENOENT") {
2255
+ throw new Error('Not logged in. Please run "auggiegw login" first.');
2256
+ }
2257
+ throw new Error(`Failed to load auth data: ${error}`);
2258
+ }
2259
+ }
2260
+ async function deleteAuthData() {
2261
+ try {
2262
+ await fs.unlink(AUTH_FILE);
2263
+ } catch (error) {
2264
+ if (error.code !== "ENOENT") {
2265
+ throw new Error(`Failed to delete auth file: ${error}`);
2266
+ }
2267
+ }
2268
+ }
2269
+ async function saveAugmentSession(session) {
2270
+ try {
2271
+ await fs.mkdir(AUGMENT_DIR, { recursive: true });
2272
+ await fs.writeFile(AUGMENT_SESSION_FILE, JSON.stringify(session, null, 2), "utf-8");
2273
+ } catch (error) {
2274
+ throw new Error(`Failed to save Augment session: ${error}`);
2275
+ }
2276
+ }
2277
+ async function getPrompts(token, apiUrl, page, limit) {
2278
+ const response = await fetch(`${apiUrl}/prompts?page=${page}&limit=${limit}`, {
2279
+ method: "GET",
2280
+ headers: {
2281
+ Authorization: `Bearer ${token}`
2282
+ }
2283
+ });
2284
+ if (!response.ok) {
2285
+ throw new Error(`HTTP error! status: ${response.status}`);
2286
+ }
2287
+ const data = await response.json();
2288
+ if (!data.success) {
2289
+ throw new Error("Failed to get prompts");
2290
+ }
2291
+ return data;
2292
+ }
2293
+ async function getAllPrompts(token, apiUrl, spinner) {
2294
+ const allPrompts = [];
2295
+ const limit = 10;
2296
+ let currentPage = 1;
2297
+ let hasMorePages = true;
2298
+ while (hasMorePages) {
2299
+ if (spinner) {
2300
+ spinner.text = `Fetching prompts (page ${currentPage})...`;
2301
+ }
2302
+ const response = await getPrompts(token, apiUrl, currentPage, limit);
2303
+ if (response.data.prompts && response.data.prompts.length > 0) {
2304
+ allPrompts.push(...response.data.prompts);
2305
+ if (response.data.totalPages) {
2306
+ hasMorePages = currentPage < response.data.totalPages;
2307
+ } else if (response.data.total) {
2308
+ const calculatedTotalPages = Math.ceil(response.data.total / limit);
2309
+ hasMorePages = currentPage < calculatedTotalPages;
2310
+ } else {
2311
+ hasMorePages = response.data.prompts.length === limit;
2312
+ }
2313
+ if (hasMorePages) {
2314
+ await new Promise((resolve) => setTimeout(resolve, 500));
2315
+ }
2316
+ currentPage++;
2317
+ } else {
2318
+ hasMorePages = false;
2319
+ }
2320
+ }
2321
+ return allPrompts;
148
2322
  }
149
2323
  async function savePromptToFile(prompt) {
150
- try {
151
- await fs.mkdir(AUGMENT_COMMANDS_DIR, { recursive: true });
152
- const markdownContent = `---
2324
+ try {
2325
+ await fs.mkdir(AUGMENT_COMMANDS_DIR, { recursive: true });
2326
+ const markdownContent = `---
153
2327
  description: ${prompt.name}
154
2328
  ---
155
2329
 
156
2330
  ${prompt.content}`;
157
- const filePath = path.join(AUGMENT_COMMANDS_DIR, `${prompt.command}.md`);
158
- await fs.writeFile(filePath, markdownContent, 'utf-8');
159
- }
160
- catch (error) {
161
- throw new Error(`Failed to save prompt file for command '${prompt.command}': ${error}`);
162
- }
2331
+ const filePath = path.join(AUGMENT_COMMANDS_DIR, `${prompt.command}.md`);
2332
+ await fs.writeFile(filePath, markdownContent, "utf-8");
2333
+ } catch (error) {
2334
+ throw new Error(`Failed to save prompt file for command '${prompt.command}': ${error}`);
2335
+ }
2336
+ }
2337
+ async function deleteAllCommandFiles() {
2338
+ try {
2339
+ await fs.access(AUGMENT_COMMANDS_DIR);
2340
+ } catch {
2341
+ return 0;
2342
+ }
2343
+ const files = await fs.readdir(AUGMENT_COMMANDS_DIR);
2344
+ const mdFiles = files.filter((file) => file.endsWith(".md"));
2345
+ for (const file of mdFiles) {
2346
+ await fs.unlink(path.join(AUGMENT_COMMANDS_DIR, file));
2347
+ }
2348
+ return mdFiles.length;
163
2349
  }
164
2350
  async function promptInput(question, hidden = false) {
165
- const rl = readline.createInterface({
166
- input: process.stdin,
167
- output: process.stdout,
168
- });
169
- if (hidden) {
170
- const originalWrite = process.stdout.write.bind(process.stdout);
171
- process.stdout.write = (chunk, encoding, callback) => {
172
- if (chunk.toString().includes(question)) {
173
- return originalWrite(chunk, encoding, callback);
174
- }
175
- return true;
176
- };
177
- const answer = await rl.question(question);
178
- process.stdout.write = originalWrite;
179
- process.stdout.write('\n');
180
- rl.close();
181
- return answer;
182
- }
183
- const answer = await rl.question(question);
2351
+ const rl = readline.createInterface({
2352
+ input: process.stdin,
2353
+ output: process.stdout
2354
+ });
2355
+ if (hidden) {
2356
+ const originalWrite = process.stdout.write.bind(process.stdout);
2357
+ process.stdout.write = (chunk, encoding, callback) => {
2358
+ if (chunk.toString().includes(question)) {
2359
+ return originalWrite(chunk, encoding, callback);
2360
+ }
2361
+ return true;
2362
+ };
2363
+ const answer2 = await rl.question(question);
2364
+ process.stdout.write = originalWrite;
2365
+ process.stdout.write(`
2366
+ `);
184
2367
  rl.close();
185
- return answer;
2368
+ return answer2;
2369
+ }
2370
+ const answer = await rl.question(question);
2371
+ rl.close();
2372
+ return answer;
186
2373
  }
187
2374
  async function loginToApi(username, password, apiUrl) {
188
- const response = await fetch(`${apiUrl}/api/login`, {
189
- method: 'POST',
190
- headers: {
191
- 'Content-Type': 'application/json',
192
- },
193
- body: JSON.stringify({ username, password }),
194
- });
195
- if (!response.ok) {
196
- throw new Error(`HTTP error! status: ${response.status}`);
197
- }
198
- const data = (await response.json());
199
- if (!data.success) {
200
- throw new Error(data.message || 'Login failed');
201
- }
202
- return data;
2375
+ const response = await fetch(`${apiUrl}/api/login`, {
2376
+ method: "POST",
2377
+ headers: {
2378
+ "Content-Type": "application/json"
2379
+ },
2380
+ body: JSON.stringify({ username, password })
2381
+ });
2382
+ if (!response.ok) {
2383
+ throw new Error(`HTTP error! status: ${response.status}`);
2384
+ }
2385
+ const data = await response.json();
2386
+ if (!data.success) {
2387
+ throw new Error(data.message || "Login failed");
2388
+ }
2389
+ return data;
203
2390
  }
204
2391
  async function getProxy(token, apiUrl) {
205
- const response = await fetch(`${apiUrl}/proxy`, {
206
- method: 'POST',
207
- headers: {
208
- Authorization: `Bearer ${token}`,
209
- },
210
- });
211
- if (!response.ok) {
212
- throw new Error(`HTTP error! status: ${response.status}`);
213
- }
214
- const data = (await response.json());
215
- if (!data.success) {
216
- throw new Error(data.message || 'Failed to get proxy');
2392
+ const response = await fetch(`${apiUrl}/proxy`, {
2393
+ method: "POST",
2394
+ headers: {
2395
+ Authorization: `Bearer ${token}`
217
2396
  }
218
- return data;
2397
+ });
2398
+ if (!response.ok) {
2399
+ throw new Error(`HTTP error! status: ${response.status}`);
2400
+ }
2401
+ const data = await response.json();
2402
+ if (!data.success) {
2403
+ throw new Error(data.message || "Failed to get proxy");
2404
+ }
2405
+ return data;
219
2406
  }
220
2407
  async function authProxy(proxyId, proxyPassword, apiUrl) {
221
- const requestBody = {
222
- proxyId,
223
- proxyPassword,
224
- ipv4: '',
225
- };
226
- const response = await fetch(`${apiUrl}/api/proxy-auth`, {
227
- method: 'POST',
228
- headers: {
229
- 'Content-Type': 'application/json',
230
- },
231
- body: JSON.stringify(requestBody),
232
- });
233
- if (!response.ok) {
234
- throw new Error(`HTTP error! status: ${response.status}`);
235
- }
236
- const data = (await response.json());
237
- return data;
2408
+ const requestBody = {
2409
+ proxyId,
2410
+ proxyPassword,
2411
+ ipv4: ""
2412
+ };
2413
+ const response = await fetch(`${apiUrl}/api/proxy-auth`, {
2414
+ method: "POST",
2415
+ headers: {
2416
+ "Content-Type": "application/json"
2417
+ },
2418
+ body: JSON.stringify(requestBody)
2419
+ });
2420
+ if (!response.ok) {
2421
+ throw new Error(`HTTP error! status: ${response.status}`);
2422
+ }
2423
+ const data = await response.json();
2424
+ return data;
238
2425
  }
239
2426
  async function getPurchasedAccounts(token, apiUrl) {
240
- const response = await fetch(`${apiUrl}/augment-accounts/user/purchased?limit=0&sort=purchased_at&order=desc`, {
241
- method: 'GET',
242
- headers: {
243
- Authorization: `Bearer ${token}`,
244
- },
245
- });
246
- if (!response.ok) {
247
- throw new Error(`HTTP error! status: ${response.status}`);
248
- }
249
- const data = (await response.json());
250
- if (!data.success) {
251
- throw new Error(data.message || 'Failed to get purchased accounts');
2427
+ const response = await fetch(`${apiUrl}/augment-accounts/user/purchased?limit=0&sort=purchased_at&order=desc`, {
2428
+ method: "GET",
2429
+ headers: {
2430
+ Authorization: `Bearer ${token}`
252
2431
  }
253
- return data;
2432
+ });
2433
+ if (!response.ok) {
2434
+ throw new Error(`HTTP error! status: ${response.status}`);
2435
+ }
2436
+ const data = await response.json();
2437
+ if (!data.success) {
2438
+ throw new Error(data.message || "Failed to get purchased accounts");
2439
+ }
2440
+ return data;
254
2441
  }
255
2442
  async function activateAccount(accountId, token, apiUrl) {
256
- const response = await fetch(`${apiUrl}/augment-accounts/${accountId}/activate`, {
257
- method: 'PUT',
258
- headers: {
259
- Authorization: `Bearer ${token}`,
260
- },
261
- });
262
- if (!response.ok) {
263
- throw new Error(`HTTP error! status: ${response.status}`);
2443
+ const response = await fetch(`${apiUrl}/augment-accounts/${accountId}/activate`, {
2444
+ method: "PUT",
2445
+ headers: {
2446
+ Authorization: `Bearer ${token}`
264
2447
  }
265
- const data = (await response.json());
266
- if (!data.success) {
267
- throw new Error(data.message || 'Failed to activate account');
268
- }
269
- return data;
2448
+ });
2449
+ if (!response.ok) {
2450
+ throw new Error(`HTTP error! status: ${response.status}`);
2451
+ }
2452
+ const data = await response.json();
2453
+ if (!data.success) {
2454
+ throw new Error(data.message || "Failed to activate account");
2455
+ }
2456
+ return data;
270
2457
  }
271
2458
  async function handleLogin(usernameArg, passwordArg) {
272
- try {
273
- const config = loadConfig();
274
- let username;
275
- let password;
276
- if (usernameArg && passwordArg) {
277
- username = usernameArg;
278
- password = passwordArg;
279
- }
280
- else {
281
- username = await promptInput('Username: ');
282
- password = await promptInput('Password: ', true);
283
- }
284
- if (!username || !password) {
285
- console.error('Error: Username and password are required');
286
- process.exit(1);
287
- }
288
- console.log('Authenticating...');
289
- const loginResponse = await loginToApi(username, password, config.apiUrl);
290
- const authData = {
291
- username,
292
- token: loginResponse.data.token,
293
- };
294
- await saveAuthData(authData);
295
- console.log('Login successful! Token saved.');
2459
+ try {
2460
+ const config = loadConfig();
2461
+ let username;
2462
+ let password;
2463
+ if (usernameArg && passwordArg) {
2464
+ username = usernameArg;
2465
+ password = passwordArg;
2466
+ } else {
2467
+ username = await promptInput("Username: ");
2468
+ password = await promptInput("Password: ", true);
296
2469
  }
297
- catch (error) {
298
- console.error(`Login failed: ${error}`);
299
- process.exit(1);
2470
+ if (!username || !password) {
2471
+ console.error("Error: Username and password are required");
2472
+ process.exit(1);
300
2473
  }
2474
+ console.log("Authenticating...");
2475
+ const loginResponse = await loginToApi(username, password, config.apiUrl);
2476
+ const authData = {
2477
+ username,
2478
+ token: loginResponse.data.token
2479
+ };
2480
+ await saveAuthData(authData);
2481
+ console.log("Login successful! Token saved.");
2482
+ } catch (error) {
2483
+ console.error(`Login failed: ${error}`);
2484
+ process.exit(1);
2485
+ }
301
2486
  }
302
2487
  async function handleLogout() {
303
- try {
304
- await deleteAuthData();
305
- console.log('Logout successful! Credentials removed.');
306
- }
307
- catch (error) {
308
- console.error(`Logout failed: ${error}`);
309
- process.exit(1);
310
- }
2488
+ try {
2489
+ await deleteAuthData();
2490
+ console.log("Logout successful! Credentials removed.");
2491
+ } catch (error) {
2492
+ console.error(`Logout failed: ${error}`);
2493
+ process.exit(1);
2494
+ }
311
2495
  }
312
2496
  async function handleFetch(options) {
313
- const spinner = ora('Initializing...').start();
314
- try {
315
- const config = loadConfig();
316
- const token = await getAuthToken();
317
- spinner.text = 'Fetching proxy configuration...';
318
- const proxyResponse = await getProxy(token, config.apiUrl);
319
- if (!proxyResponse.data || proxyResponse.data.length === 0) {
320
- spinner.fail('No proxy data available');
321
- process.exit(1);
322
- }
323
- const firstProxy = proxyResponse.data[0];
324
- if (!firstProxy) {
325
- spinner.fail('No proxy data available');
326
- process.exit(1);
327
- }
328
- const proxyId = firstProxy.http_user;
329
- const rawPassword = firstProxy.http_password;
330
- const atIndex = rawPassword.indexOf('@');
331
- if (atIndex === -1) {
332
- spinner.fail('Invalid proxy password format');
333
- process.exit(1);
334
- }
335
- const proxyPassword = rawPassword.substring(0, atIndex);
336
- spinner.text = 'Authenticating proxy...';
337
- const authResponse = await authProxy(proxyId, proxyPassword, config.apiUrl);
338
- if (authResponse.success && authResponse.data) {
339
- const augmentSession = {
340
- accessToken: authResponse.data.token,
341
- tenantURL: authResponse.data.tenantUrl,
342
- scopes: ['read', 'write'],
343
- };
344
- await saveAugmentSession(augmentSession);
345
- // Check if session deletion is enabled - delete old sessions and reset the most recent one
346
- if (shouldDeleteSession(options)) {
347
- try {
348
- const sessionsDir = path.join(os.homedir(), '.augment', 'sessions');
349
- // Check if directory exists
350
- try {
351
- await fs.access(sessionsDir);
352
- }
353
- catch {
354
- // Directory doesn't exist, nothing to do
355
- throw new Error('Sessions directory does not exist');
356
- }
357
- // Read all JSON files from the sessions directory
358
- const files = await fs.readdir(sessionsDir);
359
- const jsonFiles = files.filter((file) => file.endsWith('.json'));
360
- if (jsonFiles.length === 0) {
361
- // No files to process
362
- throw new Error('No session files found');
363
- }
364
- // Get file stats and sort by mtime (most recent first)
365
- const fileStats = await Promise.all(jsonFiles.map(async (file) => {
366
- const filePath = path.join(sessionsDir, file);
367
- const stats = await fs.stat(filePath);
368
- return { file, filePath, mtime: stats.mtime };
369
- }));
370
- fileStats.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
371
- // Delete all files except the most recently modified one
372
- for (let i = 1; i < fileStats.length; i++) {
373
- const fileStat = fileStats[i];
374
- if (fileStat) {
375
- await fs.unlink(fileStat.filePath);
376
- }
377
- }
378
- // Process the most recently modified file
379
- const mostRecent = fileStats[0];
380
- if (!mostRecent) {
381
- throw new Error('No most recent file found');
382
- }
383
- // Read the file content
384
- const content = await fs.readFile(mostRecent.filePath, 'utf-8');
385
- // Generate a new UUID
386
- const newUuid = uuidv4();
387
- // Parse JSON, update sessionId, replace request_id keys, and save
388
- const jsonData = JSON.parse(content);
389
- jsonData.sessionId = newUuid;
390
- // Convert to string and replace all "request_id" keys with "request_id_temp"
391
- let jsonString = JSON.stringify(jsonData, null, 2);
392
- jsonString = jsonString.replace(/"request_id"/g, '"request_id_temp"');
393
- // Write the modified content
394
- const newFilePath = path.join(sessionsDir, `${newUuid}.json`);
395
- await fs.writeFile(newFilePath, jsonString, 'utf-8');
396
- // Delete the old file if it has a different name
397
- if (mostRecent.filePath !== newFilePath) {
398
- await fs.unlink(mostRecent.filePath);
399
- }
400
- }
401
- catch {
402
- // Fallback to old logic if new session management fails
403
- try {
404
- await execAsync('auggie session delete');
405
- }
406
- catch {
407
- // Silently ignore fallback errors
408
- }
409
- }
410
- }
411
- // Skip prompt fetching if authOnly flag is set
412
- if (options?.authOnly) {
413
- spinner.succeed('Authentication successful (prompts skipped)');
414
- }
415
- else {
416
- spinner.text = 'Fetching prompts...';
417
- const allPrompts = await getAllPrompts(token, config.apiUrl, spinner);
418
- if (allPrompts.length > 0) {
419
- spinner.text = `Saving ${allPrompts.length} prompts...`;
420
- for (const prompt of allPrompts) {
421
- await savePromptToFile(prompt);
422
- }
423
- spinner.succeed(`Successfully saved ${allPrompts.length} prompts`);
424
- }
425
- else {
426
- spinner.warn('No prompts found');
427
- }
2497
+ const spinner = ora("Initializing...").start();
2498
+ try {
2499
+ const config = loadConfig();
2500
+ const token = await getAuthToken();
2501
+ spinner.text = "Fetching proxy configuration...";
2502
+ const proxyResponse = await getProxy(token, config.apiUrl);
2503
+ if (!proxyResponse.data || proxyResponse.data.length === 0) {
2504
+ spinner.fail("No proxy data available");
2505
+ process.exit(1);
2506
+ }
2507
+ const firstProxy = proxyResponse.data[0];
2508
+ if (!firstProxy) {
2509
+ spinner.fail("No proxy data available");
2510
+ process.exit(1);
2511
+ }
2512
+ const proxyId = firstProxy.http_user;
2513
+ const rawPassword = firstProxy.http_password;
2514
+ const atIndex = rawPassword.indexOf("@");
2515
+ if (atIndex === -1) {
2516
+ spinner.fail("Invalid proxy password format");
2517
+ process.exit(1);
2518
+ }
2519
+ const proxyPassword = rawPassword.substring(0, atIndex);
2520
+ spinner.text = "Authenticating proxy...";
2521
+ const authResponse = await authProxy(proxyId, proxyPassword, config.apiUrl);
2522
+ if (authResponse.success && authResponse.data) {
2523
+ const augmentSession = {
2524
+ accessToken: authResponse.data.token,
2525
+ tenantURL: authResponse.data.tenantUrl,
2526
+ scopes: ["read", "write"]
2527
+ };
2528
+ await saveAugmentSession(augmentSession);
2529
+ if (shouldDeleteSession(options)) {
2530
+ try {
2531
+ const sessionsDir = path.join(os.homedir(), ".augment", "sessions");
2532
+ try {
2533
+ await fs.access(sessionsDir);
2534
+ } catch {
2535
+ throw new Error("Sessions directory does not exist");
2536
+ }
2537
+ const files = await fs.readdir(sessionsDir);
2538
+ const jsonFiles = files.filter((file) => file.endsWith(".json"));
2539
+ if (jsonFiles.length === 0) {
2540
+ throw new Error("No session files found");
2541
+ }
2542
+ const fileStats = await Promise.all(jsonFiles.map(async (file) => {
2543
+ const filePath = path.join(sessionsDir, file);
2544
+ const stats = await fs.stat(filePath);
2545
+ return { file, filePath, mtime: stats.mtime };
2546
+ }));
2547
+ fileStats.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
2548
+ for (let i = 1;i < fileStats.length; i++) {
2549
+ const fileStat = fileStats[i];
2550
+ if (fileStat) {
2551
+ await fs.unlink(fileStat.filePath);
428
2552
  }
2553
+ }
2554
+ const mostRecent = fileStats[0];
2555
+ if (!mostRecent) {
2556
+ throw new Error("No most recent file found");
2557
+ }
2558
+ const content = await fs.readFile(mostRecent.filePath, "utf-8");
2559
+ const newUuid = v4_default();
2560
+ const jsonData = JSON.parse(content);
2561
+ jsonData.sessionId = newUuid;
2562
+ let jsonString = JSON.stringify(jsonData, null, 2);
2563
+ jsonString = jsonString.replace(/"request_id"/g, '"request_id_temp"');
2564
+ const newFilePath = path.join(sessionsDir, `${newUuid}.json`);
2565
+ await fs.writeFile(newFilePath, jsonString, "utf-8");
2566
+ if (mostRecent.filePath !== newFilePath) {
2567
+ await fs.unlink(mostRecent.filePath);
2568
+ }
2569
+ } catch {
2570
+ try {
2571
+ await execAsync("auggie session delete");
2572
+ } catch {}
429
2573
  }
2574
+ }
2575
+ if (options?.authOnly) {
2576
+ spinner.succeed("Authentication successful (prompts skipped)");
2577
+ } else if (options?.refreshCommands) {
2578
+ spinner.text = "Deleting existing commands...";
2579
+ const deletedCount = await deleteAllCommandFiles();
2580
+ if (deletedCount > 0) {
2581
+ spinner.text = `Deleted ${deletedCount} existing commands. Fetching prompts...`;
2582
+ } else {
2583
+ spinner.text = "Fetching prompts...";
2584
+ }
2585
+ const allPrompts = await getAllPrompts(token, config.apiUrl, spinner);
2586
+ if (allPrompts.length > 0) {
2587
+ spinner.text = `Saving ${allPrompts.length} prompts...`;
2588
+ for (const prompt of allPrompts) {
2589
+ await savePromptToFile(prompt);
2590
+ }
2591
+ spinner.succeed(`Successfully refreshed commands: deleted ${deletedCount}, saved ${allPrompts.length} prompts`);
2592
+ } else {
2593
+ spinner.warn(`Deleted ${deletedCount} commands, no new prompts found`);
2594
+ }
2595
+ } else {
2596
+ spinner.succeed("Authentication successful (use --refresh-commands to update prompts)");
2597
+ }
430
2598
  }
431
- catch (error) {
432
- spinner.fail(`Fetch failed: ${error}`);
433
- process.exit(1);
434
- }
2599
+ } catch (error) {
2600
+ spinner.fail(`Fetch failed: ${error}`);
2601
+ process.exit(1);
2602
+ }
435
2603
  }
436
2604
  async function handleAuggie(args, options) {
437
- await handleFetch(options);
438
- const auggieProcess = spawn('auggie', args, {
439
- stdio: 'inherit',
440
- shell: true,
441
- });
442
- auggieProcess.on('error', (error) => {
443
- console.error(`Failed to execute auggie: ${error.message}`);
444
- process.exit(1);
445
- });
446
- auggieProcess.on('exit', (code) => {
447
- process.exit(code ?? 0);
448
- });
2605
+ await handleFetch(options);
2606
+ const auggieProcess = spawn("auggie", args, {
2607
+ stdio: "inherit",
2608
+ shell: true
2609
+ });
2610
+ auggieProcess.on("error", (error) => {
2611
+ console.error(`Failed to execute auggie: ${error.message}`);
2612
+ process.exit(1);
2613
+ });
2614
+ auggieProcess.on("exit", (code) => {
2615
+ process.exit(code ?? 0);
2616
+ });
449
2617
  }
450
2618
  async function handleExec(command, args, options) {
451
- if (!command) {
452
- console.error('Error: Command is required');
453
- console.error('Usage: auggiegw exec <command> [args...]');
454
- process.exit(1);
455
- }
456
- await handleFetch(options);
457
- const childProcess = spawn(command, args, {
458
- stdio: 'inherit',
459
- shell: true,
460
- });
461
- childProcess.on('error', (error) => {
462
- console.error(`Failed to execute ${command}: ${error.message}`);
463
- process.exit(1);
464
- });
465
- childProcess.on('exit', (code) => {
466
- process.exit(code ?? 0);
467
- });
2619
+ if (!command) {
2620
+ console.error("Error: Command is required");
2621
+ console.error("Usage: auggiegw exec <command> [args...]");
2622
+ process.exit(1);
2623
+ }
2624
+ await handleFetch(options);
2625
+ const childProcess = spawn(command, args, {
2626
+ stdio: "inherit",
2627
+ shell: true
2628
+ });
2629
+ childProcess.on("error", (error) => {
2630
+ console.error(`Failed to execute ${command}: ${error.message}`);
2631
+ process.exit(1);
2632
+ });
2633
+ childProcess.on("exit", (code) => {
2634
+ process.exit(code ?? 0);
2635
+ });
468
2636
  }
469
2637
  async function handleSwitchAccount() {
470
- const spinner = ora('Fetching account list...').start();
471
- try {
472
- const config = loadConfig();
473
- const token = await getAuthToken();
474
- const accountsResponse = await getPurchasedAccounts(token, config.apiUrl);
475
- if (!accountsResponse.data.accounts || accountsResponse.data.accounts.length === 0) {
476
- spinner.fail('No accounts available');
477
- process.exit(1);
478
- }
479
- const accounts = accountsResponse.data.accounts;
480
- // Find the current account (status "in-use")
481
- const currentAccountIndex = accounts.findIndex((account) => account.status === 'in-use');
482
- if (currentAccountIndex === -1) {
483
- spinner.fail('No account is currently in use');
484
- process.exit(1);
485
- }
486
- // Get the account before the current one (since list is sorted in descending order)
487
- const nextAccountIndex = currentAccountIndex - 1;
488
- if (nextAccountIndex < 0) {
489
- spinner.fail('No newer account available to switch to');
490
- process.exit(1);
491
- }
492
- const nextAccount = accounts[nextAccountIndex];
493
- const currentAccount = accounts[currentAccountIndex];
494
- if (!nextAccount || !currentAccount) {
495
- spinner.fail('Failed to retrieve account information');
496
- process.exit(1);
497
- }
498
- spinner.text = `Switching from ${currentAccount.email} to ${nextAccount.email}...`;
499
- // Activate the next account
500
- const activateResponse = await activateAccount(nextAccount.id, token, config.apiUrl);
501
- spinner.succeed(`Successfully switched to account: ${activateResponse.data.activatedAccount.email}`);
502
- // Execute account fetch logic again (auth only, preserve session)
503
- console.log('Refreshing authentication...');
504
- await handleFetch({ authOnly: true, deleteSession: true });
505
- }
506
- catch (error) {
507
- spinner.fail(`Account switch failed: ${error}`);
508
- process.exit(1);
2638
+ const spinner = ora("Fetching account list...").start();
2639
+ try {
2640
+ const config = loadConfig();
2641
+ const token = await getAuthToken();
2642
+ const accountsResponse = await getPurchasedAccounts(token, config.apiUrl);
2643
+ if (!accountsResponse.data.accounts || accountsResponse.data.accounts.length === 0) {
2644
+ spinner.fail("No accounts available");
2645
+ process.exit(1);
2646
+ }
2647
+ const accounts = accountsResponse.data.accounts;
2648
+ const currentAccountIndex = accounts.findIndex((account) => account.status === "in-use");
2649
+ if (currentAccountIndex === -1) {
2650
+ spinner.fail("No account is currently in use");
2651
+ process.exit(1);
2652
+ }
2653
+ const nextAccountIndex = currentAccountIndex - 1;
2654
+ if (nextAccountIndex < 0) {
2655
+ spinner.fail("No newer account available to switch to");
2656
+ process.exit(1);
509
2657
  }
2658
+ const nextAccount = accounts[nextAccountIndex];
2659
+ const currentAccount = accounts[currentAccountIndex];
2660
+ if (!nextAccount || !currentAccount) {
2661
+ spinner.fail("Failed to retrieve account information");
2662
+ process.exit(1);
2663
+ }
2664
+ spinner.text = `Switching from ${currentAccount.email} to ${nextAccount.email}...`;
2665
+ const activateResponse = await activateAccount(nextAccount.id, token, config.apiUrl);
2666
+ spinner.succeed(`Successfully switched to account: ${activateResponse.data.activatedAccount.email}`);
2667
+ console.log("Refreshing authentication...");
2668
+ await handleFetch({ authOnly: true, deleteSession: true });
2669
+ } catch (error) {
2670
+ spinner.fail(`Account switch failed: ${error}`);
2671
+ process.exit(1);
2672
+ }
510
2673
  }
511
- const program = new Command();
512
- program
513
- .name('auggiegw')
514
- .description('CLI tool for auggiegw authentication')
515
- .version('1.0.0')
516
- .option('--preserve-session', 'Preserve Auggie session (do not delete chat history)')
517
- .option('--delete-session', 'Delete Auggie session (clear chat history)')
518
- .option('--auth-only', 'Fetch authentication session only without fetching prompts');
519
- program
520
- .command('login [username] [password]')
521
- .description('Login and store credentials')
522
- .action(handleLogin);
523
- program.command('logout').description('Logout and remove stored credentials').action(handleLogout);
524
- program
525
- .command('fetch')
526
- .description('Fetch proxy configuration and authenticate')
527
- .action(() => {
528
- const opts = program.opts();
529
- const sessionOptions = getSessionOptions(opts);
530
- handleFetch(sessionOptions);
2674
+ var program2 = new Command;
2675
+ program2.name("auggiegw").description("CLI tool for auggiegw authentication").version("1.0.0").option("--preserve-session", "Preserve Auggie session (do not delete chat history)").option("--delete-session", "Delete Auggie session (clear chat history)").option("--auth-only", "Fetch authentication session only without fetching prompts").option("--refresh-commands", "Delete all existing commands and fetch fresh ones from API");
2676
+ program2.command("login [username] [password]").description("Login and store credentials").action(handleLogin);
2677
+ program2.command("logout").description("Logout and remove stored credentials").action(handleLogout);
2678
+ program2.command("fetch").description("Fetch proxy configuration and authenticate").action(() => {
2679
+ const opts = program2.opts();
2680
+ const sessionOptions = getSessionOptions(opts);
2681
+ handleFetch(sessionOptions);
531
2682
  });
532
- program
533
- .command('auggie [args...]')
534
- .description('Forward command to auggie CLI')
535
- .allowUnknownOption()
536
- .action((args) => {
537
- const opts = program.opts();
538
- const sessionOptions = getSessionOptions(opts);
539
- handleAuggie(args || [], sessionOptions);
2683
+ program2.command("auggie [args...]").description("Forward command to auggie CLI").allowUnknownOption().action((args) => {
2684
+ const opts = program2.opts();
2685
+ const sessionOptions = getSessionOptions(opts);
2686
+ handleAuggie(args || [], sessionOptions);
540
2687
  });
541
- program
542
- .command('exec <command> [args...]')
543
- .description('Execute any custom command')
544
- .allowUnknownOption()
545
- .action((command, args) => {
546
- const opts = program.opts();
547
- const sessionOptions = getSessionOptions(opts);
548
- handleExec(command, args, sessionOptions);
2688
+ program2.command("exec <command> [args...]").description("Execute any custom command").allowUnknownOption().action((command, args) => {
2689
+ const opts = program2.opts();
2690
+ const sessionOptions = getSessionOptions(opts);
2691
+ handleExec(command, args, sessionOptions);
549
2692
  });
550
- program
551
- .command('switch-account')
552
- .description('Switch to a newer account from the purchased account list')
553
- .action(handleSwitchAccount);
554
- program.parse();
555
- //# sourceMappingURL=cli.js.map
2693
+ program2.command("switch-account").description("Switch to a newer account from the purchased account list").action(handleSwitchAccount);
2694
+ program2.parse();
2695
+
2696
+ //# debugId=B34B485639FF8F0864756E2164756E21