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