@mantou/gem-port 1.0.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/index.js +2437 -0
- package/package.json +39 -0
package/bin/index.js
ADDED
|
@@ -0,0 +1,2437 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
var __create = Object.create;
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
8
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
9
|
+
var __commonJS = (cb, mod) => function __require() {
|
|
10
|
+
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
|
|
29
|
+
// ../../node_modules/.pnpm/commander@7.2.0/node_modules/commander/index.js
|
|
30
|
+
var require_commander = __commonJS({
|
|
31
|
+
"../../node_modules/.pnpm/commander@7.2.0/node_modules/commander/index.js"(exports2, module2) {
|
|
32
|
+
var EventEmitter = require("events").EventEmitter;
|
|
33
|
+
var childProcess = require("child_process");
|
|
34
|
+
var path4 = require("path");
|
|
35
|
+
var fs = require("fs");
|
|
36
|
+
var Help = class {
|
|
37
|
+
constructor() {
|
|
38
|
+
this.helpWidth = void 0;
|
|
39
|
+
this.sortSubcommands = false;
|
|
40
|
+
this.sortOptions = false;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
|
|
44
|
+
*
|
|
45
|
+
* @param {Command} cmd
|
|
46
|
+
* @returns {Command[]}
|
|
47
|
+
*/
|
|
48
|
+
visibleCommands(cmd) {
|
|
49
|
+
const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
|
|
50
|
+
if (cmd._hasImplicitHelpCommand()) {
|
|
51
|
+
const args = cmd._helpCommandnameAndArgs.split(/ +/);
|
|
52
|
+
const helpCommand = cmd.createCommand(args.shift()).helpOption(false);
|
|
53
|
+
helpCommand.description(cmd._helpCommandDescription);
|
|
54
|
+
helpCommand._parseExpectedArgs(args);
|
|
55
|
+
visibleCommands.push(helpCommand);
|
|
56
|
+
}
|
|
57
|
+
if (this.sortSubcommands) {
|
|
58
|
+
visibleCommands.sort((a, b) => {
|
|
59
|
+
return a.name().localeCompare(b.name());
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
return visibleCommands;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
|
|
66
|
+
*
|
|
67
|
+
* @param {Command} cmd
|
|
68
|
+
* @returns {Option[]}
|
|
69
|
+
*/
|
|
70
|
+
visibleOptions(cmd) {
|
|
71
|
+
const visibleOptions = cmd.options.filter((option) => !option.hidden);
|
|
72
|
+
const showShortHelpFlag = cmd._hasHelpOption && cmd._helpShortFlag && !cmd._findOption(cmd._helpShortFlag);
|
|
73
|
+
const showLongHelpFlag = cmd._hasHelpOption && !cmd._findOption(cmd._helpLongFlag);
|
|
74
|
+
if (showShortHelpFlag || showLongHelpFlag) {
|
|
75
|
+
let helpOption;
|
|
76
|
+
if (!showShortHelpFlag) {
|
|
77
|
+
helpOption = cmd.createOption(cmd._helpLongFlag, cmd._helpDescription);
|
|
78
|
+
} else if (!showLongHelpFlag) {
|
|
79
|
+
helpOption = cmd.createOption(cmd._helpShortFlag, cmd._helpDescription);
|
|
80
|
+
} else {
|
|
81
|
+
helpOption = cmd.createOption(cmd._helpFlags, cmd._helpDescription);
|
|
82
|
+
}
|
|
83
|
+
visibleOptions.push(helpOption);
|
|
84
|
+
}
|
|
85
|
+
if (this.sortOptions) {
|
|
86
|
+
const getSortKey = (option) => {
|
|
87
|
+
return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
|
|
88
|
+
};
|
|
89
|
+
visibleOptions.sort((a, b) => {
|
|
90
|
+
return getSortKey(a).localeCompare(getSortKey(b));
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
return visibleOptions;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Get an array of the arguments which have descriptions.
|
|
97
|
+
*
|
|
98
|
+
* @param {Command} cmd
|
|
99
|
+
* @returns {{ term: string, description:string }[]}
|
|
100
|
+
*/
|
|
101
|
+
visibleArguments(cmd) {
|
|
102
|
+
if (cmd._argsDescription && cmd._args.length) {
|
|
103
|
+
return cmd._args.map((argument) => {
|
|
104
|
+
return { term: argument.name, description: cmd._argsDescription[argument.name] || "" };
|
|
105
|
+
}, 0);
|
|
106
|
+
}
|
|
107
|
+
return [];
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Get the command term to show in the list of subcommands.
|
|
111
|
+
*
|
|
112
|
+
* @param {Command} cmd
|
|
113
|
+
* @returns {string}
|
|
114
|
+
*/
|
|
115
|
+
subcommandTerm(cmd) {
|
|
116
|
+
const args = cmd._args.map((arg) => humanReadableArgName(arg)).join(" ");
|
|
117
|
+
return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
|
|
118
|
+
(args ? " " + args : "");
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Get the option term to show in the list of options.
|
|
122
|
+
*
|
|
123
|
+
* @param {Option} option
|
|
124
|
+
* @returns {string}
|
|
125
|
+
*/
|
|
126
|
+
optionTerm(option) {
|
|
127
|
+
return option.flags;
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Get the longest command term length.
|
|
131
|
+
*
|
|
132
|
+
* @param {Command} cmd
|
|
133
|
+
* @param {Help} helper
|
|
134
|
+
* @returns {number}
|
|
135
|
+
*/
|
|
136
|
+
longestSubcommandTermLength(cmd, helper) {
|
|
137
|
+
return helper.visibleCommands(cmd).reduce((max, command) => {
|
|
138
|
+
return Math.max(max, helper.subcommandTerm(command).length);
|
|
139
|
+
}, 0);
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Get the longest option term length.
|
|
143
|
+
*
|
|
144
|
+
* @param {Command} cmd
|
|
145
|
+
* @param {Help} helper
|
|
146
|
+
* @returns {number}
|
|
147
|
+
*/
|
|
148
|
+
longestOptionTermLength(cmd, helper) {
|
|
149
|
+
return helper.visibleOptions(cmd).reduce((max, option) => {
|
|
150
|
+
return Math.max(max, helper.optionTerm(option).length);
|
|
151
|
+
}, 0);
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Get the longest argument term length.
|
|
155
|
+
*
|
|
156
|
+
* @param {Command} cmd
|
|
157
|
+
* @param {Help} helper
|
|
158
|
+
* @returns {number}
|
|
159
|
+
*/
|
|
160
|
+
longestArgumentTermLength(cmd, helper) {
|
|
161
|
+
return helper.visibleArguments(cmd).reduce((max, argument) => {
|
|
162
|
+
return Math.max(max, argument.term.length);
|
|
163
|
+
}, 0);
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Get the command usage to be displayed at the top of the built-in help.
|
|
167
|
+
*
|
|
168
|
+
* @param {Command} cmd
|
|
169
|
+
* @returns {string}
|
|
170
|
+
*/
|
|
171
|
+
commandUsage(cmd) {
|
|
172
|
+
let cmdName = cmd._name;
|
|
173
|
+
if (cmd._aliases[0]) {
|
|
174
|
+
cmdName = cmdName + "|" + cmd._aliases[0];
|
|
175
|
+
}
|
|
176
|
+
let parentCmdNames = "";
|
|
177
|
+
for (let parentCmd = cmd.parent; parentCmd; parentCmd = parentCmd.parent) {
|
|
178
|
+
parentCmdNames = parentCmd.name() + " " + parentCmdNames;
|
|
179
|
+
}
|
|
180
|
+
return parentCmdNames + cmdName + " " + cmd.usage();
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Get the description for the command.
|
|
184
|
+
*
|
|
185
|
+
* @param {Command} cmd
|
|
186
|
+
* @returns {string}
|
|
187
|
+
*/
|
|
188
|
+
commandDescription(cmd) {
|
|
189
|
+
return cmd.description();
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Get the command description to show in the list of subcommands.
|
|
193
|
+
*
|
|
194
|
+
* @param {Command} cmd
|
|
195
|
+
* @returns {string}
|
|
196
|
+
*/
|
|
197
|
+
subcommandDescription(cmd) {
|
|
198
|
+
return cmd.description();
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Get the option description to show in the list of options.
|
|
202
|
+
*
|
|
203
|
+
* @param {Option} option
|
|
204
|
+
* @return {string}
|
|
205
|
+
*/
|
|
206
|
+
optionDescription(option) {
|
|
207
|
+
if (option.negate) {
|
|
208
|
+
return option.description;
|
|
209
|
+
}
|
|
210
|
+
const extraInfo = [];
|
|
211
|
+
if (option.argChoices) {
|
|
212
|
+
extraInfo.push(
|
|
213
|
+
// use stringify to match the display of the default value
|
|
214
|
+
`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
if (option.defaultValue !== void 0) {
|
|
218
|
+
extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
|
|
219
|
+
}
|
|
220
|
+
if (extraInfo.length > 0) {
|
|
221
|
+
return `${option.description} (${extraInfo.join(", ")})`;
|
|
222
|
+
}
|
|
223
|
+
return option.description;
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Generate the built-in help text.
|
|
227
|
+
*
|
|
228
|
+
* @param {Command} cmd
|
|
229
|
+
* @param {Help} helper
|
|
230
|
+
* @returns {string}
|
|
231
|
+
*/
|
|
232
|
+
formatHelp(cmd, helper) {
|
|
233
|
+
const termWidth = helper.padWidth(cmd, helper);
|
|
234
|
+
const helpWidth = helper.helpWidth || 80;
|
|
235
|
+
const itemIndentWidth = 2;
|
|
236
|
+
const itemSeparatorWidth = 2;
|
|
237
|
+
function formatItem(term, description2) {
|
|
238
|
+
if (description2) {
|
|
239
|
+
const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description2}`;
|
|
240
|
+
return helper.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth);
|
|
241
|
+
}
|
|
242
|
+
return term;
|
|
243
|
+
}
|
|
244
|
+
;
|
|
245
|
+
function formatList(textArray) {
|
|
246
|
+
return textArray.join("\n").replace(/^/gm, " ".repeat(itemIndentWidth));
|
|
247
|
+
}
|
|
248
|
+
let output = [`Usage: ${helper.commandUsage(cmd)}`, ""];
|
|
249
|
+
const commandDescription = helper.commandDescription(cmd);
|
|
250
|
+
if (commandDescription.length > 0) {
|
|
251
|
+
output = output.concat([commandDescription, ""]);
|
|
252
|
+
}
|
|
253
|
+
const argumentList = helper.visibleArguments(cmd).map((argument) => {
|
|
254
|
+
return formatItem(argument.term, argument.description);
|
|
255
|
+
});
|
|
256
|
+
if (argumentList.length > 0) {
|
|
257
|
+
output = output.concat(["Arguments:", formatList(argumentList), ""]);
|
|
258
|
+
}
|
|
259
|
+
const optionList = helper.visibleOptions(cmd).map((option) => {
|
|
260
|
+
return formatItem(helper.optionTerm(option), helper.optionDescription(option));
|
|
261
|
+
});
|
|
262
|
+
if (optionList.length > 0) {
|
|
263
|
+
output = output.concat(["Options:", formatList(optionList), ""]);
|
|
264
|
+
}
|
|
265
|
+
const commandList = helper.visibleCommands(cmd).map((cmd2) => {
|
|
266
|
+
return formatItem(helper.subcommandTerm(cmd2), helper.subcommandDescription(cmd2));
|
|
267
|
+
});
|
|
268
|
+
if (commandList.length > 0) {
|
|
269
|
+
output = output.concat(["Commands:", formatList(commandList), ""]);
|
|
270
|
+
}
|
|
271
|
+
return output.join("\n");
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Calculate the pad width from the maximum term length.
|
|
275
|
+
*
|
|
276
|
+
* @param {Command} cmd
|
|
277
|
+
* @param {Help} helper
|
|
278
|
+
* @returns {number}
|
|
279
|
+
*/
|
|
280
|
+
padWidth(cmd, helper) {
|
|
281
|
+
return Math.max(
|
|
282
|
+
helper.longestOptionTermLength(cmd, helper),
|
|
283
|
+
helper.longestSubcommandTermLength(cmd, helper),
|
|
284
|
+
helper.longestArgumentTermLength(cmd, helper)
|
|
285
|
+
);
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Wrap the given string to width characters per line, with lines after the first indented.
|
|
289
|
+
* Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
|
|
290
|
+
*
|
|
291
|
+
* @param {string} str
|
|
292
|
+
* @param {number} width
|
|
293
|
+
* @param {number} indent
|
|
294
|
+
* @param {number} [minColumnWidth=40]
|
|
295
|
+
* @return {string}
|
|
296
|
+
*
|
|
297
|
+
*/
|
|
298
|
+
wrap(str, width, indent, minColumnWidth = 40) {
|
|
299
|
+
if (str.match(/[\n]\s+/)) return str;
|
|
300
|
+
const columnWidth = width - indent;
|
|
301
|
+
if (columnWidth < minColumnWidth) return str;
|
|
302
|
+
const leadingStr = str.substr(0, indent);
|
|
303
|
+
const columnText = str.substr(indent);
|
|
304
|
+
const indentString = " ".repeat(indent);
|
|
305
|
+
const regex = new RegExp(".{1," + (columnWidth - 1) + "}([\\s\u200B]|$)|[^\\s\u200B]+?([\\s\u200B]|$)", "g");
|
|
306
|
+
const lines = columnText.match(regex) || [];
|
|
307
|
+
return leadingStr + lines.map((line, i) => {
|
|
308
|
+
if (line.slice(-1) === "\n") {
|
|
309
|
+
line = line.slice(0, line.length - 1);
|
|
310
|
+
}
|
|
311
|
+
return (i > 0 ? indentString : "") + line.trimRight();
|
|
312
|
+
}).join("\n");
|
|
313
|
+
}
|
|
314
|
+
};
|
|
315
|
+
var Option = class {
|
|
316
|
+
/**
|
|
317
|
+
* Initialize a new `Option` with the given `flags` and `description`.
|
|
318
|
+
*
|
|
319
|
+
* @param {string} flags
|
|
320
|
+
* @param {string} [description]
|
|
321
|
+
*/
|
|
322
|
+
constructor(flags, description2) {
|
|
323
|
+
this.flags = flags;
|
|
324
|
+
this.description = description2 || "";
|
|
325
|
+
this.required = flags.includes("<");
|
|
326
|
+
this.optional = flags.includes("[");
|
|
327
|
+
this.variadic = /\w\.\.\.[>\]]$/.test(flags);
|
|
328
|
+
this.mandatory = false;
|
|
329
|
+
const optionFlags = _parseOptionFlags(flags);
|
|
330
|
+
this.short = optionFlags.shortFlag;
|
|
331
|
+
this.long = optionFlags.longFlag;
|
|
332
|
+
this.negate = false;
|
|
333
|
+
if (this.long) {
|
|
334
|
+
this.negate = this.long.startsWith("--no-");
|
|
335
|
+
}
|
|
336
|
+
this.defaultValue = void 0;
|
|
337
|
+
this.defaultValueDescription = void 0;
|
|
338
|
+
this.parseArg = void 0;
|
|
339
|
+
this.hidden = false;
|
|
340
|
+
this.argChoices = void 0;
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* Set the default value, and optionally supply the description to be displayed in the help.
|
|
344
|
+
*
|
|
345
|
+
* @param {any} value
|
|
346
|
+
* @param {string} [description]
|
|
347
|
+
* @return {Option}
|
|
348
|
+
*/
|
|
349
|
+
default(value, description2) {
|
|
350
|
+
this.defaultValue = value;
|
|
351
|
+
this.defaultValueDescription = description2;
|
|
352
|
+
return this;
|
|
353
|
+
}
|
|
354
|
+
/**
|
|
355
|
+
* Set the custom handler for processing CLI option arguments into option values.
|
|
356
|
+
*
|
|
357
|
+
* @param {Function} [fn]
|
|
358
|
+
* @return {Option}
|
|
359
|
+
*/
|
|
360
|
+
argParser(fn) {
|
|
361
|
+
this.parseArg = fn;
|
|
362
|
+
return this;
|
|
363
|
+
}
|
|
364
|
+
/**
|
|
365
|
+
* Whether the option is mandatory and must have a value after parsing.
|
|
366
|
+
*
|
|
367
|
+
* @param {boolean} [mandatory=true]
|
|
368
|
+
* @return {Option}
|
|
369
|
+
*/
|
|
370
|
+
makeOptionMandatory(mandatory = true) {
|
|
371
|
+
this.mandatory = !!mandatory;
|
|
372
|
+
return this;
|
|
373
|
+
}
|
|
374
|
+
/**
|
|
375
|
+
* Hide option in help.
|
|
376
|
+
*
|
|
377
|
+
* @param {boolean} [hide=true]
|
|
378
|
+
* @return {Option}
|
|
379
|
+
*/
|
|
380
|
+
hideHelp(hide = true) {
|
|
381
|
+
this.hidden = !!hide;
|
|
382
|
+
return this;
|
|
383
|
+
}
|
|
384
|
+
/**
|
|
385
|
+
* @api private
|
|
386
|
+
*/
|
|
387
|
+
_concatValue(value, previous) {
|
|
388
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) {
|
|
389
|
+
return [value];
|
|
390
|
+
}
|
|
391
|
+
return previous.concat(value);
|
|
392
|
+
}
|
|
393
|
+
/**
|
|
394
|
+
* Only allow option value to be one of choices.
|
|
395
|
+
*
|
|
396
|
+
* @param {string[]} values
|
|
397
|
+
* @return {Option}
|
|
398
|
+
*/
|
|
399
|
+
choices(values) {
|
|
400
|
+
this.argChoices = values;
|
|
401
|
+
this.parseArg = (arg, previous) => {
|
|
402
|
+
if (!values.includes(arg)) {
|
|
403
|
+
throw new InvalidOptionArgumentError(`Allowed choices are ${values.join(", ")}.`);
|
|
404
|
+
}
|
|
405
|
+
if (this.variadic) {
|
|
406
|
+
return this._concatValue(arg, previous);
|
|
407
|
+
}
|
|
408
|
+
return arg;
|
|
409
|
+
};
|
|
410
|
+
return this;
|
|
411
|
+
}
|
|
412
|
+
/**
|
|
413
|
+
* Return option name.
|
|
414
|
+
*
|
|
415
|
+
* @return {string}
|
|
416
|
+
*/
|
|
417
|
+
name() {
|
|
418
|
+
if (this.long) {
|
|
419
|
+
return this.long.replace(/^--/, "");
|
|
420
|
+
}
|
|
421
|
+
return this.short.replace(/^-/, "");
|
|
422
|
+
}
|
|
423
|
+
/**
|
|
424
|
+
* Return option name, in a camelcase format that can be used
|
|
425
|
+
* as a object attribute key.
|
|
426
|
+
*
|
|
427
|
+
* @return {string}
|
|
428
|
+
* @api private
|
|
429
|
+
*/
|
|
430
|
+
attributeName() {
|
|
431
|
+
return camelcase(this.name().replace(/^no-/, ""));
|
|
432
|
+
}
|
|
433
|
+
/**
|
|
434
|
+
* Check if `arg` matches the short or long flag.
|
|
435
|
+
*
|
|
436
|
+
* @param {string} arg
|
|
437
|
+
* @return {boolean}
|
|
438
|
+
* @api private
|
|
439
|
+
*/
|
|
440
|
+
is(arg) {
|
|
441
|
+
return this.short === arg || this.long === arg;
|
|
442
|
+
}
|
|
443
|
+
};
|
|
444
|
+
var CommanderError = class extends Error {
|
|
445
|
+
/**
|
|
446
|
+
* Constructs the CommanderError class
|
|
447
|
+
* @param {number} exitCode suggested exit code which could be used with process.exit
|
|
448
|
+
* @param {string} code an id string representing the error
|
|
449
|
+
* @param {string} message human-readable description of the error
|
|
450
|
+
* @constructor
|
|
451
|
+
*/
|
|
452
|
+
constructor(exitCode, code, message) {
|
|
453
|
+
super(message);
|
|
454
|
+
Error.captureStackTrace(this, this.constructor);
|
|
455
|
+
this.name = this.constructor.name;
|
|
456
|
+
this.code = code;
|
|
457
|
+
this.exitCode = exitCode;
|
|
458
|
+
this.nestedError = void 0;
|
|
459
|
+
}
|
|
460
|
+
};
|
|
461
|
+
var InvalidOptionArgumentError = class extends CommanderError {
|
|
462
|
+
/**
|
|
463
|
+
* Constructs the InvalidOptionArgumentError class
|
|
464
|
+
* @param {string} [message] explanation of why argument is invalid
|
|
465
|
+
* @constructor
|
|
466
|
+
*/
|
|
467
|
+
constructor(message) {
|
|
468
|
+
super(1, "commander.invalidOptionArgument", message);
|
|
469
|
+
Error.captureStackTrace(this, this.constructor);
|
|
470
|
+
this.name = this.constructor.name;
|
|
471
|
+
}
|
|
472
|
+
};
|
|
473
|
+
var Command = class _Command extends EventEmitter {
|
|
474
|
+
/**
|
|
475
|
+
* Initialize a new `Command`.
|
|
476
|
+
*
|
|
477
|
+
* @param {string} [name]
|
|
478
|
+
*/
|
|
479
|
+
constructor(name2) {
|
|
480
|
+
super();
|
|
481
|
+
this.commands = [];
|
|
482
|
+
this.options = [];
|
|
483
|
+
this.parent = null;
|
|
484
|
+
this._allowUnknownOption = false;
|
|
485
|
+
this._allowExcessArguments = true;
|
|
486
|
+
this._args = [];
|
|
487
|
+
this.rawArgs = null;
|
|
488
|
+
this._scriptPath = null;
|
|
489
|
+
this._name = name2 || "";
|
|
490
|
+
this._optionValues = {};
|
|
491
|
+
this._storeOptionsAsProperties = false;
|
|
492
|
+
this._actionResults = [];
|
|
493
|
+
this._actionHandler = null;
|
|
494
|
+
this._executableHandler = false;
|
|
495
|
+
this._executableFile = null;
|
|
496
|
+
this._defaultCommandName = null;
|
|
497
|
+
this._exitCallback = null;
|
|
498
|
+
this._aliases = [];
|
|
499
|
+
this._combineFlagAndOptionalValue = true;
|
|
500
|
+
this._description = "";
|
|
501
|
+
this._argsDescription = void 0;
|
|
502
|
+
this._enablePositionalOptions = false;
|
|
503
|
+
this._passThroughOptions = false;
|
|
504
|
+
this._outputConfiguration = {
|
|
505
|
+
writeOut: (str) => process.stdout.write(str),
|
|
506
|
+
writeErr: (str) => process.stderr.write(str),
|
|
507
|
+
getOutHelpWidth: () => process.stdout.isTTY ? process.stdout.columns : void 0,
|
|
508
|
+
getErrHelpWidth: () => process.stderr.isTTY ? process.stderr.columns : void 0,
|
|
509
|
+
outputError: (str, write) => write(str)
|
|
510
|
+
};
|
|
511
|
+
this._hidden = false;
|
|
512
|
+
this._hasHelpOption = true;
|
|
513
|
+
this._helpFlags = "-h, --help";
|
|
514
|
+
this._helpDescription = "display help for command";
|
|
515
|
+
this._helpShortFlag = "-h";
|
|
516
|
+
this._helpLongFlag = "--help";
|
|
517
|
+
this._addImplicitHelpCommand = void 0;
|
|
518
|
+
this._helpCommandName = "help";
|
|
519
|
+
this._helpCommandnameAndArgs = "help [command]";
|
|
520
|
+
this._helpCommandDescription = "display help for command";
|
|
521
|
+
this._helpConfiguration = {};
|
|
522
|
+
}
|
|
523
|
+
/**
|
|
524
|
+
* Define a command.
|
|
525
|
+
*
|
|
526
|
+
* There are two styles of command: pay attention to where to put the description.
|
|
527
|
+
*
|
|
528
|
+
* Examples:
|
|
529
|
+
*
|
|
530
|
+
* // Command implemented using action handler (description is supplied separately to `.command`)
|
|
531
|
+
* program
|
|
532
|
+
* .command('clone <source> [destination]')
|
|
533
|
+
* .description('clone a repository into a newly created directory')
|
|
534
|
+
* .action((source, destination) => {
|
|
535
|
+
* console.log('clone command called');
|
|
536
|
+
* });
|
|
537
|
+
*
|
|
538
|
+
* // Command implemented using separate executable file (description is second parameter to `.command`)
|
|
539
|
+
* program
|
|
540
|
+
* .command('start <service>', 'start named service')
|
|
541
|
+
* .command('stop [service]', 'stop named service, or all if no name supplied');
|
|
542
|
+
*
|
|
543
|
+
* @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
|
|
544
|
+
* @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
|
|
545
|
+
* @param {Object} [execOpts] - configuration options (for executable)
|
|
546
|
+
* @return {Command} returns new command for action handler, or `this` for executable command
|
|
547
|
+
*/
|
|
548
|
+
command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
|
|
549
|
+
let desc = actionOptsOrExecDesc;
|
|
550
|
+
let opts = execOpts;
|
|
551
|
+
if (typeof desc === "object" && desc !== null) {
|
|
552
|
+
opts = desc;
|
|
553
|
+
desc = null;
|
|
554
|
+
}
|
|
555
|
+
opts = opts || {};
|
|
556
|
+
const args = nameAndArgs.split(/ +/);
|
|
557
|
+
const cmd = this.createCommand(args.shift());
|
|
558
|
+
if (desc) {
|
|
559
|
+
cmd.description(desc);
|
|
560
|
+
cmd._executableHandler = true;
|
|
561
|
+
}
|
|
562
|
+
if (opts.isDefault) this._defaultCommandName = cmd._name;
|
|
563
|
+
cmd._outputConfiguration = this._outputConfiguration;
|
|
564
|
+
cmd._hidden = !!(opts.noHelp || opts.hidden);
|
|
565
|
+
cmd._hasHelpOption = this._hasHelpOption;
|
|
566
|
+
cmd._helpFlags = this._helpFlags;
|
|
567
|
+
cmd._helpDescription = this._helpDescription;
|
|
568
|
+
cmd._helpShortFlag = this._helpShortFlag;
|
|
569
|
+
cmd._helpLongFlag = this._helpLongFlag;
|
|
570
|
+
cmd._helpCommandName = this._helpCommandName;
|
|
571
|
+
cmd._helpCommandnameAndArgs = this._helpCommandnameAndArgs;
|
|
572
|
+
cmd._helpCommandDescription = this._helpCommandDescription;
|
|
573
|
+
cmd._helpConfiguration = this._helpConfiguration;
|
|
574
|
+
cmd._exitCallback = this._exitCallback;
|
|
575
|
+
cmd._storeOptionsAsProperties = this._storeOptionsAsProperties;
|
|
576
|
+
cmd._combineFlagAndOptionalValue = this._combineFlagAndOptionalValue;
|
|
577
|
+
cmd._allowExcessArguments = this._allowExcessArguments;
|
|
578
|
+
cmd._enablePositionalOptions = this._enablePositionalOptions;
|
|
579
|
+
cmd._executableFile = opts.executableFile || null;
|
|
580
|
+
this.commands.push(cmd);
|
|
581
|
+
cmd._parseExpectedArgs(args);
|
|
582
|
+
cmd.parent = this;
|
|
583
|
+
if (desc) return this;
|
|
584
|
+
return cmd;
|
|
585
|
+
}
|
|
586
|
+
/**
|
|
587
|
+
* Factory routine to create a new unattached command.
|
|
588
|
+
*
|
|
589
|
+
* See .command() for creating an attached subcommand, which uses this routine to
|
|
590
|
+
* create the command. You can override createCommand to customise subcommands.
|
|
591
|
+
*
|
|
592
|
+
* @param {string} [name]
|
|
593
|
+
* @return {Command} new command
|
|
594
|
+
*/
|
|
595
|
+
createCommand(name2) {
|
|
596
|
+
return new _Command(name2);
|
|
597
|
+
}
|
|
598
|
+
/**
|
|
599
|
+
* You can customise the help with a subclass of Help by overriding createHelp,
|
|
600
|
+
* or by overriding Help properties using configureHelp().
|
|
601
|
+
*
|
|
602
|
+
* @return {Help}
|
|
603
|
+
*/
|
|
604
|
+
createHelp() {
|
|
605
|
+
return Object.assign(new Help(), this.configureHelp());
|
|
606
|
+
}
|
|
607
|
+
/**
|
|
608
|
+
* You can customise the help by overriding Help properties using configureHelp(),
|
|
609
|
+
* or with a subclass of Help by overriding createHelp().
|
|
610
|
+
*
|
|
611
|
+
* @param {Object} [configuration] - configuration options
|
|
612
|
+
* @return {Command|Object} `this` command for chaining, or stored configuration
|
|
613
|
+
*/
|
|
614
|
+
configureHelp(configuration) {
|
|
615
|
+
if (configuration === void 0) return this._helpConfiguration;
|
|
616
|
+
this._helpConfiguration = configuration;
|
|
617
|
+
return this;
|
|
618
|
+
}
|
|
619
|
+
/**
|
|
620
|
+
* The default output goes to stdout and stderr. You can customise this for special
|
|
621
|
+
* applications. You can also customise the display of errors by overriding outputError.
|
|
622
|
+
*
|
|
623
|
+
* The configuration properties are all functions:
|
|
624
|
+
*
|
|
625
|
+
* // functions to change where being written, stdout and stderr
|
|
626
|
+
* writeOut(str)
|
|
627
|
+
* writeErr(str)
|
|
628
|
+
* // matching functions to specify width for wrapping help
|
|
629
|
+
* getOutHelpWidth()
|
|
630
|
+
* getErrHelpWidth()
|
|
631
|
+
* // functions based on what is being written out
|
|
632
|
+
* outputError(str, write) // used for displaying errors, and not used for displaying help
|
|
633
|
+
*
|
|
634
|
+
* @param {Object} [configuration] - configuration options
|
|
635
|
+
* @return {Command|Object} `this` command for chaining, or stored configuration
|
|
636
|
+
*/
|
|
637
|
+
configureOutput(configuration) {
|
|
638
|
+
if (configuration === void 0) return this._outputConfiguration;
|
|
639
|
+
Object.assign(this._outputConfiguration, configuration);
|
|
640
|
+
return this;
|
|
641
|
+
}
|
|
642
|
+
/**
|
|
643
|
+
* Add a prepared subcommand.
|
|
644
|
+
*
|
|
645
|
+
* See .command() for creating an attached subcommand which inherits settings from its parent.
|
|
646
|
+
*
|
|
647
|
+
* @param {Command} cmd - new subcommand
|
|
648
|
+
* @param {Object} [opts] - configuration options
|
|
649
|
+
* @return {Command} `this` command for chaining
|
|
650
|
+
*/
|
|
651
|
+
addCommand(cmd, opts) {
|
|
652
|
+
if (!cmd._name) throw new Error("Command passed to .addCommand() must have a name");
|
|
653
|
+
function checkExplicitNames(commandArray) {
|
|
654
|
+
commandArray.forEach((cmd2) => {
|
|
655
|
+
if (cmd2._executableHandler && !cmd2._executableFile) {
|
|
656
|
+
throw new Error(`Must specify executableFile for deeply nested executable: ${cmd2.name()}`);
|
|
657
|
+
}
|
|
658
|
+
checkExplicitNames(cmd2.commands);
|
|
659
|
+
});
|
|
660
|
+
}
|
|
661
|
+
checkExplicitNames(cmd.commands);
|
|
662
|
+
opts = opts || {};
|
|
663
|
+
if (opts.isDefault) this._defaultCommandName = cmd._name;
|
|
664
|
+
if (opts.noHelp || opts.hidden) cmd._hidden = true;
|
|
665
|
+
this.commands.push(cmd);
|
|
666
|
+
cmd.parent = this;
|
|
667
|
+
return this;
|
|
668
|
+
}
|
|
669
|
+
/**
|
|
670
|
+
* Define argument syntax for the command.
|
|
671
|
+
*/
|
|
672
|
+
arguments(desc) {
|
|
673
|
+
return this._parseExpectedArgs(desc.split(/ +/));
|
|
674
|
+
}
|
|
675
|
+
/**
|
|
676
|
+
* Override default decision whether to add implicit help command.
|
|
677
|
+
*
|
|
678
|
+
* addHelpCommand() // force on
|
|
679
|
+
* addHelpCommand(false); // force off
|
|
680
|
+
* addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details
|
|
681
|
+
*
|
|
682
|
+
* @return {Command} `this` command for chaining
|
|
683
|
+
*/
|
|
684
|
+
addHelpCommand(enableOrNameAndArgs, description2) {
|
|
685
|
+
if (enableOrNameAndArgs === false) {
|
|
686
|
+
this._addImplicitHelpCommand = false;
|
|
687
|
+
} else {
|
|
688
|
+
this._addImplicitHelpCommand = true;
|
|
689
|
+
if (typeof enableOrNameAndArgs === "string") {
|
|
690
|
+
this._helpCommandName = enableOrNameAndArgs.split(" ")[0];
|
|
691
|
+
this._helpCommandnameAndArgs = enableOrNameAndArgs;
|
|
692
|
+
}
|
|
693
|
+
this._helpCommandDescription = description2 || this._helpCommandDescription;
|
|
694
|
+
}
|
|
695
|
+
return this;
|
|
696
|
+
}
|
|
697
|
+
/**
|
|
698
|
+
* @return {boolean}
|
|
699
|
+
* @api private
|
|
700
|
+
*/
|
|
701
|
+
_hasImplicitHelpCommand() {
|
|
702
|
+
if (this._addImplicitHelpCommand === void 0) {
|
|
703
|
+
return this.commands.length && !this._actionHandler && !this._findCommand("help");
|
|
704
|
+
}
|
|
705
|
+
return this._addImplicitHelpCommand;
|
|
706
|
+
}
|
|
707
|
+
/**
|
|
708
|
+
* Parse expected `args`.
|
|
709
|
+
*
|
|
710
|
+
* For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`.
|
|
711
|
+
*
|
|
712
|
+
* @param {Array} args
|
|
713
|
+
* @return {Command} `this` command for chaining
|
|
714
|
+
* @api private
|
|
715
|
+
*/
|
|
716
|
+
_parseExpectedArgs(args) {
|
|
717
|
+
if (!args.length) return;
|
|
718
|
+
args.forEach((arg) => {
|
|
719
|
+
const argDetails = {
|
|
720
|
+
required: false,
|
|
721
|
+
name: "",
|
|
722
|
+
variadic: false
|
|
723
|
+
};
|
|
724
|
+
switch (arg[0]) {
|
|
725
|
+
case "<":
|
|
726
|
+
argDetails.required = true;
|
|
727
|
+
argDetails.name = arg.slice(1, -1);
|
|
728
|
+
break;
|
|
729
|
+
case "[":
|
|
730
|
+
argDetails.name = arg.slice(1, -1);
|
|
731
|
+
break;
|
|
732
|
+
}
|
|
733
|
+
if (argDetails.name.length > 3 && argDetails.name.slice(-3) === "...") {
|
|
734
|
+
argDetails.variadic = true;
|
|
735
|
+
argDetails.name = argDetails.name.slice(0, -3);
|
|
736
|
+
}
|
|
737
|
+
if (argDetails.name) {
|
|
738
|
+
this._args.push(argDetails);
|
|
739
|
+
}
|
|
740
|
+
});
|
|
741
|
+
this._args.forEach((arg, i) => {
|
|
742
|
+
if (arg.variadic && i < this._args.length - 1) {
|
|
743
|
+
throw new Error(`only the last argument can be variadic '${arg.name}'`);
|
|
744
|
+
}
|
|
745
|
+
});
|
|
746
|
+
return this;
|
|
747
|
+
}
|
|
748
|
+
/**
|
|
749
|
+
* Register callback to use as replacement for calling process.exit.
|
|
750
|
+
*
|
|
751
|
+
* @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
|
|
752
|
+
* @return {Command} `this` command for chaining
|
|
753
|
+
*/
|
|
754
|
+
exitOverride(fn) {
|
|
755
|
+
if (fn) {
|
|
756
|
+
this._exitCallback = fn;
|
|
757
|
+
} else {
|
|
758
|
+
this._exitCallback = (err) => {
|
|
759
|
+
if (err.code !== "commander.executeSubCommandAsync") {
|
|
760
|
+
throw err;
|
|
761
|
+
} else {
|
|
762
|
+
}
|
|
763
|
+
};
|
|
764
|
+
}
|
|
765
|
+
return this;
|
|
766
|
+
}
|
|
767
|
+
/**
|
|
768
|
+
* Call process.exit, and _exitCallback if defined.
|
|
769
|
+
*
|
|
770
|
+
* @param {number} exitCode exit code for using with process.exit
|
|
771
|
+
* @param {string} code an id string representing the error
|
|
772
|
+
* @param {string} message human-readable description of the error
|
|
773
|
+
* @return never
|
|
774
|
+
* @api private
|
|
775
|
+
*/
|
|
776
|
+
_exit(exitCode, code, message) {
|
|
777
|
+
if (this._exitCallback) {
|
|
778
|
+
this._exitCallback(new CommanderError(exitCode, code, message));
|
|
779
|
+
}
|
|
780
|
+
process.exit(exitCode);
|
|
781
|
+
}
|
|
782
|
+
/**
|
|
783
|
+
* Register callback `fn` for the command.
|
|
784
|
+
*
|
|
785
|
+
* Examples:
|
|
786
|
+
*
|
|
787
|
+
* program
|
|
788
|
+
* .command('help')
|
|
789
|
+
* .description('display verbose help')
|
|
790
|
+
* .action(function() {
|
|
791
|
+
* // output help here
|
|
792
|
+
* });
|
|
793
|
+
*
|
|
794
|
+
* @param {Function} fn
|
|
795
|
+
* @return {Command} `this` command for chaining
|
|
796
|
+
*/
|
|
797
|
+
action(fn) {
|
|
798
|
+
const listener = (args) => {
|
|
799
|
+
const expectedArgsCount = this._args.length;
|
|
800
|
+
const actionArgs = args.slice(0, expectedArgsCount);
|
|
801
|
+
if (this._storeOptionsAsProperties) {
|
|
802
|
+
actionArgs[expectedArgsCount] = this;
|
|
803
|
+
} else {
|
|
804
|
+
actionArgs[expectedArgsCount] = this.opts();
|
|
805
|
+
}
|
|
806
|
+
actionArgs.push(this);
|
|
807
|
+
const actionResult = fn.apply(this, actionArgs);
|
|
808
|
+
let rootCommand = this;
|
|
809
|
+
while (rootCommand.parent) {
|
|
810
|
+
rootCommand = rootCommand.parent;
|
|
811
|
+
}
|
|
812
|
+
rootCommand._actionResults.push(actionResult);
|
|
813
|
+
};
|
|
814
|
+
this._actionHandler = listener;
|
|
815
|
+
return this;
|
|
816
|
+
}
|
|
817
|
+
/**
|
|
818
|
+
* Factory routine to create a new unattached option.
|
|
819
|
+
*
|
|
820
|
+
* See .option() for creating an attached option, which uses this routine to
|
|
821
|
+
* create the option. You can override createOption to return a custom option.
|
|
822
|
+
*
|
|
823
|
+
* @param {string} flags
|
|
824
|
+
* @param {string} [description]
|
|
825
|
+
* @return {Option} new option
|
|
826
|
+
*/
|
|
827
|
+
createOption(flags, description2) {
|
|
828
|
+
return new Option(flags, description2);
|
|
829
|
+
}
|
|
830
|
+
/**
|
|
831
|
+
* Add an option.
|
|
832
|
+
*
|
|
833
|
+
* @param {Option} option
|
|
834
|
+
* @return {Command} `this` command for chaining
|
|
835
|
+
*/
|
|
836
|
+
addOption(option) {
|
|
837
|
+
const oname = option.name();
|
|
838
|
+
const name2 = option.attributeName();
|
|
839
|
+
let defaultValue = option.defaultValue;
|
|
840
|
+
if (option.negate || option.optional || option.required || typeof defaultValue === "boolean") {
|
|
841
|
+
if (option.negate) {
|
|
842
|
+
const positiveLongFlag = option.long.replace(/^--no-/, "--");
|
|
843
|
+
defaultValue = this._findOption(positiveLongFlag) ? this._getOptionValue(name2) : true;
|
|
844
|
+
}
|
|
845
|
+
if (defaultValue !== void 0) {
|
|
846
|
+
this._setOptionValue(name2, defaultValue);
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
this.options.push(option);
|
|
850
|
+
this.on("option:" + oname, (val) => {
|
|
851
|
+
const oldValue = this._getOptionValue(name2);
|
|
852
|
+
if (val !== null && option.parseArg) {
|
|
853
|
+
try {
|
|
854
|
+
val = option.parseArg(val, oldValue === void 0 ? defaultValue : oldValue);
|
|
855
|
+
} catch (err) {
|
|
856
|
+
if (err.code === "commander.invalidOptionArgument") {
|
|
857
|
+
const message = `error: option '${option.flags}' argument '${val}' is invalid. ${err.message}`;
|
|
858
|
+
this._displayError(err.exitCode, err.code, message);
|
|
859
|
+
}
|
|
860
|
+
throw err;
|
|
861
|
+
}
|
|
862
|
+
} else if (val !== null && option.variadic) {
|
|
863
|
+
val = option._concatValue(val, oldValue);
|
|
864
|
+
}
|
|
865
|
+
if (typeof oldValue === "boolean" || typeof oldValue === "undefined") {
|
|
866
|
+
if (val == null) {
|
|
867
|
+
this._setOptionValue(name2, option.negate ? false : defaultValue || true);
|
|
868
|
+
} else {
|
|
869
|
+
this._setOptionValue(name2, val);
|
|
870
|
+
}
|
|
871
|
+
} else if (val !== null) {
|
|
872
|
+
this._setOptionValue(name2, option.negate ? false : val);
|
|
873
|
+
}
|
|
874
|
+
});
|
|
875
|
+
return this;
|
|
876
|
+
}
|
|
877
|
+
/**
|
|
878
|
+
* Internal implementation shared by .option() and .requiredOption()
|
|
879
|
+
*
|
|
880
|
+
* @api private
|
|
881
|
+
*/
|
|
882
|
+
_optionEx(config, flags, description2, fn, defaultValue) {
|
|
883
|
+
const option = this.createOption(flags, description2);
|
|
884
|
+
option.makeOptionMandatory(!!config.mandatory);
|
|
885
|
+
if (typeof fn === "function") {
|
|
886
|
+
option.default(defaultValue).argParser(fn);
|
|
887
|
+
} else if (fn instanceof RegExp) {
|
|
888
|
+
const regex = fn;
|
|
889
|
+
fn = (val, def) => {
|
|
890
|
+
const m = regex.exec(val);
|
|
891
|
+
return m ? m[0] : def;
|
|
892
|
+
};
|
|
893
|
+
option.default(defaultValue).argParser(fn);
|
|
894
|
+
} else {
|
|
895
|
+
option.default(fn);
|
|
896
|
+
}
|
|
897
|
+
return this.addOption(option);
|
|
898
|
+
}
|
|
899
|
+
/**
|
|
900
|
+
* Define option with `flags`, `description` and optional
|
|
901
|
+
* coercion `fn`.
|
|
902
|
+
*
|
|
903
|
+
* The `flags` string contains the short and/or long flags,
|
|
904
|
+
* separated by comma, a pipe or space. The following are all valid
|
|
905
|
+
* all will output this way when `--help` is used.
|
|
906
|
+
*
|
|
907
|
+
* "-p, --pepper"
|
|
908
|
+
* "-p|--pepper"
|
|
909
|
+
* "-p --pepper"
|
|
910
|
+
*
|
|
911
|
+
* Examples:
|
|
912
|
+
*
|
|
913
|
+
* // simple boolean defaulting to undefined
|
|
914
|
+
* program.option('-p, --pepper', 'add pepper');
|
|
915
|
+
*
|
|
916
|
+
* program.pepper
|
|
917
|
+
* // => undefined
|
|
918
|
+
*
|
|
919
|
+
* --pepper
|
|
920
|
+
* program.pepper
|
|
921
|
+
* // => true
|
|
922
|
+
*
|
|
923
|
+
* // simple boolean defaulting to true (unless non-negated option is also defined)
|
|
924
|
+
* program.option('-C, --no-cheese', 'remove cheese');
|
|
925
|
+
*
|
|
926
|
+
* program.cheese
|
|
927
|
+
* // => true
|
|
928
|
+
*
|
|
929
|
+
* --no-cheese
|
|
930
|
+
* program.cheese
|
|
931
|
+
* // => false
|
|
932
|
+
*
|
|
933
|
+
* // required argument
|
|
934
|
+
* program.option('-C, --chdir <path>', 'change the working directory');
|
|
935
|
+
*
|
|
936
|
+
* --chdir /tmp
|
|
937
|
+
* program.chdir
|
|
938
|
+
* // => "/tmp"
|
|
939
|
+
*
|
|
940
|
+
* // optional argument
|
|
941
|
+
* program.option('-c, --cheese [type]', 'add cheese [marble]');
|
|
942
|
+
*
|
|
943
|
+
* @param {string} flags
|
|
944
|
+
* @param {string} [description]
|
|
945
|
+
* @param {Function|*} [fn] - custom option processing function or default value
|
|
946
|
+
* @param {*} [defaultValue]
|
|
947
|
+
* @return {Command} `this` command for chaining
|
|
948
|
+
*/
|
|
949
|
+
option(flags, description2, fn, defaultValue) {
|
|
950
|
+
return this._optionEx({}, flags, description2, fn, defaultValue);
|
|
951
|
+
}
|
|
952
|
+
/**
|
|
953
|
+
* Add a required option which must have a value after parsing. This usually means
|
|
954
|
+
* the option must be specified on the command line. (Otherwise the same as .option().)
|
|
955
|
+
*
|
|
956
|
+
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
|
|
957
|
+
*
|
|
958
|
+
* @param {string} flags
|
|
959
|
+
* @param {string} [description]
|
|
960
|
+
* @param {Function|*} [fn] - custom option processing function or default value
|
|
961
|
+
* @param {*} [defaultValue]
|
|
962
|
+
* @return {Command} `this` command for chaining
|
|
963
|
+
*/
|
|
964
|
+
requiredOption(flags, description2, fn, defaultValue) {
|
|
965
|
+
return this._optionEx({ mandatory: true }, flags, description2, fn, defaultValue);
|
|
966
|
+
}
|
|
967
|
+
/**
|
|
968
|
+
* Alter parsing of short flags with optional values.
|
|
969
|
+
*
|
|
970
|
+
* Examples:
|
|
971
|
+
*
|
|
972
|
+
* // for `.option('-f,--flag [value]'):
|
|
973
|
+
* .combineFlagAndOptionalValue(true) // `-f80` is treated like `--flag=80`, this is the default behaviour
|
|
974
|
+
* .combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
|
|
975
|
+
*
|
|
976
|
+
* @param {Boolean} [combine=true] - if `true` or omitted, an optional value can be specified directly after the flag.
|
|
977
|
+
*/
|
|
978
|
+
combineFlagAndOptionalValue(combine = true) {
|
|
979
|
+
this._combineFlagAndOptionalValue = !!combine;
|
|
980
|
+
return this;
|
|
981
|
+
}
|
|
982
|
+
/**
|
|
983
|
+
* Allow unknown options on the command line.
|
|
984
|
+
*
|
|
985
|
+
* @param {Boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown
|
|
986
|
+
* for unknown options.
|
|
987
|
+
*/
|
|
988
|
+
allowUnknownOption(allowUnknown = true) {
|
|
989
|
+
this._allowUnknownOption = !!allowUnknown;
|
|
990
|
+
return this;
|
|
991
|
+
}
|
|
992
|
+
/**
|
|
993
|
+
* Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
|
|
994
|
+
*
|
|
995
|
+
* @param {Boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown
|
|
996
|
+
* for excess arguments.
|
|
997
|
+
*/
|
|
998
|
+
allowExcessArguments(allowExcess = true) {
|
|
999
|
+
this._allowExcessArguments = !!allowExcess;
|
|
1000
|
+
return this;
|
|
1001
|
+
}
|
|
1002
|
+
/**
|
|
1003
|
+
* Enable positional options. Positional means global options are specified before subcommands which lets
|
|
1004
|
+
* subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
|
|
1005
|
+
* The default behaviour is non-positional and global options may appear anywhere on the command line.
|
|
1006
|
+
*
|
|
1007
|
+
* @param {Boolean} [positional=true]
|
|
1008
|
+
*/
|
|
1009
|
+
enablePositionalOptions(positional = true) {
|
|
1010
|
+
this._enablePositionalOptions = !!positional;
|
|
1011
|
+
return this;
|
|
1012
|
+
}
|
|
1013
|
+
/**
|
|
1014
|
+
* Pass through options that come after command-arguments rather than treat them as command-options,
|
|
1015
|
+
* so actual command-options come before command-arguments. Turning this on for a subcommand requires
|
|
1016
|
+
* positional options to have been enabled on the program (parent commands).
|
|
1017
|
+
* The default behaviour is non-positional and options may appear before or after command-arguments.
|
|
1018
|
+
*
|
|
1019
|
+
* @param {Boolean} [passThrough=true]
|
|
1020
|
+
* for unknown options.
|
|
1021
|
+
*/
|
|
1022
|
+
passThroughOptions(passThrough = true) {
|
|
1023
|
+
this._passThroughOptions = !!passThrough;
|
|
1024
|
+
if (!!this.parent && passThrough && !this.parent._enablePositionalOptions) {
|
|
1025
|
+
throw new Error("passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)");
|
|
1026
|
+
}
|
|
1027
|
+
return this;
|
|
1028
|
+
}
|
|
1029
|
+
/**
|
|
1030
|
+
* Whether to store option values as properties on command object,
|
|
1031
|
+
* or store separately (specify false). In both cases the option values can be accessed using .opts().
|
|
1032
|
+
*
|
|
1033
|
+
* @param {boolean} [storeAsProperties=true]
|
|
1034
|
+
* @return {Command} `this` command for chaining
|
|
1035
|
+
*/
|
|
1036
|
+
storeOptionsAsProperties(storeAsProperties = true) {
|
|
1037
|
+
this._storeOptionsAsProperties = !!storeAsProperties;
|
|
1038
|
+
if (this.options.length) {
|
|
1039
|
+
throw new Error("call .storeOptionsAsProperties() before adding options");
|
|
1040
|
+
}
|
|
1041
|
+
return this;
|
|
1042
|
+
}
|
|
1043
|
+
/**
|
|
1044
|
+
* Store option value
|
|
1045
|
+
*
|
|
1046
|
+
* @param {string} key
|
|
1047
|
+
* @param {Object} value
|
|
1048
|
+
* @api private
|
|
1049
|
+
*/
|
|
1050
|
+
_setOptionValue(key, value) {
|
|
1051
|
+
if (this._storeOptionsAsProperties) {
|
|
1052
|
+
this[key] = value;
|
|
1053
|
+
} else {
|
|
1054
|
+
this._optionValues[key] = value;
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
/**
|
|
1058
|
+
* Retrieve option value
|
|
1059
|
+
*
|
|
1060
|
+
* @param {string} key
|
|
1061
|
+
* @return {Object} value
|
|
1062
|
+
* @api private
|
|
1063
|
+
*/
|
|
1064
|
+
_getOptionValue(key) {
|
|
1065
|
+
if (this._storeOptionsAsProperties) {
|
|
1066
|
+
return this[key];
|
|
1067
|
+
}
|
|
1068
|
+
return this._optionValues[key];
|
|
1069
|
+
}
|
|
1070
|
+
/**
|
|
1071
|
+
* Parse `argv`, setting options and invoking commands when defined.
|
|
1072
|
+
*
|
|
1073
|
+
* The default expectation is that the arguments are from node and have the application as argv[0]
|
|
1074
|
+
* and the script being run in argv[1], with user parameters after that.
|
|
1075
|
+
*
|
|
1076
|
+
* Examples:
|
|
1077
|
+
*
|
|
1078
|
+
* program.parse(process.argv);
|
|
1079
|
+
* program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions
|
|
1080
|
+
* program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
|
|
1081
|
+
*
|
|
1082
|
+
* @param {string[]} [argv] - optional, defaults to process.argv
|
|
1083
|
+
* @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron
|
|
1084
|
+
* @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
|
|
1085
|
+
* @return {Command} `this` command for chaining
|
|
1086
|
+
*/
|
|
1087
|
+
parse(argv, parseOptions) {
|
|
1088
|
+
if (argv !== void 0 && !Array.isArray(argv)) {
|
|
1089
|
+
throw new Error("first parameter to parse must be array or undefined");
|
|
1090
|
+
}
|
|
1091
|
+
parseOptions = parseOptions || {};
|
|
1092
|
+
if (argv === void 0) {
|
|
1093
|
+
argv = process.argv;
|
|
1094
|
+
if (process.versions && process.versions.electron) {
|
|
1095
|
+
parseOptions.from = "electron";
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
this.rawArgs = argv.slice();
|
|
1099
|
+
let userArgs;
|
|
1100
|
+
switch (parseOptions.from) {
|
|
1101
|
+
case void 0:
|
|
1102
|
+
case "node":
|
|
1103
|
+
this._scriptPath = argv[1];
|
|
1104
|
+
userArgs = argv.slice(2);
|
|
1105
|
+
break;
|
|
1106
|
+
case "electron":
|
|
1107
|
+
if (process.defaultApp) {
|
|
1108
|
+
this._scriptPath = argv[1];
|
|
1109
|
+
userArgs = argv.slice(2);
|
|
1110
|
+
} else {
|
|
1111
|
+
userArgs = argv.slice(1);
|
|
1112
|
+
}
|
|
1113
|
+
break;
|
|
1114
|
+
case "user":
|
|
1115
|
+
userArgs = argv.slice(0);
|
|
1116
|
+
break;
|
|
1117
|
+
default:
|
|
1118
|
+
throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
|
|
1119
|
+
}
|
|
1120
|
+
if (!this._scriptPath && require.main) {
|
|
1121
|
+
this._scriptPath = require.main.filename;
|
|
1122
|
+
}
|
|
1123
|
+
this._name = this._name || this._scriptPath && path4.basename(this._scriptPath, path4.extname(this._scriptPath));
|
|
1124
|
+
this._parseCommand([], userArgs);
|
|
1125
|
+
return this;
|
|
1126
|
+
}
|
|
1127
|
+
/**
|
|
1128
|
+
* Parse `argv`, setting options and invoking commands when defined.
|
|
1129
|
+
*
|
|
1130
|
+
* Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.
|
|
1131
|
+
*
|
|
1132
|
+
* The default expectation is that the arguments are from node and have the application as argv[0]
|
|
1133
|
+
* and the script being run in argv[1], with user parameters after that.
|
|
1134
|
+
*
|
|
1135
|
+
* Examples:
|
|
1136
|
+
*
|
|
1137
|
+
* program.parseAsync(process.argv);
|
|
1138
|
+
* program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions
|
|
1139
|
+
* program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
|
|
1140
|
+
*
|
|
1141
|
+
* @param {string[]} [argv]
|
|
1142
|
+
* @param {Object} [parseOptions]
|
|
1143
|
+
* @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
|
|
1144
|
+
* @return {Promise}
|
|
1145
|
+
*/
|
|
1146
|
+
parseAsync(argv, parseOptions) {
|
|
1147
|
+
this.parse(argv, parseOptions);
|
|
1148
|
+
return Promise.all(this._actionResults).then(() => this);
|
|
1149
|
+
}
|
|
1150
|
+
/**
|
|
1151
|
+
* Execute a sub-command executable.
|
|
1152
|
+
*
|
|
1153
|
+
* @api private
|
|
1154
|
+
*/
|
|
1155
|
+
_executeSubCommand(subcommand, args) {
|
|
1156
|
+
args = args.slice();
|
|
1157
|
+
let launchWithNode = false;
|
|
1158
|
+
const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
|
|
1159
|
+
this._checkForMissingMandatoryOptions();
|
|
1160
|
+
let scriptPath = this._scriptPath;
|
|
1161
|
+
if (!scriptPath && require.main) {
|
|
1162
|
+
scriptPath = require.main.filename;
|
|
1163
|
+
}
|
|
1164
|
+
let baseDir;
|
|
1165
|
+
try {
|
|
1166
|
+
const resolvedLink = fs.realpathSync(scriptPath);
|
|
1167
|
+
baseDir = path4.dirname(resolvedLink);
|
|
1168
|
+
} catch (e) {
|
|
1169
|
+
baseDir = ".";
|
|
1170
|
+
}
|
|
1171
|
+
let bin = path4.basename(scriptPath, path4.extname(scriptPath)) + "-" + subcommand._name;
|
|
1172
|
+
if (subcommand._executableFile) {
|
|
1173
|
+
bin = subcommand._executableFile;
|
|
1174
|
+
}
|
|
1175
|
+
const localBin = path4.join(baseDir, bin);
|
|
1176
|
+
if (fs.existsSync(localBin)) {
|
|
1177
|
+
bin = localBin;
|
|
1178
|
+
} else {
|
|
1179
|
+
sourceExt.forEach((ext) => {
|
|
1180
|
+
if (fs.existsSync(`${localBin}${ext}`)) {
|
|
1181
|
+
bin = `${localBin}${ext}`;
|
|
1182
|
+
}
|
|
1183
|
+
});
|
|
1184
|
+
}
|
|
1185
|
+
launchWithNode = sourceExt.includes(path4.extname(bin));
|
|
1186
|
+
let proc;
|
|
1187
|
+
if (process.platform !== "win32") {
|
|
1188
|
+
if (launchWithNode) {
|
|
1189
|
+
args.unshift(bin);
|
|
1190
|
+
args = incrementNodeInspectorPort(process.execArgv).concat(args);
|
|
1191
|
+
proc = childProcess.spawn(process.argv[0], args, { stdio: "inherit" });
|
|
1192
|
+
} else {
|
|
1193
|
+
proc = childProcess.spawn(bin, args, { stdio: "inherit" });
|
|
1194
|
+
}
|
|
1195
|
+
} else {
|
|
1196
|
+
args.unshift(bin);
|
|
1197
|
+
args = incrementNodeInspectorPort(process.execArgv).concat(args);
|
|
1198
|
+
proc = childProcess.spawn(process.execPath, args, { stdio: "inherit" });
|
|
1199
|
+
}
|
|
1200
|
+
const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
|
|
1201
|
+
signals.forEach((signal) => {
|
|
1202
|
+
process.on(signal, () => {
|
|
1203
|
+
if (proc.killed === false && proc.exitCode === null) {
|
|
1204
|
+
proc.kill(signal);
|
|
1205
|
+
}
|
|
1206
|
+
});
|
|
1207
|
+
});
|
|
1208
|
+
const exitCallback = this._exitCallback;
|
|
1209
|
+
if (!exitCallback) {
|
|
1210
|
+
proc.on("close", process.exit.bind(process));
|
|
1211
|
+
} else {
|
|
1212
|
+
proc.on("close", () => {
|
|
1213
|
+
exitCallback(new CommanderError(process.exitCode || 0, "commander.executeSubCommandAsync", "(close)"));
|
|
1214
|
+
});
|
|
1215
|
+
}
|
|
1216
|
+
proc.on("error", (err) => {
|
|
1217
|
+
if (err.code === "ENOENT") {
|
|
1218
|
+
const executableMissing = `'${bin}' does not exist
|
|
1219
|
+
- if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
1220
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name`;
|
|
1221
|
+
throw new Error(executableMissing);
|
|
1222
|
+
} else if (err.code === "EACCES") {
|
|
1223
|
+
throw new Error(`'${bin}' not executable`);
|
|
1224
|
+
}
|
|
1225
|
+
if (!exitCallback) {
|
|
1226
|
+
process.exit(1);
|
|
1227
|
+
} else {
|
|
1228
|
+
const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
|
|
1229
|
+
wrappedError.nestedError = err;
|
|
1230
|
+
exitCallback(wrappedError);
|
|
1231
|
+
}
|
|
1232
|
+
});
|
|
1233
|
+
this.runningCommand = proc;
|
|
1234
|
+
}
|
|
1235
|
+
/**
|
|
1236
|
+
* @api private
|
|
1237
|
+
*/
|
|
1238
|
+
_dispatchSubcommand(commandName, operands, unknown) {
|
|
1239
|
+
const subCommand = this._findCommand(commandName);
|
|
1240
|
+
if (!subCommand) this.help({ error: true });
|
|
1241
|
+
if (subCommand._executableHandler) {
|
|
1242
|
+
this._executeSubCommand(subCommand, operands.concat(unknown));
|
|
1243
|
+
} else {
|
|
1244
|
+
subCommand._parseCommand(operands, unknown);
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
/**
|
|
1248
|
+
* Process arguments in context of this command.
|
|
1249
|
+
*
|
|
1250
|
+
* @api private
|
|
1251
|
+
*/
|
|
1252
|
+
_parseCommand(operands, unknown) {
|
|
1253
|
+
const parsed = this.parseOptions(unknown);
|
|
1254
|
+
operands = operands.concat(parsed.operands);
|
|
1255
|
+
unknown = parsed.unknown;
|
|
1256
|
+
this.args = operands.concat(unknown);
|
|
1257
|
+
if (operands && this._findCommand(operands[0])) {
|
|
1258
|
+
this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
|
|
1259
|
+
} else if (this._hasImplicitHelpCommand() && operands[0] === this._helpCommandName) {
|
|
1260
|
+
if (operands.length === 1) {
|
|
1261
|
+
this.help();
|
|
1262
|
+
} else {
|
|
1263
|
+
this._dispatchSubcommand(operands[1], [], [this._helpLongFlag]);
|
|
1264
|
+
}
|
|
1265
|
+
} else if (this._defaultCommandName) {
|
|
1266
|
+
outputHelpIfRequested(this, unknown);
|
|
1267
|
+
this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
|
|
1268
|
+
} else {
|
|
1269
|
+
if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
|
|
1270
|
+
this.help({ error: true });
|
|
1271
|
+
}
|
|
1272
|
+
outputHelpIfRequested(this, parsed.unknown);
|
|
1273
|
+
this._checkForMissingMandatoryOptions();
|
|
1274
|
+
const checkForUnknownOptions = () => {
|
|
1275
|
+
if (parsed.unknown.length > 0) {
|
|
1276
|
+
this.unknownOption(parsed.unknown[0]);
|
|
1277
|
+
}
|
|
1278
|
+
};
|
|
1279
|
+
const commandEvent = `command:${this.name()}`;
|
|
1280
|
+
if (this._actionHandler) {
|
|
1281
|
+
checkForUnknownOptions();
|
|
1282
|
+
const args = this.args.slice();
|
|
1283
|
+
this._args.forEach((arg, i) => {
|
|
1284
|
+
if (arg.required && args[i] == null) {
|
|
1285
|
+
this.missingArgument(arg.name);
|
|
1286
|
+
} else if (arg.variadic) {
|
|
1287
|
+
args[i] = args.splice(i);
|
|
1288
|
+
args.length = Math.min(i + 1, args.length);
|
|
1289
|
+
}
|
|
1290
|
+
});
|
|
1291
|
+
if (args.length > this._args.length) {
|
|
1292
|
+
this._excessArguments(args);
|
|
1293
|
+
}
|
|
1294
|
+
this._actionHandler(args);
|
|
1295
|
+
if (this.parent) this.parent.emit(commandEvent, operands, unknown);
|
|
1296
|
+
} else if (this.parent && this.parent.listenerCount(commandEvent)) {
|
|
1297
|
+
checkForUnknownOptions();
|
|
1298
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
1299
|
+
} else if (operands.length) {
|
|
1300
|
+
if (this._findCommand("*")) {
|
|
1301
|
+
this._dispatchSubcommand("*", operands, unknown);
|
|
1302
|
+
} else if (this.listenerCount("command:*")) {
|
|
1303
|
+
this.emit("command:*", operands, unknown);
|
|
1304
|
+
} else if (this.commands.length) {
|
|
1305
|
+
this.unknownCommand();
|
|
1306
|
+
} else {
|
|
1307
|
+
checkForUnknownOptions();
|
|
1308
|
+
}
|
|
1309
|
+
} else if (this.commands.length) {
|
|
1310
|
+
this.help({ error: true });
|
|
1311
|
+
} else {
|
|
1312
|
+
checkForUnknownOptions();
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
/**
|
|
1317
|
+
* Find matching command.
|
|
1318
|
+
*
|
|
1319
|
+
* @api private
|
|
1320
|
+
*/
|
|
1321
|
+
_findCommand(name2) {
|
|
1322
|
+
if (!name2) return void 0;
|
|
1323
|
+
return this.commands.find((cmd) => cmd._name === name2 || cmd._aliases.includes(name2));
|
|
1324
|
+
}
|
|
1325
|
+
/**
|
|
1326
|
+
* Return an option matching `arg` if any.
|
|
1327
|
+
*
|
|
1328
|
+
* @param {string} arg
|
|
1329
|
+
* @return {Option}
|
|
1330
|
+
* @api private
|
|
1331
|
+
*/
|
|
1332
|
+
_findOption(arg) {
|
|
1333
|
+
return this.options.find((option) => option.is(arg));
|
|
1334
|
+
}
|
|
1335
|
+
/**
|
|
1336
|
+
* Display an error message if a mandatory option does not have a value.
|
|
1337
|
+
* Lazy calling after checking for help flags from leaf subcommand.
|
|
1338
|
+
*
|
|
1339
|
+
* @api private
|
|
1340
|
+
*/
|
|
1341
|
+
_checkForMissingMandatoryOptions() {
|
|
1342
|
+
for (let cmd = this; cmd; cmd = cmd.parent) {
|
|
1343
|
+
cmd.options.forEach((anOption) => {
|
|
1344
|
+
if (anOption.mandatory && cmd._getOptionValue(anOption.attributeName()) === void 0) {
|
|
1345
|
+
cmd.missingMandatoryOptionValue(anOption);
|
|
1346
|
+
}
|
|
1347
|
+
});
|
|
1348
|
+
}
|
|
1349
|
+
}
|
|
1350
|
+
/**
|
|
1351
|
+
* Parse options from `argv` removing known options,
|
|
1352
|
+
* and return argv split into operands and unknown arguments.
|
|
1353
|
+
*
|
|
1354
|
+
* Examples:
|
|
1355
|
+
*
|
|
1356
|
+
* argv => operands, unknown
|
|
1357
|
+
* --known kkk op => [op], []
|
|
1358
|
+
* op --known kkk => [op], []
|
|
1359
|
+
* sub --unknown uuu op => [sub], [--unknown uuu op]
|
|
1360
|
+
* sub -- --unknown uuu op => [sub --unknown uuu op], []
|
|
1361
|
+
*
|
|
1362
|
+
* @param {String[]} argv
|
|
1363
|
+
* @return {{operands: String[], unknown: String[]}}
|
|
1364
|
+
*/
|
|
1365
|
+
parseOptions(argv) {
|
|
1366
|
+
const operands = [];
|
|
1367
|
+
const unknown = [];
|
|
1368
|
+
let dest = operands;
|
|
1369
|
+
const args = argv.slice();
|
|
1370
|
+
function maybeOption(arg) {
|
|
1371
|
+
return arg.length > 1 && arg[0] === "-";
|
|
1372
|
+
}
|
|
1373
|
+
let activeVariadicOption = null;
|
|
1374
|
+
while (args.length) {
|
|
1375
|
+
const arg = args.shift();
|
|
1376
|
+
if (arg === "--") {
|
|
1377
|
+
if (dest === unknown) dest.push(arg);
|
|
1378
|
+
dest.push(...args);
|
|
1379
|
+
break;
|
|
1380
|
+
}
|
|
1381
|
+
if (activeVariadicOption && !maybeOption(arg)) {
|
|
1382
|
+
this.emit(`option:${activeVariadicOption.name()}`, arg);
|
|
1383
|
+
continue;
|
|
1384
|
+
}
|
|
1385
|
+
activeVariadicOption = null;
|
|
1386
|
+
if (maybeOption(arg)) {
|
|
1387
|
+
const option = this._findOption(arg);
|
|
1388
|
+
if (option) {
|
|
1389
|
+
if (option.required) {
|
|
1390
|
+
const value = args.shift();
|
|
1391
|
+
if (value === void 0) this.optionMissingArgument(option);
|
|
1392
|
+
this.emit(`option:${option.name()}`, value);
|
|
1393
|
+
} else if (option.optional) {
|
|
1394
|
+
let value = null;
|
|
1395
|
+
if (args.length > 0 && !maybeOption(args[0])) {
|
|
1396
|
+
value = args.shift();
|
|
1397
|
+
}
|
|
1398
|
+
this.emit(`option:${option.name()}`, value);
|
|
1399
|
+
} else {
|
|
1400
|
+
this.emit(`option:${option.name()}`);
|
|
1401
|
+
}
|
|
1402
|
+
activeVariadicOption = option.variadic ? option : null;
|
|
1403
|
+
continue;
|
|
1404
|
+
}
|
|
1405
|
+
}
|
|
1406
|
+
if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
|
|
1407
|
+
const option = this._findOption(`-${arg[1]}`);
|
|
1408
|
+
if (option) {
|
|
1409
|
+
if (option.required || option.optional && this._combineFlagAndOptionalValue) {
|
|
1410
|
+
this.emit(`option:${option.name()}`, arg.slice(2));
|
|
1411
|
+
} else {
|
|
1412
|
+
this.emit(`option:${option.name()}`);
|
|
1413
|
+
args.unshift(`-${arg.slice(2)}`);
|
|
1414
|
+
}
|
|
1415
|
+
continue;
|
|
1416
|
+
}
|
|
1417
|
+
}
|
|
1418
|
+
if (/^--[^=]+=/.test(arg)) {
|
|
1419
|
+
const index = arg.indexOf("=");
|
|
1420
|
+
const option = this._findOption(arg.slice(0, index));
|
|
1421
|
+
if (option && (option.required || option.optional)) {
|
|
1422
|
+
this.emit(`option:${option.name()}`, arg.slice(index + 1));
|
|
1423
|
+
continue;
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
if (maybeOption(arg)) {
|
|
1427
|
+
dest = unknown;
|
|
1428
|
+
}
|
|
1429
|
+
if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
|
|
1430
|
+
if (this._findCommand(arg)) {
|
|
1431
|
+
operands.push(arg);
|
|
1432
|
+
if (args.length > 0) unknown.push(...args);
|
|
1433
|
+
break;
|
|
1434
|
+
} else if (arg === this._helpCommandName && this._hasImplicitHelpCommand()) {
|
|
1435
|
+
operands.push(arg);
|
|
1436
|
+
if (args.length > 0) operands.push(...args);
|
|
1437
|
+
break;
|
|
1438
|
+
} else if (this._defaultCommandName) {
|
|
1439
|
+
unknown.push(arg);
|
|
1440
|
+
if (args.length > 0) unknown.push(...args);
|
|
1441
|
+
break;
|
|
1442
|
+
}
|
|
1443
|
+
}
|
|
1444
|
+
if (this._passThroughOptions) {
|
|
1445
|
+
dest.push(arg);
|
|
1446
|
+
if (args.length > 0) dest.push(...args);
|
|
1447
|
+
break;
|
|
1448
|
+
}
|
|
1449
|
+
dest.push(arg);
|
|
1450
|
+
}
|
|
1451
|
+
return { operands, unknown };
|
|
1452
|
+
}
|
|
1453
|
+
/**
|
|
1454
|
+
* Return an object containing options as key-value pairs
|
|
1455
|
+
*
|
|
1456
|
+
* @return {Object}
|
|
1457
|
+
*/
|
|
1458
|
+
opts() {
|
|
1459
|
+
if (this._storeOptionsAsProperties) {
|
|
1460
|
+
const result = {};
|
|
1461
|
+
const len = this.options.length;
|
|
1462
|
+
for (let i = 0; i < len; i++) {
|
|
1463
|
+
const key = this.options[i].attributeName();
|
|
1464
|
+
result[key] = key === this._versionOptionName ? this._version : this[key];
|
|
1465
|
+
}
|
|
1466
|
+
return result;
|
|
1467
|
+
}
|
|
1468
|
+
return this._optionValues;
|
|
1469
|
+
}
|
|
1470
|
+
/**
|
|
1471
|
+
* Internal bottleneck for handling of parsing errors.
|
|
1472
|
+
*
|
|
1473
|
+
* @api private
|
|
1474
|
+
*/
|
|
1475
|
+
_displayError(exitCode, code, message) {
|
|
1476
|
+
this._outputConfiguration.outputError(`${message}
|
|
1477
|
+
`, this._outputConfiguration.writeErr);
|
|
1478
|
+
this._exit(exitCode, code, message);
|
|
1479
|
+
}
|
|
1480
|
+
/**
|
|
1481
|
+
* Argument `name` is missing.
|
|
1482
|
+
*
|
|
1483
|
+
* @param {string} name
|
|
1484
|
+
* @api private
|
|
1485
|
+
*/
|
|
1486
|
+
missingArgument(name2) {
|
|
1487
|
+
const message = `error: missing required argument '${name2}'`;
|
|
1488
|
+
this._displayError(1, "commander.missingArgument", message);
|
|
1489
|
+
}
|
|
1490
|
+
/**
|
|
1491
|
+
* `Option` is missing an argument.
|
|
1492
|
+
*
|
|
1493
|
+
* @param {Option} option
|
|
1494
|
+
* @api private
|
|
1495
|
+
*/
|
|
1496
|
+
optionMissingArgument(option) {
|
|
1497
|
+
const message = `error: option '${option.flags}' argument missing`;
|
|
1498
|
+
this._displayError(1, "commander.optionMissingArgument", message);
|
|
1499
|
+
}
|
|
1500
|
+
/**
|
|
1501
|
+
* `Option` does not have a value, and is a mandatory option.
|
|
1502
|
+
*
|
|
1503
|
+
* @param {Option} option
|
|
1504
|
+
* @api private
|
|
1505
|
+
*/
|
|
1506
|
+
missingMandatoryOptionValue(option) {
|
|
1507
|
+
const message = `error: required option '${option.flags}' not specified`;
|
|
1508
|
+
this._displayError(1, "commander.missingMandatoryOptionValue", message);
|
|
1509
|
+
}
|
|
1510
|
+
/**
|
|
1511
|
+
* Unknown option `flag`.
|
|
1512
|
+
*
|
|
1513
|
+
* @param {string} flag
|
|
1514
|
+
* @api private
|
|
1515
|
+
*/
|
|
1516
|
+
unknownOption(flag) {
|
|
1517
|
+
if (this._allowUnknownOption) return;
|
|
1518
|
+
const message = `error: unknown option '${flag}'`;
|
|
1519
|
+
this._displayError(1, "commander.unknownOption", message);
|
|
1520
|
+
}
|
|
1521
|
+
/**
|
|
1522
|
+
* Excess arguments, more than expected.
|
|
1523
|
+
*
|
|
1524
|
+
* @param {string[]} receivedArgs
|
|
1525
|
+
* @api private
|
|
1526
|
+
*/
|
|
1527
|
+
_excessArguments(receivedArgs) {
|
|
1528
|
+
if (this._allowExcessArguments) return;
|
|
1529
|
+
const expected = this._args.length;
|
|
1530
|
+
const s = expected === 1 ? "" : "s";
|
|
1531
|
+
const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
|
|
1532
|
+
const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
|
|
1533
|
+
this._displayError(1, "commander.excessArguments", message);
|
|
1534
|
+
}
|
|
1535
|
+
/**
|
|
1536
|
+
* Unknown command.
|
|
1537
|
+
*
|
|
1538
|
+
* @api private
|
|
1539
|
+
*/
|
|
1540
|
+
unknownCommand() {
|
|
1541
|
+
const partCommands = [this.name()];
|
|
1542
|
+
for (let parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) {
|
|
1543
|
+
partCommands.unshift(parentCmd.name());
|
|
1544
|
+
}
|
|
1545
|
+
const fullCommand = partCommands.join(" ");
|
|
1546
|
+
const message = `error: unknown command '${this.args[0]}'.` + (this._hasHelpOption ? ` See '${fullCommand} ${this._helpLongFlag}'.` : "");
|
|
1547
|
+
this._displayError(1, "commander.unknownCommand", message);
|
|
1548
|
+
}
|
|
1549
|
+
/**
|
|
1550
|
+
* Set the program version to `str`.
|
|
1551
|
+
*
|
|
1552
|
+
* This method auto-registers the "-V, --version" flag
|
|
1553
|
+
* which will print the version number when passed.
|
|
1554
|
+
*
|
|
1555
|
+
* You can optionally supply the flags and description to override the defaults.
|
|
1556
|
+
*
|
|
1557
|
+
* @param {string} str
|
|
1558
|
+
* @param {string} [flags]
|
|
1559
|
+
* @param {string} [description]
|
|
1560
|
+
* @return {this | string} `this` command for chaining, or version string if no arguments
|
|
1561
|
+
*/
|
|
1562
|
+
version(str, flags, description2) {
|
|
1563
|
+
if (str === void 0) return this._version;
|
|
1564
|
+
this._version = str;
|
|
1565
|
+
flags = flags || "-V, --version";
|
|
1566
|
+
description2 = description2 || "output the version number";
|
|
1567
|
+
const versionOption = this.createOption(flags, description2);
|
|
1568
|
+
this._versionOptionName = versionOption.attributeName();
|
|
1569
|
+
this.options.push(versionOption);
|
|
1570
|
+
this.on("option:" + versionOption.name(), () => {
|
|
1571
|
+
this._outputConfiguration.writeOut(`${str}
|
|
1572
|
+
`);
|
|
1573
|
+
this._exit(0, "commander.version", str);
|
|
1574
|
+
});
|
|
1575
|
+
return this;
|
|
1576
|
+
}
|
|
1577
|
+
/**
|
|
1578
|
+
* Set the description to `str`.
|
|
1579
|
+
*
|
|
1580
|
+
* @param {string} [str]
|
|
1581
|
+
* @param {Object} [argsDescription]
|
|
1582
|
+
* @return {string|Command}
|
|
1583
|
+
*/
|
|
1584
|
+
description(str, argsDescription) {
|
|
1585
|
+
if (str === void 0 && argsDescription === void 0) return this._description;
|
|
1586
|
+
this._description = str;
|
|
1587
|
+
this._argsDescription = argsDescription;
|
|
1588
|
+
return this;
|
|
1589
|
+
}
|
|
1590
|
+
/**
|
|
1591
|
+
* Set an alias for the command.
|
|
1592
|
+
*
|
|
1593
|
+
* You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
|
|
1594
|
+
*
|
|
1595
|
+
* @param {string} [alias]
|
|
1596
|
+
* @return {string|Command}
|
|
1597
|
+
*/
|
|
1598
|
+
alias(alias) {
|
|
1599
|
+
if (alias === void 0) return this._aliases[0];
|
|
1600
|
+
let command = this;
|
|
1601
|
+
if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
|
|
1602
|
+
command = this.commands[this.commands.length - 1];
|
|
1603
|
+
}
|
|
1604
|
+
if (alias === command._name) throw new Error("Command alias can't be the same as its name");
|
|
1605
|
+
command._aliases.push(alias);
|
|
1606
|
+
return this;
|
|
1607
|
+
}
|
|
1608
|
+
/**
|
|
1609
|
+
* Set aliases for the command.
|
|
1610
|
+
*
|
|
1611
|
+
* Only the first alias is shown in the auto-generated help.
|
|
1612
|
+
*
|
|
1613
|
+
* @param {string[]} [aliases]
|
|
1614
|
+
* @return {string[]|Command}
|
|
1615
|
+
*/
|
|
1616
|
+
aliases(aliases) {
|
|
1617
|
+
if (aliases === void 0) return this._aliases;
|
|
1618
|
+
aliases.forEach((alias) => this.alias(alias));
|
|
1619
|
+
return this;
|
|
1620
|
+
}
|
|
1621
|
+
/**
|
|
1622
|
+
* Set / get the command usage `str`.
|
|
1623
|
+
*
|
|
1624
|
+
* @param {string} [str]
|
|
1625
|
+
* @return {String|Command}
|
|
1626
|
+
*/
|
|
1627
|
+
usage(str) {
|
|
1628
|
+
if (str === void 0) {
|
|
1629
|
+
if (this._usage) return this._usage;
|
|
1630
|
+
const args = this._args.map((arg) => {
|
|
1631
|
+
return humanReadableArgName(arg);
|
|
1632
|
+
});
|
|
1633
|
+
return [].concat(
|
|
1634
|
+
this.options.length || this._hasHelpOption ? "[options]" : [],
|
|
1635
|
+
this.commands.length ? "[command]" : [],
|
|
1636
|
+
this._args.length ? args : []
|
|
1637
|
+
).join(" ");
|
|
1638
|
+
}
|
|
1639
|
+
this._usage = str;
|
|
1640
|
+
return this;
|
|
1641
|
+
}
|
|
1642
|
+
/**
|
|
1643
|
+
* Get or set the name of the command
|
|
1644
|
+
*
|
|
1645
|
+
* @param {string} [str]
|
|
1646
|
+
* @return {string|Command}
|
|
1647
|
+
*/
|
|
1648
|
+
name(str) {
|
|
1649
|
+
if (str === void 0) return this._name;
|
|
1650
|
+
this._name = str;
|
|
1651
|
+
return this;
|
|
1652
|
+
}
|
|
1653
|
+
/**
|
|
1654
|
+
* Return program help documentation.
|
|
1655
|
+
*
|
|
1656
|
+
* @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
|
|
1657
|
+
* @return {string}
|
|
1658
|
+
*/
|
|
1659
|
+
helpInformation(contextOptions) {
|
|
1660
|
+
const helper = this.createHelp();
|
|
1661
|
+
if (helper.helpWidth === void 0) {
|
|
1662
|
+
helper.helpWidth = contextOptions && contextOptions.error ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
|
|
1663
|
+
}
|
|
1664
|
+
return helper.formatHelp(this, helper);
|
|
1665
|
+
}
|
|
1666
|
+
/**
|
|
1667
|
+
* @api private
|
|
1668
|
+
*/
|
|
1669
|
+
_getHelpContext(contextOptions) {
|
|
1670
|
+
contextOptions = contextOptions || {};
|
|
1671
|
+
const context = { error: !!contextOptions.error };
|
|
1672
|
+
let write;
|
|
1673
|
+
if (context.error) {
|
|
1674
|
+
write = (arg) => this._outputConfiguration.writeErr(arg);
|
|
1675
|
+
} else {
|
|
1676
|
+
write = (arg) => this._outputConfiguration.writeOut(arg);
|
|
1677
|
+
}
|
|
1678
|
+
context.write = contextOptions.write || write;
|
|
1679
|
+
context.command = this;
|
|
1680
|
+
return context;
|
|
1681
|
+
}
|
|
1682
|
+
/**
|
|
1683
|
+
* Output help information for this command.
|
|
1684
|
+
*
|
|
1685
|
+
* Outputs built-in help, and custom text added using `.addHelpText()`.
|
|
1686
|
+
*
|
|
1687
|
+
* @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
|
|
1688
|
+
*/
|
|
1689
|
+
outputHelp(contextOptions) {
|
|
1690
|
+
let deprecatedCallback;
|
|
1691
|
+
if (typeof contextOptions === "function") {
|
|
1692
|
+
deprecatedCallback = contextOptions;
|
|
1693
|
+
contextOptions = void 0;
|
|
1694
|
+
}
|
|
1695
|
+
const context = this._getHelpContext(contextOptions);
|
|
1696
|
+
const groupListeners = [];
|
|
1697
|
+
let command = this;
|
|
1698
|
+
while (command) {
|
|
1699
|
+
groupListeners.push(command);
|
|
1700
|
+
command = command.parent;
|
|
1701
|
+
}
|
|
1702
|
+
groupListeners.slice().reverse().forEach((command2) => command2.emit("beforeAllHelp", context));
|
|
1703
|
+
this.emit("beforeHelp", context);
|
|
1704
|
+
let helpInformation = this.helpInformation(context);
|
|
1705
|
+
if (deprecatedCallback) {
|
|
1706
|
+
helpInformation = deprecatedCallback(helpInformation);
|
|
1707
|
+
if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
|
|
1708
|
+
throw new Error("outputHelp callback must return a string or a Buffer");
|
|
1709
|
+
}
|
|
1710
|
+
}
|
|
1711
|
+
context.write(helpInformation);
|
|
1712
|
+
this.emit(this._helpLongFlag);
|
|
1713
|
+
this.emit("afterHelp", context);
|
|
1714
|
+
groupListeners.forEach((command2) => command2.emit("afterAllHelp", context));
|
|
1715
|
+
}
|
|
1716
|
+
/**
|
|
1717
|
+
* You can pass in flags and a description to override the help
|
|
1718
|
+
* flags and help description for your command. Pass in false to
|
|
1719
|
+
* disable the built-in help option.
|
|
1720
|
+
*
|
|
1721
|
+
* @param {string | boolean} [flags]
|
|
1722
|
+
* @param {string} [description]
|
|
1723
|
+
* @return {Command} `this` command for chaining
|
|
1724
|
+
*/
|
|
1725
|
+
helpOption(flags, description2) {
|
|
1726
|
+
if (typeof flags === "boolean") {
|
|
1727
|
+
this._hasHelpOption = flags;
|
|
1728
|
+
return this;
|
|
1729
|
+
}
|
|
1730
|
+
this._helpFlags = flags || this._helpFlags;
|
|
1731
|
+
this._helpDescription = description2 || this._helpDescription;
|
|
1732
|
+
const helpFlags = _parseOptionFlags(this._helpFlags);
|
|
1733
|
+
this._helpShortFlag = helpFlags.shortFlag;
|
|
1734
|
+
this._helpLongFlag = helpFlags.longFlag;
|
|
1735
|
+
return this;
|
|
1736
|
+
}
|
|
1737
|
+
/**
|
|
1738
|
+
* Output help information and exit.
|
|
1739
|
+
*
|
|
1740
|
+
* Outputs built-in help, and custom text added using `.addHelpText()`.
|
|
1741
|
+
*
|
|
1742
|
+
* @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
|
|
1743
|
+
*/
|
|
1744
|
+
help(contextOptions) {
|
|
1745
|
+
this.outputHelp(contextOptions);
|
|
1746
|
+
let exitCode = process.exitCode || 0;
|
|
1747
|
+
if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
|
|
1748
|
+
exitCode = 1;
|
|
1749
|
+
}
|
|
1750
|
+
this._exit(exitCode, "commander.help", "(outputHelp)");
|
|
1751
|
+
}
|
|
1752
|
+
/**
|
|
1753
|
+
* Add additional text to be displayed with the built-in help.
|
|
1754
|
+
*
|
|
1755
|
+
* Position is 'before' or 'after' to affect just this command,
|
|
1756
|
+
* and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
|
|
1757
|
+
*
|
|
1758
|
+
* @param {string} position - before or after built-in help
|
|
1759
|
+
* @param {string | Function} text - string to add, or a function returning a string
|
|
1760
|
+
* @return {Command} `this` command for chaining
|
|
1761
|
+
*/
|
|
1762
|
+
addHelpText(position, text) {
|
|
1763
|
+
const allowedValues = ["beforeAll", "before", "after", "afterAll"];
|
|
1764
|
+
if (!allowedValues.includes(position)) {
|
|
1765
|
+
throw new Error(`Unexpected value for position to addHelpText.
|
|
1766
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
1767
|
+
}
|
|
1768
|
+
const helpEvent = `${position}Help`;
|
|
1769
|
+
this.on(helpEvent, (context) => {
|
|
1770
|
+
let helpStr;
|
|
1771
|
+
if (typeof text === "function") {
|
|
1772
|
+
helpStr = text({ error: context.error, command: context.command });
|
|
1773
|
+
} else {
|
|
1774
|
+
helpStr = text;
|
|
1775
|
+
}
|
|
1776
|
+
if (helpStr) {
|
|
1777
|
+
context.write(`${helpStr}
|
|
1778
|
+
`);
|
|
1779
|
+
}
|
|
1780
|
+
});
|
|
1781
|
+
return this;
|
|
1782
|
+
}
|
|
1783
|
+
};
|
|
1784
|
+
exports2 = module2.exports = new Command();
|
|
1785
|
+
exports2.program = exports2;
|
|
1786
|
+
exports2.Command = Command;
|
|
1787
|
+
exports2.Option = Option;
|
|
1788
|
+
exports2.CommanderError = CommanderError;
|
|
1789
|
+
exports2.InvalidOptionArgumentError = InvalidOptionArgumentError;
|
|
1790
|
+
exports2.Help = Help;
|
|
1791
|
+
function camelcase(flag) {
|
|
1792
|
+
return flag.split("-").reduce((str, word) => {
|
|
1793
|
+
return str + word[0].toUpperCase() + word.slice(1);
|
|
1794
|
+
});
|
|
1795
|
+
}
|
|
1796
|
+
function outputHelpIfRequested(cmd, args) {
|
|
1797
|
+
const helpOption = cmd._hasHelpOption && args.find((arg) => arg === cmd._helpLongFlag || arg === cmd._helpShortFlag);
|
|
1798
|
+
if (helpOption) {
|
|
1799
|
+
cmd.outputHelp();
|
|
1800
|
+
cmd._exit(0, "commander.helpDisplayed", "(outputHelp)");
|
|
1801
|
+
}
|
|
1802
|
+
}
|
|
1803
|
+
function humanReadableArgName(arg) {
|
|
1804
|
+
const nameOutput = arg.name + (arg.variadic === true ? "..." : "");
|
|
1805
|
+
return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
|
|
1806
|
+
}
|
|
1807
|
+
function _parseOptionFlags(flags) {
|
|
1808
|
+
let shortFlag;
|
|
1809
|
+
let longFlag;
|
|
1810
|
+
const flagParts = flags.split(/[ |,]+/);
|
|
1811
|
+
if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1])) shortFlag = flagParts.shift();
|
|
1812
|
+
longFlag = flagParts.shift();
|
|
1813
|
+
if (!shortFlag && /^-[^-]$/.test(longFlag)) {
|
|
1814
|
+
shortFlag = longFlag;
|
|
1815
|
+
longFlag = void 0;
|
|
1816
|
+
}
|
|
1817
|
+
return { shortFlag, longFlag };
|
|
1818
|
+
}
|
|
1819
|
+
function incrementNodeInspectorPort(args) {
|
|
1820
|
+
return args.map((arg) => {
|
|
1821
|
+
if (!arg.startsWith("--inspect")) {
|
|
1822
|
+
return arg;
|
|
1823
|
+
}
|
|
1824
|
+
let debugOption;
|
|
1825
|
+
let debugHost = "127.0.0.1";
|
|
1826
|
+
let debugPort = "9229";
|
|
1827
|
+
let match;
|
|
1828
|
+
if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
|
|
1829
|
+
debugOption = match[1];
|
|
1830
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
|
|
1831
|
+
debugOption = match[1];
|
|
1832
|
+
if (/^\d+$/.test(match[3])) {
|
|
1833
|
+
debugPort = match[3];
|
|
1834
|
+
} else {
|
|
1835
|
+
debugHost = match[3];
|
|
1836
|
+
}
|
|
1837
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
|
|
1838
|
+
debugOption = match[1];
|
|
1839
|
+
debugHost = match[3];
|
|
1840
|
+
debugPort = match[4];
|
|
1841
|
+
}
|
|
1842
|
+
if (debugOption && debugPort !== "0") {
|
|
1843
|
+
return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
|
|
1844
|
+
}
|
|
1845
|
+
return arg;
|
|
1846
|
+
});
|
|
1847
|
+
}
|
|
1848
|
+
}
|
|
1849
|
+
});
|
|
1850
|
+
|
|
1851
|
+
// src/index.ts
|
|
1852
|
+
var import_path4 = __toESM(require("path"));
|
|
1853
|
+
var import_commander = __toESM(require_commander());
|
|
1854
|
+
|
|
1855
|
+
// package.json
|
|
1856
|
+
var name = "@mantou/gem-port";
|
|
1857
|
+
var version = "1.0.0-alpha.0";
|
|
1858
|
+
var description = "Export React component";
|
|
1859
|
+
|
|
1860
|
+
// src/common.ts
|
|
1861
|
+
var import_path = __toESM(require("path"));
|
|
1862
|
+
var import_fs = require("fs");
|
|
1863
|
+
|
|
1864
|
+
// ../gem/lib/utils.js
|
|
1865
|
+
function camelToKebabCase(str) {
|
|
1866
|
+
return str.replace(/[A-Z]/g, ($1) => "-" + $1.toLowerCase());
|
|
1867
|
+
}
|
|
1868
|
+
|
|
1869
|
+
// ../gem-analyzer/lib/utils.js
|
|
1870
|
+
function getJsDoc(declaration) {
|
|
1871
|
+
if ("getJsDocs" in declaration) {
|
|
1872
|
+
const jsDocs = declaration.getJsDocs();
|
|
1873
|
+
const deprecated = jsDocs.map((jsDoc) => jsDoc.getTags()).flat().some((e) => e.getTagName() === "deprecated");
|
|
1874
|
+
const comment = jsDocs.map((jsDoc) => jsDoc.getCommentText()).join("\n\n");
|
|
1875
|
+
return {
|
|
1876
|
+
deprecated,
|
|
1877
|
+
description: `${deprecated ? "@deprecated " : ""}${comment || ""}`
|
|
1878
|
+
};
|
|
1879
|
+
}
|
|
1880
|
+
}
|
|
1881
|
+
function getTypeText(declaration) {
|
|
1882
|
+
const structure = declaration.getStructure();
|
|
1883
|
+
return "type" in structure && typeof structure.type === "string" && structure.type || declaration.getType().getText();
|
|
1884
|
+
}
|
|
1885
|
+
function isGetter(declaration, kind = "get") {
|
|
1886
|
+
const first = declaration.getFirstChild();
|
|
1887
|
+
const firstText = first?.getText();
|
|
1888
|
+
return (firstText === "static" ? first?.getNextSibling()?.getText() : firstText) === kind;
|
|
1889
|
+
}
|
|
1890
|
+
function isSetter(declaration) {
|
|
1891
|
+
return isGetter(declaration, "set");
|
|
1892
|
+
}
|
|
1893
|
+
|
|
1894
|
+
// ../gem-analyzer/index.js
|
|
1895
|
+
var shadowDecoratorName = ["shadow"];
|
|
1896
|
+
var elementDecoratorName = ["customElement"];
|
|
1897
|
+
var attrDecoratorName = ["attribute", "boolattribute", "numattribute"];
|
|
1898
|
+
var propDecoratorName = ["property"];
|
|
1899
|
+
var stateDecoratorName = ["state"];
|
|
1900
|
+
var slotDecoratorName = ["slot"];
|
|
1901
|
+
var partDecoratorName = ["part"];
|
|
1902
|
+
var refDecoratorName = ["refobject"];
|
|
1903
|
+
var eventDecoratorName = ["emitter", "globalemitter"];
|
|
1904
|
+
var globalEventDecoratorName = ["globalemitter"];
|
|
1905
|
+
var lifecyclePopsOrMethods = ["state", "willMount", "render", "mounted", "shouldUpdate", "updated", "unmounted"];
|
|
1906
|
+
async function getExtendsClassDetail(className, sourceFile, project2) {
|
|
1907
|
+
if (className === "GemElement")
|
|
1908
|
+
return;
|
|
1909
|
+
const currentFile = sourceFile.getFilePath();
|
|
1910
|
+
const isAbsFilePath = currentFile.startsWith("/");
|
|
1911
|
+
if (!isAbsFilePath || !project2)
|
|
1912
|
+
return;
|
|
1913
|
+
const fileSystem = project2.getFileSystem();
|
|
1914
|
+
const importDeclaration = sourceFile.getImportDeclaration((desc) => !!desc.getNamedImports().map((e) => e.getText()).find((e) => e.includes(className)));
|
|
1915
|
+
if (!importDeclaration)
|
|
1916
|
+
return;
|
|
1917
|
+
const depPath = importDeclaration.getModuleSpecifierValue();
|
|
1918
|
+
if (!depPath.startsWith("."))
|
|
1919
|
+
return;
|
|
1920
|
+
const { pathname } = new URL(`${depPath}.ts`, `gem:${currentFile}`);
|
|
1921
|
+
if (project2.getSourceFile(pathname))
|
|
1922
|
+
return;
|
|
1923
|
+
project2.createSourceFile(pathname, "");
|
|
1924
|
+
try {
|
|
1925
|
+
const text = await fileSystem.readFile(pathname);
|
|
1926
|
+
const file = project2.createSourceFile(pathname, text, { overwrite: true });
|
|
1927
|
+
const classDeclaration = file.getClass(className);
|
|
1928
|
+
if (!classDeclaration)
|
|
1929
|
+
return;
|
|
1930
|
+
const detail = await parseElement(classDeclaration, file, project2);
|
|
1931
|
+
detail.relativePath = depPath;
|
|
1932
|
+
return detail;
|
|
1933
|
+
} catch {
|
|
1934
|
+
return;
|
|
1935
|
+
}
|
|
1936
|
+
}
|
|
1937
|
+
var parseElement = async (declaration, file, project2) => {
|
|
1938
|
+
const detail = {
|
|
1939
|
+
name: "",
|
|
1940
|
+
shadow: false,
|
|
1941
|
+
constructorName: "",
|
|
1942
|
+
constructorExtendsName: "",
|
|
1943
|
+
constructorParams: [],
|
|
1944
|
+
staticProperties: [],
|
|
1945
|
+
staticMethods: [],
|
|
1946
|
+
properties: [],
|
|
1947
|
+
methods: [],
|
|
1948
|
+
attributes: [],
|
|
1949
|
+
cssStates: [],
|
|
1950
|
+
events: [],
|
|
1951
|
+
parts: [],
|
|
1952
|
+
slots: []
|
|
1953
|
+
};
|
|
1954
|
+
const className = declaration.getName();
|
|
1955
|
+
const constructorExtendsName = declaration.getExtends()?.getText();
|
|
1956
|
+
const constructor = declaration.getConstructors()[0];
|
|
1957
|
+
const appendElementDesc = (desc = "") => detail.description = (detail.description ? detail.description + "\n\n" : "") + desc;
|
|
1958
|
+
declaration.getJsDocs().forEach((jsDoc) => appendElementDesc(jsDoc.getCommentText()));
|
|
1959
|
+
if (className && constructorExtendsName) {
|
|
1960
|
+
detail.extend = await getExtendsClassDetail(constructorExtendsName, file, project2);
|
|
1961
|
+
detail.constructorName = className;
|
|
1962
|
+
detail.constructorExtendsName = constructorExtendsName;
|
|
1963
|
+
if (constructor) {
|
|
1964
|
+
const params = {};
|
|
1965
|
+
const jsDocs = constructor.getJsDocs();
|
|
1966
|
+
jsDocs.forEach((jsDoc) => {
|
|
1967
|
+
appendElementDesc(jsDoc.getDescription());
|
|
1968
|
+
jsDoc.getTags().map((tag) => ({ tagName: tag.getTagName(), name: tag.getName(), comment: tag.getCommentText() })).filter(({ tagName, comment, name: name2 }) => tagName === "param" && comment && name2).forEach(({ name: name2, comment }) => {
|
|
1969
|
+
params[name2] = comment;
|
|
1970
|
+
});
|
|
1971
|
+
});
|
|
1972
|
+
detail.constructorParams = constructor.getParameters().map((param) => ({
|
|
1973
|
+
name: param.getName(),
|
|
1974
|
+
type: getTypeText(param),
|
|
1975
|
+
description: params[param.getName()]
|
|
1976
|
+
}));
|
|
1977
|
+
}
|
|
1978
|
+
}
|
|
1979
|
+
const staticPropertiesDeclarations = declaration.getStaticProperties();
|
|
1980
|
+
for (const staticPropDeclaration of staticPropertiesDeclarations) {
|
|
1981
|
+
const staticPropName = staticPropDeclaration.getName();
|
|
1982
|
+
if (staticPropName.startsWith("#"))
|
|
1983
|
+
continue;
|
|
1984
|
+
const prop = {
|
|
1985
|
+
name: staticPropName,
|
|
1986
|
+
type: staticPropDeclaration.getType().getText(),
|
|
1987
|
+
getter: isGetter(staticPropDeclaration),
|
|
1988
|
+
setter: isSetter(staticPropDeclaration),
|
|
1989
|
+
...getJsDoc(staticPropDeclaration)
|
|
1990
|
+
};
|
|
1991
|
+
let isPartOrSlot = false;
|
|
1992
|
+
const staticPropDecorators = staticPropDeclaration.getDecorators();
|
|
1993
|
+
for (const decorator of staticPropDecorators) {
|
|
1994
|
+
const decoratorName = decorator.getName();
|
|
1995
|
+
if (slotDecoratorName.includes(decoratorName)) {
|
|
1996
|
+
isPartOrSlot = true;
|
|
1997
|
+
prop.slot = camelToKebabCase(staticPropName);
|
|
1998
|
+
detail.slots.push(prop.slot);
|
|
1999
|
+
} else if (partDecoratorName.includes(decoratorName)) {
|
|
2000
|
+
isPartOrSlot = true;
|
|
2001
|
+
prop.part = camelToKebabCase(staticPropName);
|
|
2002
|
+
detail.parts.push(prop.part);
|
|
2003
|
+
}
|
|
2004
|
+
}
|
|
2005
|
+
if (!isPartOrSlot) {
|
|
2006
|
+
detail.staticProperties.push(prop);
|
|
2007
|
+
}
|
|
2008
|
+
}
|
|
2009
|
+
const staticMethodDeclarations = declaration.getStaticMethods();
|
|
2010
|
+
for (const staticMethodDeclaration of staticMethodDeclarations) {
|
|
2011
|
+
const staticMethodName = staticMethodDeclaration.getName();
|
|
2012
|
+
if (staticMethodName.startsWith("#"))
|
|
2013
|
+
continue;
|
|
2014
|
+
const method = {
|
|
2015
|
+
name: staticMethodName,
|
|
2016
|
+
type: staticMethodDeclaration.getType().getText(),
|
|
2017
|
+
...getJsDoc(staticMethodDeclaration)
|
|
2018
|
+
};
|
|
2019
|
+
detail.staticMethods.push(method);
|
|
2020
|
+
}
|
|
2021
|
+
const propDeclarations = declaration.getInstanceProperties();
|
|
2022
|
+
for (const propDeclaration of propDeclarations) {
|
|
2023
|
+
const propName = propDeclaration.getName();
|
|
2024
|
+
if (propName.startsWith("#"))
|
|
2025
|
+
continue;
|
|
2026
|
+
if (lifecyclePopsOrMethods.includes(propName))
|
|
2027
|
+
continue;
|
|
2028
|
+
const prop = {
|
|
2029
|
+
name: propName,
|
|
2030
|
+
reactive: false,
|
|
2031
|
+
type: getTypeText(propDeclaration),
|
|
2032
|
+
getter: isGetter(propDeclaration),
|
|
2033
|
+
setter: isSetter(propDeclaration),
|
|
2034
|
+
...getJsDoc(propDeclaration)
|
|
2035
|
+
};
|
|
2036
|
+
detail.properties.push(prop);
|
|
2037
|
+
const propDecorators = propDeclaration.getDecorators();
|
|
2038
|
+
for (const decorator of propDecorators) {
|
|
2039
|
+
const decoratorName = decorator.getName();
|
|
2040
|
+
if (attrDecoratorName.includes(decoratorName)) {
|
|
2041
|
+
prop.reactive = true;
|
|
2042
|
+
prop.attribute = camelToKebabCase(propName);
|
|
2043
|
+
detail.attributes.push(prop.attribute);
|
|
2044
|
+
} else if (propDecoratorName.includes(decoratorName)) {
|
|
2045
|
+
prop.reactive = true;
|
|
2046
|
+
} else if (stateDecoratorName.includes(decoratorName)) {
|
|
2047
|
+
prop.cssState = camelToKebabCase(propName);
|
|
2048
|
+
detail.cssStates.push(prop.cssState);
|
|
2049
|
+
} else if (slotDecoratorName.includes(decoratorName)) {
|
|
2050
|
+
prop.slot = camelToKebabCase(propName);
|
|
2051
|
+
detail.slots.push(prop.slot);
|
|
2052
|
+
} else if (partDecoratorName.includes(decoratorName)) {
|
|
2053
|
+
prop.part = camelToKebabCase(propName);
|
|
2054
|
+
detail.parts.push(prop.part);
|
|
2055
|
+
} else if (refDecoratorName.includes(decoratorName)) {
|
|
2056
|
+
prop.isRef = true;
|
|
2057
|
+
} else if (eventDecoratorName.includes(decoratorName)) {
|
|
2058
|
+
prop.event = camelToKebabCase(propName);
|
|
2059
|
+
detail.events.push(prop.event);
|
|
2060
|
+
}
|
|
2061
|
+
if (globalEventDecoratorName.includes(decoratorName)) {
|
|
2062
|
+
prop.isGlobalEvent = true;
|
|
2063
|
+
}
|
|
2064
|
+
}
|
|
2065
|
+
}
|
|
2066
|
+
const methodDeclarations = declaration.getInstanceMethods();
|
|
2067
|
+
for (const methodDeclaration of methodDeclarations) {
|
|
2068
|
+
const methodName = methodDeclaration.getName();
|
|
2069
|
+
if (methodName.startsWith("#"))
|
|
2070
|
+
continue;
|
|
2071
|
+
if (lifecyclePopsOrMethods.includes(methodName))
|
|
2072
|
+
continue;
|
|
2073
|
+
const method = {
|
|
2074
|
+
name: methodName,
|
|
2075
|
+
type: getTypeText(methodDeclaration),
|
|
2076
|
+
...getJsDoc(methodDeclaration)
|
|
2077
|
+
};
|
|
2078
|
+
detail.methods.push(method);
|
|
2079
|
+
const methodDecorators = methodDeclaration.getDecorators();
|
|
2080
|
+
for (const decorator of methodDecorators) {
|
|
2081
|
+
const decoratorName = decorator.getName();
|
|
2082
|
+
if (eventDecoratorName.includes(decoratorName)) {
|
|
2083
|
+
method.event = camelToKebabCase(methodName);
|
|
2084
|
+
detail.events.push(method.event);
|
|
2085
|
+
}
|
|
2086
|
+
if (globalEventDecoratorName.includes(decoratorName)) {
|
|
2087
|
+
method.isGlobalEvent = true;
|
|
2088
|
+
}
|
|
2089
|
+
}
|
|
2090
|
+
}
|
|
2091
|
+
const elementDecorators = declaration.getDecorators();
|
|
2092
|
+
const shadowDeclaration = elementDecorators.find((decorator) => shadowDecoratorName.includes(decorator.getName()));
|
|
2093
|
+
if (shadowDeclaration) {
|
|
2094
|
+
detail.shadow = true;
|
|
2095
|
+
}
|
|
2096
|
+
return detail;
|
|
2097
|
+
};
|
|
2098
|
+
var getElements = async (file, project2) => {
|
|
2099
|
+
const result = [];
|
|
2100
|
+
for (const declaration of file.getClasses()) {
|
|
2101
|
+
const elementDecorators = declaration.getDecorators();
|
|
2102
|
+
const elementDeclaration = elementDecorators.find((decorator) => elementDecoratorName.includes(decorator.getName()));
|
|
2103
|
+
const elementTag = elementDeclaration?.getCallExpression().getArguments()[0].getText().replace(/('|"|`)?(\S*)\1/, "$2") || declaration.getJsDocs().map((jsDoc) => jsDoc.getTags()).flat().find((e) => e.getTagName() === "customElement")?.getCommentText();
|
|
2104
|
+
if (elementTag) {
|
|
2105
|
+
const detail = {
|
|
2106
|
+
...await parseElement(declaration, file, project2),
|
|
2107
|
+
name: elementTag
|
|
2108
|
+
};
|
|
2109
|
+
if (!detail.constructorName.startsWith("_")) {
|
|
2110
|
+
result.push(detail);
|
|
2111
|
+
}
|
|
2112
|
+
}
|
|
2113
|
+
}
|
|
2114
|
+
return result;
|
|
2115
|
+
};
|
|
2116
|
+
|
|
2117
|
+
// src/common.ts
|
|
2118
|
+
var import_ts_morph = require("ts-morph");
|
|
2119
|
+
var ts = __toESM(require("typescript"));
|
|
2120
|
+
var dev = process.env.MODE === "dev";
|
|
2121
|
+
var elements = process.env.ELEMENTS?.split(",");
|
|
2122
|
+
function getElementPathList(elementsDir) {
|
|
2123
|
+
const paths = (0, import_fs.readdirSync)(elementsDir).map((filename) => import_path.default.resolve(elementsDir, filename)).filter((elementFilePath, index) => {
|
|
2124
|
+
if (!(0, import_fs.statSync)(elementFilePath).isFile()) return false;
|
|
2125
|
+
if (elements) {
|
|
2126
|
+
return elements?.some((ele) => elementFilePath.includes(ele));
|
|
2127
|
+
} else if (dev) {
|
|
2128
|
+
return index < 2;
|
|
2129
|
+
}
|
|
2130
|
+
return true;
|
|
2131
|
+
});
|
|
2132
|
+
if (dev) {
|
|
2133
|
+
console.log("Compile files:", paths);
|
|
2134
|
+
}
|
|
2135
|
+
return paths;
|
|
2136
|
+
}
|
|
2137
|
+
var getChain = (detail) => {
|
|
2138
|
+
let root = detail;
|
|
2139
|
+
const result = [root];
|
|
2140
|
+
while (root.extend) {
|
|
2141
|
+
root = root.extend;
|
|
2142
|
+
result.push(root);
|
|
2143
|
+
}
|
|
2144
|
+
return result;
|
|
2145
|
+
};
|
|
2146
|
+
var mergeElementDetail = (elementFilePath, detail) => {
|
|
2147
|
+
const chain = getChain(detail);
|
|
2148
|
+
return {
|
|
2149
|
+
...detail,
|
|
2150
|
+
properties: chain.map((e) => e.properties).flat(),
|
|
2151
|
+
methods: chain.map((e) => e.methods).flat(),
|
|
2152
|
+
events: chain.map((e) => e.events).flat()
|
|
2153
|
+
};
|
|
2154
|
+
};
|
|
2155
|
+
var elementCache = {};
|
|
2156
|
+
var project = new import_ts_morph.Project({
|
|
2157
|
+
useInMemoryFileSystem: true,
|
|
2158
|
+
compilerOptions: { target: import_ts_morph.ts.ScriptTarget.ESNext }
|
|
2159
|
+
});
|
|
2160
|
+
project.getFileSystem().readFile = (filePath) => import_fs.promises.readFile(filePath, "utf8");
|
|
2161
|
+
async function getFileElements(elementFilePath) {
|
|
2162
|
+
if (!elementCache[elementFilePath]) {
|
|
2163
|
+
const text = (0, import_fs.readFileSync)(elementFilePath, { encoding: "utf-8" });
|
|
2164
|
+
const file = project.getSourceFile(elementFilePath) || project.createSourceFile(elementFilePath, text);
|
|
2165
|
+
const details = await getElements(file, project);
|
|
2166
|
+
elementCache[elementFilePath] = details.map((detail) => mergeElementDetail(elementFilePath, detail));
|
|
2167
|
+
}
|
|
2168
|
+
return elementCache[elementFilePath];
|
|
2169
|
+
}
|
|
2170
|
+
function getComponentName(tag) {
|
|
2171
|
+
return tag.replace(/(^|-)(\w)/g, (_, __, $1) => $1.toUpperCase());
|
|
2172
|
+
}
|
|
2173
|
+
function getJsDocDescName(name2, deprecated) {
|
|
2174
|
+
return `${deprecated ? "/**@deprecated */\n" : ""}${name2}`;
|
|
2175
|
+
}
|
|
2176
|
+
function getRelativePath(elementFilePath, outDir) {
|
|
2177
|
+
const basename = import_path.default.basename(elementFilePath, import_path.default.extname(elementFilePath));
|
|
2178
|
+
const relativePath = import_path.default.relative(import_path.default.resolve(outDir), import_path.default.dirname(elementFilePath)).replace("src/", "");
|
|
2179
|
+
return `${relativePath}/${basename}`;
|
|
2180
|
+
}
|
|
2181
|
+
function compile(outDir, fileSystem) {
|
|
2182
|
+
const options = {
|
|
2183
|
+
jsx: ts.JsxEmit.React,
|
|
2184
|
+
target: ts.ScriptTarget.ES2020,
|
|
2185
|
+
declaration: true,
|
|
2186
|
+
outDir
|
|
2187
|
+
};
|
|
2188
|
+
const host = ts.createCompilerHost(options);
|
|
2189
|
+
const originReadFile = host.readFile;
|
|
2190
|
+
host.readFile = (filename) => {
|
|
2191
|
+
if (filename in fileSystem) return fileSystem[filename];
|
|
2192
|
+
return originReadFile(filename);
|
|
2193
|
+
};
|
|
2194
|
+
const program2 = ts.createProgram(Object.keys(fileSystem), options, host);
|
|
2195
|
+
program2.emit().diagnostics.forEach((diagnostic) => {
|
|
2196
|
+
if (diagnostic.file) {
|
|
2197
|
+
const { line, character } = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start);
|
|
2198
|
+
const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n");
|
|
2199
|
+
console.warn(`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`);
|
|
2200
|
+
} else {
|
|
2201
|
+
console.warn(ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"));
|
|
2202
|
+
}
|
|
2203
|
+
});
|
|
2204
|
+
}
|
|
2205
|
+
|
|
2206
|
+
// src/react.ts
|
|
2207
|
+
async function createReactSourceFile(elementFilePath, outDir) {
|
|
2208
|
+
const elementDetailList = await getFileElements(elementFilePath);
|
|
2209
|
+
return Object.fromEntries(
|
|
2210
|
+
elementDetailList.map(({ name: tag, constructorName, properties, methods }) => {
|
|
2211
|
+
const componentName = getComponentName(tag);
|
|
2212
|
+
const componentPropsName = `${componentName}Props`;
|
|
2213
|
+
const componentExposeName = `${componentName}Expose`;
|
|
2214
|
+
const relativePath = getRelativePath(elementFilePath, outDir);
|
|
2215
|
+
const getters = properties.filter((e) => e.getter);
|
|
2216
|
+
const settableProperties = properties.filter((e) => !e.getter && !e.event);
|
|
2217
|
+
return [
|
|
2218
|
+
componentName + ".tsx",
|
|
2219
|
+
`
|
|
2220
|
+
import React, { HTMLAttributes, RefAttributes } from 'react';
|
|
2221
|
+
import React, { ForwardRefExoticComponent, forwardRef, useImperativeHandle, useRef, useLayoutEffect } from 'react';
|
|
2222
|
+
import { ${constructorName} } from '${relativePath}';
|
|
2223
|
+
export * from '${relativePath}';
|
|
2224
|
+
|
|
2225
|
+
export type ${componentPropsName} = HTMLAttributes<HTMLDivElement> & RefAttributes<${constructorName}> & {
|
|
2226
|
+
${properties.map(
|
|
2227
|
+
({ name: name2, getter, event, deprecated }) => event ? [
|
|
2228
|
+
getJsDocDescName(`'on${event}'`, deprecated),
|
|
2229
|
+
`(event: CustomEvent<Parameters<${constructorName}['${name2}']>[0]>) => void`
|
|
2230
|
+
].join("?:") : !getter ? [getJsDocDescName(name2, deprecated), `${constructorName}['${name2}']`].join("?:") : ""
|
|
2231
|
+
).join(";\n")}
|
|
2232
|
+
};
|
|
2233
|
+
|
|
2234
|
+
export type ${componentExposeName} = {
|
|
2235
|
+
${[...methods, ...getters].map(
|
|
2236
|
+
({ name: name2, deprecated }) => [getJsDocDescName(name2, deprecated), `${constructorName}['${name2}']`].join(": ")
|
|
2237
|
+
).join(";\n")}
|
|
2238
|
+
}
|
|
2239
|
+
|
|
2240
|
+
declare global {
|
|
2241
|
+
namespace JSX {
|
|
2242
|
+
interface IntrinsicElements {
|
|
2243
|
+
'${tag}': ${componentPropsName};
|
|
2244
|
+
}
|
|
2245
|
+
}
|
|
2246
|
+
}
|
|
2247
|
+
|
|
2248
|
+
export const ${componentName}: ForwardRefExoticComponent<Omit<${componentPropsName}, "ref"> & RefAttributes<${componentExposeName}>> = forwardRef<${componentExposeName}, ${componentPropsName}>(function (props, ref): JSX.Element {
|
|
2249
|
+
const elementRef = useRef<${constructorName}>(null);
|
|
2250
|
+
useImperativeHandle(ref, () => {
|
|
2251
|
+
return {
|
|
2252
|
+
${methods.map(
|
|
2253
|
+
({ name: name2 }) => `
|
|
2254
|
+
${name2}(...args) {
|
|
2255
|
+
return elementRef.current!.${name2}(...args)
|
|
2256
|
+
},
|
|
2257
|
+
`
|
|
2258
|
+
).join("")}
|
|
2259
|
+
${getters.map(
|
|
2260
|
+
({ name: name2 }) => `
|
|
2261
|
+
get ${name2}() {
|
|
2262
|
+
return elementRef.current!.${name2}
|
|
2263
|
+
},
|
|
2264
|
+
`
|
|
2265
|
+
).join("")}
|
|
2266
|
+
};
|
|
2267
|
+
}, []);
|
|
2268
|
+
|
|
2269
|
+
// React Bug?
|
|
2270
|
+
useLayoutEffect(() => {
|
|
2271
|
+
const element = elementRef.current!;
|
|
2272
|
+
${JSON.stringify(settableProperties.map(({ name: name2 }) => name2))}.map(name => {
|
|
2273
|
+
element[name] = props[name];
|
|
2274
|
+
})
|
|
2275
|
+
}, [])
|
|
2276
|
+
|
|
2277
|
+
return <${tag} ref={elementRef} {...props}></${tag}>;
|
|
2278
|
+
})
|
|
2279
|
+
|
|
2280
|
+
export default ${componentName};
|
|
2281
|
+
`
|
|
2282
|
+
];
|
|
2283
|
+
})
|
|
2284
|
+
);
|
|
2285
|
+
}
|
|
2286
|
+
async function compileReact(elementsDir, outDir) {
|
|
2287
|
+
const fileSystem = {};
|
|
2288
|
+
const processFile = async (elementFilePath) => {
|
|
2289
|
+
Object.assign(fileSystem, await createReactSourceFile(elementFilePath, outDir));
|
|
2290
|
+
};
|
|
2291
|
+
await Promise.all(getElementPathList(elementsDir).map(processFile));
|
|
2292
|
+
compile(outDir, fileSystem);
|
|
2293
|
+
}
|
|
2294
|
+
|
|
2295
|
+
// src/vue.ts
|
|
2296
|
+
var import_fs2 = require("fs");
|
|
2297
|
+
var import_path2 = require("path");
|
|
2298
|
+
async function generateVue(elementsDir, outDir) {
|
|
2299
|
+
(0, import_fs2.mkdirSync)(outDir, { recursive: true });
|
|
2300
|
+
const processFile = async (elementFilePath) => {
|
|
2301
|
+
const elements2 = await getFileElements(elementFilePath);
|
|
2302
|
+
elements2.forEach(({ name: tag, properties, constructorName, methods, events }) => {
|
|
2303
|
+
const componentName = getComponentName(tag);
|
|
2304
|
+
const componentExposeName = `${componentName}Expose`;
|
|
2305
|
+
const relativePath = getRelativePath(elementFilePath, outDir);
|
|
2306
|
+
const settableProperties = properties.filter((e) => !e.getter && !e.event);
|
|
2307
|
+
const getters = properties.filter((e) => e.getter);
|
|
2308
|
+
(0, import_fs2.writeFileSync)(
|
|
2309
|
+
(0, import_path2.resolve)(outDir, componentName + ".vue"),
|
|
2310
|
+
`
|
|
2311
|
+
<script setup lang="ts">
|
|
2312
|
+
import { ref, defineProps, defineEmits, defineExpose, onMounted } from 'vue'
|
|
2313
|
+
import { ${constructorName} } from '${relativePath}';
|
|
2314
|
+
|
|
2315
|
+
const elementRef = ref<${constructorName}>();
|
|
2316
|
+
|
|
2317
|
+
const props = defineProps<{
|
|
2318
|
+
${settableProperties.map(
|
|
2319
|
+
({ name: name2, deprecated }) => [getJsDocDescName(name2, deprecated), `${constructorName}['${name2}']`].join("?: ")
|
|
2320
|
+
).join(",\n")}
|
|
2321
|
+
}>();
|
|
2322
|
+
|
|
2323
|
+
const emit = defineEmits<{
|
|
2324
|
+
${properties.filter(({ event }) => !!event).map(
|
|
2325
|
+
({ name: name2, deprecated }) => [
|
|
2326
|
+
getJsDocDescName(name2, deprecated),
|
|
2327
|
+
`[event: CustomEvent<Parameters<${constructorName}['${name2}']>[0]>]`
|
|
2328
|
+
].join(": ")
|
|
2329
|
+
).join(",\n")}
|
|
2330
|
+
}>()
|
|
2331
|
+
|
|
2332
|
+
type ${componentExposeName} = {
|
|
2333
|
+
${[...methods, ...getters].map(
|
|
2334
|
+
({ name: name2, deprecated }) => [getJsDocDescName(name2, deprecated), `${constructorName}['${name2}']`].join(": ")
|
|
2335
|
+
).join(";\n")}
|
|
2336
|
+
}
|
|
2337
|
+
|
|
2338
|
+
defineExpose<${componentExposeName}>({
|
|
2339
|
+
${methods.map(
|
|
2340
|
+
({ name: name2 }) => `
|
|
2341
|
+
${name2}(...args) {
|
|
2342
|
+
return elementRef.value!.${name2}(...args)
|
|
2343
|
+
},
|
|
2344
|
+
`
|
|
2345
|
+
).join("")}
|
|
2346
|
+
${getters.map(
|
|
2347
|
+
({ name: name2 }) => `
|
|
2348
|
+
get ${name2}() {
|
|
2349
|
+
return elementRef.value!.${name2}
|
|
2350
|
+
},
|
|
2351
|
+
`
|
|
2352
|
+
).join("")}
|
|
2353
|
+
})
|
|
2354
|
+
|
|
2355
|
+
</script>
|
|
2356
|
+
|
|
2357
|
+
<script lang="ts">
|
|
2358
|
+
export * from '${relativePath}';
|
|
2359
|
+
export default {
|
|
2360
|
+
name: '${componentName}',
|
|
2361
|
+
};
|
|
2362
|
+
</script>
|
|
2363
|
+
|
|
2364
|
+
<template>
|
|
2365
|
+
<${tag}
|
|
2366
|
+
ref="elementRef"
|
|
2367
|
+
${settableProperties.map(({ name: name2 }) => `.${name2}="props.${name2}"`).join(" ")}
|
|
2368
|
+
${events.map((event) => [`@${event}`, `"e => emit('${event}', e)"`].join("=")).join(" ")}>
|
|
2369
|
+
<slot />
|
|
2370
|
+
</${tag}>
|
|
2371
|
+
</template>
|
|
2372
|
+
`
|
|
2373
|
+
);
|
|
2374
|
+
});
|
|
2375
|
+
};
|
|
2376
|
+
await Promise.all(getElementPathList(elementsDir).map(processFile));
|
|
2377
|
+
}
|
|
2378
|
+
|
|
2379
|
+
// src/svelte.ts
|
|
2380
|
+
var import_path3 = __toESM(require("path"));
|
|
2381
|
+
async function compileSvelte(elementsDir, outDir, ns = "") {
|
|
2382
|
+
const fileSystem = {};
|
|
2383
|
+
const processFile = async (elementFilePath) => {
|
|
2384
|
+
const elementDetailList = await getFileElements(elementFilePath);
|
|
2385
|
+
Object.assign(
|
|
2386
|
+
fileSystem,
|
|
2387
|
+
Object.fromEntries(
|
|
2388
|
+
elementDetailList.map(({ name: tag, constructorName, properties }) => {
|
|
2389
|
+
const componentName = getComponentName(tag);
|
|
2390
|
+
const componentPropsName = `${componentName}Props`;
|
|
2391
|
+
const relativePath = getRelativePath(elementFilePath, outDir);
|
|
2392
|
+
const basename = import_path3.default.basename(relativePath);
|
|
2393
|
+
return [
|
|
2394
|
+
[ns, basename].filter((e) => !!e).join("-") + ".ts",
|
|
2395
|
+
`
|
|
2396
|
+
import type { HTMLAttributes } from "svelte/elements";
|
|
2397
|
+
import { ${constructorName} } from '${relativePath}';
|
|
2398
|
+
export * from '${relativePath}';
|
|
2399
|
+
|
|
2400
|
+
interface ${componentPropsName} extends HTMLAttributes<HTMLElement> {
|
|
2401
|
+
${properties.map(
|
|
2402
|
+
({ name: name2, getter, event, deprecated }) => event ? [
|
|
2403
|
+
getJsDocDescName(`'on:${event}'`, deprecated),
|
|
2404
|
+
`(event: CustomEvent<Parameters<${constructorName}['${name2}']>[0]>) => void`
|
|
2405
|
+
].join("?:") : !getter ? [getJsDocDescName(name2, deprecated), `${constructorName}['${name2}']`].join("?:") : ""
|
|
2406
|
+
).join(";\n")}
|
|
2407
|
+
};
|
|
2408
|
+
|
|
2409
|
+
declare module "svelte/elements" {
|
|
2410
|
+
interface SvelteHTMLElements {
|
|
2411
|
+
'${tag}': ${componentPropsName};
|
|
2412
|
+
}
|
|
2413
|
+
}
|
|
2414
|
+
`
|
|
2415
|
+
];
|
|
2416
|
+
})
|
|
2417
|
+
)
|
|
2418
|
+
);
|
|
2419
|
+
};
|
|
2420
|
+
await Promise.all(getElementPathList(elementsDir).map(processFile));
|
|
2421
|
+
compile(outDir, fileSystem);
|
|
2422
|
+
}
|
|
2423
|
+
|
|
2424
|
+
// src/index.ts
|
|
2425
|
+
var cliOptions = {
|
|
2426
|
+
outDir: "./",
|
|
2427
|
+
svelteNs: ""
|
|
2428
|
+
};
|
|
2429
|
+
var timer = setTimeout(() => import_commander.default.outputHelp());
|
|
2430
|
+
import_commander.default.name(name).description(description).version(version, "-v, --version").option("-o, --outdir <path>", `specify out dir`, (outdir) => cliOptions.outDir = outdir).option("--svelte-ns <ns>", `specify svelte element namespace`, (ns) => cliOptions.svelteNs = ns).arguments("<dir>").action(async (dir) => {
|
|
2431
|
+
clearTimeout(timer);
|
|
2432
|
+
await compileReact(dir, import_path4.default.resolve(cliOptions.outDir, "react"));
|
|
2433
|
+
await generateVue(dir, import_path4.default.resolve(cliOptions.outDir, "vue"));
|
|
2434
|
+
await compileSvelte(dir, import_path4.default.resolve(cliOptions.outDir, "svelte"), cliOptions.svelteNs);
|
|
2435
|
+
process.exit(0);
|
|
2436
|
+
});
|
|
2437
|
+
import_commander.default.parse(process.argv);
|