api2cli 0.1.0

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