@axiomify/cli 4.0.0 → 6.0.0-rc.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +114 -47
- package/dist/chunk-YZPZCUKZ.mjs +41 -0
- package/dist/dist-PKSGYMK7.mjs +357 -0
- package/dist/index.js +5070 -137
- package/dist/index.mjs +4663 -140
- package/dist/uws_darwin_arm64_108-CLFXMYPI.node +0 -0
- package/dist/uws_darwin_arm64_115-7FFEG3YF.node +0 -0
- package/dist/uws_darwin_arm64_120-GFZT7CLS.node +0 -0
- package/dist/uws_darwin_arm64_127-KHC2FVAM.node +0 -0
- package/dist/uws_darwin_x64_108-BRGT45AT.node +0 -0
- package/dist/uws_darwin_x64_115-4HGPQGDD.node +0 -0
- package/dist/uws_darwin_x64_120-C2SGUHP4.node +0 -0
- package/dist/uws_darwin_x64_127-NHKQMMST.node +0 -0
- package/dist/uws_linux_arm64_108-YHK7ACON.node +0 -0
- package/dist/uws_linux_arm64_115-EIAAY4WO.node +0 -0
- package/dist/uws_linux_arm64_120-OADY5FIN.node +0 -0
- package/dist/uws_linux_arm64_127-U2SRLYQM.node +0 -0
- package/dist/uws_linux_arm_108-BKVITVZA.node +0 -0
- package/dist/uws_linux_arm_115-7IORQF77.node +0 -0
- package/dist/uws_linux_arm_120-LCX4ED5F.node +0 -0
- package/dist/uws_linux_arm_127-6UTO7TL6.node +0 -0
- package/dist/uws_linux_x64_108-QSNE6XWU.node +0 -0
- package/dist/uws_linux_x64_115-7AAZWMWE.node +0 -0
- package/dist/uws_linux_x64_120-AIZ6RIW2.node +0 -0
- package/dist/uws_linux_x64_127-HBA6RNSU.node +0 -0
- package/dist/uws_win32_x64_108-J6KONPDM.node +0 -0
- package/dist/uws_win32_x64_115-V5N4NHJ5.node +0 -0
- package/dist/uws_win32_x64_120-XH4MVJGN.node +0 -0
- package/dist/uws_win32_x64_127-JBAEKR4X.node +0 -0
- package/package.json +5 -2
package/dist/index.mjs
CHANGED
|
@@ -1,80 +1,3587 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
2
|
+
import { __commonJS, __require, __esm, __glob, __toESM } from './chunk-YZPZCUKZ.mjs';
|
|
3
3
|
import * as esbuild from 'esbuild';
|
|
4
|
-
import
|
|
4
|
+
import path7 from 'path';
|
|
5
5
|
import fs, { existsSync } from 'fs';
|
|
6
|
+
import pc from 'picocolors';
|
|
7
|
+
import fs5 from 'fs/promises';
|
|
6
8
|
import { spawn } from 'child_process';
|
|
7
|
-
import
|
|
9
|
+
import { createServer } from 'net';
|
|
10
|
+
import { prompt } from 'enquirer';
|
|
11
|
+
import { execa } from 'execa';
|
|
8
12
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
13
|
+
// node_modules/commander/lib/error.js
|
|
14
|
+
var require_error = __commonJS({
|
|
15
|
+
"node_modules/commander/lib/error.js"(exports) {
|
|
16
|
+
var CommanderError2 = class extends Error {
|
|
17
|
+
/**
|
|
18
|
+
* Constructs the CommanderError class
|
|
19
|
+
* @param {number} exitCode suggested exit code which could be used with process.exit
|
|
20
|
+
* @param {string} code an id string representing the error
|
|
21
|
+
* @param {string} message human-readable description of the error
|
|
22
|
+
* @constructor
|
|
23
|
+
*/
|
|
24
|
+
constructor(exitCode, code, message) {
|
|
25
|
+
super(message);
|
|
26
|
+
Error.captureStackTrace(this, this.constructor);
|
|
27
|
+
this.name = this.constructor.name;
|
|
28
|
+
this.code = code;
|
|
29
|
+
this.exitCode = exitCode;
|
|
30
|
+
this.nestedError = void 0;
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
var InvalidArgumentError2 = class extends CommanderError2 {
|
|
34
|
+
/**
|
|
35
|
+
* Constructs the InvalidArgumentError class
|
|
36
|
+
* @param {string} [message] explanation of why argument is invalid
|
|
37
|
+
* @constructor
|
|
38
|
+
*/
|
|
39
|
+
constructor(message) {
|
|
40
|
+
super(1, "commander.invalidArgument", message);
|
|
41
|
+
Error.captureStackTrace(this, this.constructor);
|
|
42
|
+
this.name = this.constructor.name;
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
exports.CommanderError = CommanderError2;
|
|
46
|
+
exports.InvalidArgumentError = InvalidArgumentError2;
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
// node_modules/commander/lib/argument.js
|
|
51
|
+
var require_argument = __commonJS({
|
|
52
|
+
"node_modules/commander/lib/argument.js"(exports) {
|
|
53
|
+
var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
|
|
54
|
+
var Argument2 = class {
|
|
55
|
+
/**
|
|
56
|
+
* Initialize a new command argument with the given name and description.
|
|
57
|
+
* The default is that the argument is required, and you can explicitly
|
|
58
|
+
* indicate this with <> around the name. Put [] around the name for an optional argument.
|
|
59
|
+
*
|
|
60
|
+
* @param {string} name
|
|
61
|
+
* @param {string} [description]
|
|
62
|
+
*/
|
|
63
|
+
constructor(name, description) {
|
|
64
|
+
this.description = description || "";
|
|
65
|
+
this.variadic = false;
|
|
66
|
+
this.parseArg = void 0;
|
|
67
|
+
this.defaultValue = void 0;
|
|
68
|
+
this.defaultValueDescription = void 0;
|
|
69
|
+
this.argChoices = void 0;
|
|
70
|
+
switch (name[0]) {
|
|
71
|
+
case "<":
|
|
72
|
+
this.required = true;
|
|
73
|
+
this._name = name.slice(1, -1);
|
|
74
|
+
break;
|
|
75
|
+
case "[":
|
|
76
|
+
this.required = false;
|
|
77
|
+
this._name = name.slice(1, -1);
|
|
78
|
+
break;
|
|
79
|
+
default:
|
|
80
|
+
this.required = true;
|
|
81
|
+
this._name = name;
|
|
82
|
+
break;
|
|
83
|
+
}
|
|
84
|
+
if (this._name.length > 3 && this._name.slice(-3) === "...") {
|
|
85
|
+
this.variadic = true;
|
|
86
|
+
this._name = this._name.slice(0, -3);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Return argument name.
|
|
91
|
+
*
|
|
92
|
+
* @return {string}
|
|
93
|
+
*/
|
|
94
|
+
name() {
|
|
95
|
+
return this._name;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* @package internal use only
|
|
99
|
+
*/
|
|
100
|
+
_concatValue(value, previous) {
|
|
101
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) {
|
|
102
|
+
return [value];
|
|
103
|
+
}
|
|
104
|
+
return previous.concat(value);
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Set the default value, and optionally supply the description to be displayed in the help.
|
|
108
|
+
*
|
|
109
|
+
* @param {*} value
|
|
110
|
+
* @param {string} [description]
|
|
111
|
+
* @return {Argument}
|
|
112
|
+
*/
|
|
113
|
+
default(value, description) {
|
|
114
|
+
this.defaultValue = value;
|
|
115
|
+
this.defaultValueDescription = description;
|
|
116
|
+
return this;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Set the custom handler for processing CLI command arguments into argument values.
|
|
120
|
+
*
|
|
121
|
+
* @param {Function} [fn]
|
|
122
|
+
* @return {Argument}
|
|
123
|
+
*/
|
|
124
|
+
argParser(fn) {
|
|
125
|
+
this.parseArg = fn;
|
|
126
|
+
return this;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Only allow argument value to be one of choices.
|
|
130
|
+
*
|
|
131
|
+
* @param {string[]} values
|
|
132
|
+
* @return {Argument}
|
|
133
|
+
*/
|
|
134
|
+
choices(values) {
|
|
135
|
+
this.argChoices = values.slice();
|
|
136
|
+
this.parseArg = (arg, previous) => {
|
|
137
|
+
if (!this.argChoices.includes(arg)) {
|
|
138
|
+
throw new InvalidArgumentError2(`Allowed choices are ${this.argChoices.join(", ")}.`);
|
|
139
|
+
}
|
|
140
|
+
if (this.variadic) {
|
|
141
|
+
return this._concatValue(arg, previous);
|
|
142
|
+
}
|
|
143
|
+
return arg;
|
|
144
|
+
};
|
|
145
|
+
return this;
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Make argument required.
|
|
149
|
+
*/
|
|
150
|
+
argRequired() {
|
|
151
|
+
this.required = true;
|
|
152
|
+
return this;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Make argument optional.
|
|
156
|
+
*/
|
|
157
|
+
argOptional() {
|
|
158
|
+
this.required = false;
|
|
159
|
+
return this;
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
function humanReadableArgName(arg) {
|
|
163
|
+
const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
|
|
164
|
+
return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
|
|
165
|
+
}
|
|
166
|
+
exports.Argument = Argument2;
|
|
167
|
+
exports.humanReadableArgName = humanReadableArgName;
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
// node_modules/commander/lib/help.js
|
|
172
|
+
var require_help = __commonJS({
|
|
173
|
+
"node_modules/commander/lib/help.js"(exports) {
|
|
174
|
+
var { humanReadableArgName } = require_argument();
|
|
175
|
+
var Help2 = class {
|
|
176
|
+
constructor() {
|
|
177
|
+
this.helpWidth = void 0;
|
|
178
|
+
this.sortSubcommands = false;
|
|
179
|
+
this.sortOptions = false;
|
|
180
|
+
this.showGlobalOptions = false;
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
|
|
184
|
+
*
|
|
185
|
+
* @param {Command} cmd
|
|
186
|
+
* @returns {Command[]}
|
|
187
|
+
*/
|
|
188
|
+
visibleCommands(cmd) {
|
|
189
|
+
const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
|
|
190
|
+
const helpCommand = cmd._getHelpCommand();
|
|
191
|
+
if (helpCommand && !helpCommand._hidden) {
|
|
192
|
+
visibleCommands.push(helpCommand);
|
|
193
|
+
}
|
|
194
|
+
if (this.sortSubcommands) {
|
|
195
|
+
visibleCommands.sort((a, b) => {
|
|
196
|
+
return a.name().localeCompare(b.name());
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
return visibleCommands;
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Compare options for sort.
|
|
203
|
+
*
|
|
204
|
+
* @param {Option} a
|
|
205
|
+
* @param {Option} b
|
|
206
|
+
* @returns number
|
|
207
|
+
*/
|
|
208
|
+
compareOptions(a, b) {
|
|
209
|
+
const getSortKey = (option) => {
|
|
210
|
+
return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
|
|
211
|
+
};
|
|
212
|
+
return getSortKey(a).localeCompare(getSortKey(b));
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
|
|
216
|
+
*
|
|
217
|
+
* @param {Command} cmd
|
|
218
|
+
* @returns {Option[]}
|
|
219
|
+
*/
|
|
220
|
+
visibleOptions(cmd) {
|
|
221
|
+
const visibleOptions = cmd.options.filter((option) => !option.hidden);
|
|
222
|
+
const helpOption = cmd._getHelpOption();
|
|
223
|
+
if (helpOption && !helpOption.hidden) {
|
|
224
|
+
const removeShort = helpOption.short && cmd._findOption(helpOption.short);
|
|
225
|
+
const removeLong = helpOption.long && cmd._findOption(helpOption.long);
|
|
226
|
+
if (!removeShort && !removeLong) {
|
|
227
|
+
visibleOptions.push(helpOption);
|
|
228
|
+
} else if (helpOption.long && !removeLong) {
|
|
229
|
+
visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
|
|
230
|
+
} else if (helpOption.short && !removeShort) {
|
|
231
|
+
visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
if (this.sortOptions) {
|
|
235
|
+
visibleOptions.sort(this.compareOptions);
|
|
236
|
+
}
|
|
237
|
+
return visibleOptions;
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Get an array of the visible global options. (Not including help.)
|
|
241
|
+
*
|
|
242
|
+
* @param {Command} cmd
|
|
243
|
+
* @returns {Option[]}
|
|
244
|
+
*/
|
|
245
|
+
visibleGlobalOptions(cmd) {
|
|
246
|
+
if (!this.showGlobalOptions) return [];
|
|
247
|
+
const globalOptions = [];
|
|
248
|
+
for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
|
|
249
|
+
const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
|
|
250
|
+
globalOptions.push(...visibleOptions);
|
|
251
|
+
}
|
|
252
|
+
if (this.sortOptions) {
|
|
253
|
+
globalOptions.sort(this.compareOptions);
|
|
254
|
+
}
|
|
255
|
+
return globalOptions;
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* Get an array of the arguments if any have a description.
|
|
259
|
+
*
|
|
260
|
+
* @param {Command} cmd
|
|
261
|
+
* @returns {Argument[]}
|
|
262
|
+
*/
|
|
263
|
+
visibleArguments(cmd) {
|
|
264
|
+
if (cmd._argsDescription) {
|
|
265
|
+
cmd.registeredArguments.forEach((argument) => {
|
|
266
|
+
argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
if (cmd.registeredArguments.find((argument) => argument.description)) {
|
|
270
|
+
return cmd.registeredArguments;
|
|
271
|
+
}
|
|
272
|
+
return [];
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* Get the command term to show in the list of subcommands.
|
|
276
|
+
*
|
|
277
|
+
* @param {Command} cmd
|
|
278
|
+
* @returns {string}
|
|
279
|
+
*/
|
|
280
|
+
subcommandTerm(cmd) {
|
|
281
|
+
const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
|
|
282
|
+
return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
|
|
283
|
+
(args ? " " + args : "");
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* Get the option term to show in the list of options.
|
|
287
|
+
*
|
|
288
|
+
* @param {Option} option
|
|
289
|
+
* @returns {string}
|
|
290
|
+
*/
|
|
291
|
+
optionTerm(option) {
|
|
292
|
+
return option.flags;
|
|
293
|
+
}
|
|
294
|
+
/**
|
|
295
|
+
* Get the argument term to show in the list of arguments.
|
|
296
|
+
*
|
|
297
|
+
* @param {Argument} argument
|
|
298
|
+
* @returns {string}
|
|
299
|
+
*/
|
|
300
|
+
argumentTerm(argument) {
|
|
301
|
+
return argument.name();
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Get the longest command term length.
|
|
305
|
+
*
|
|
306
|
+
* @param {Command} cmd
|
|
307
|
+
* @param {Help} helper
|
|
308
|
+
* @returns {number}
|
|
309
|
+
*/
|
|
310
|
+
longestSubcommandTermLength(cmd, helper) {
|
|
311
|
+
return helper.visibleCommands(cmd).reduce((max, command) => {
|
|
312
|
+
return Math.max(max, helper.subcommandTerm(command).length);
|
|
313
|
+
}, 0);
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Get the longest option term length.
|
|
317
|
+
*
|
|
318
|
+
* @param {Command} cmd
|
|
319
|
+
* @param {Help} helper
|
|
320
|
+
* @returns {number}
|
|
321
|
+
*/
|
|
322
|
+
longestOptionTermLength(cmd, helper) {
|
|
323
|
+
return helper.visibleOptions(cmd).reduce((max, option) => {
|
|
324
|
+
return Math.max(max, helper.optionTerm(option).length);
|
|
325
|
+
}, 0);
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* Get the longest global option term length.
|
|
329
|
+
*
|
|
330
|
+
* @param {Command} cmd
|
|
331
|
+
* @param {Help} helper
|
|
332
|
+
* @returns {number}
|
|
333
|
+
*/
|
|
334
|
+
longestGlobalOptionTermLength(cmd, helper) {
|
|
335
|
+
return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
|
|
336
|
+
return Math.max(max, helper.optionTerm(option).length);
|
|
337
|
+
}, 0);
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* Get the longest argument term length.
|
|
341
|
+
*
|
|
342
|
+
* @param {Command} cmd
|
|
343
|
+
* @param {Help} helper
|
|
344
|
+
* @returns {number}
|
|
345
|
+
*/
|
|
346
|
+
longestArgumentTermLength(cmd, helper) {
|
|
347
|
+
return helper.visibleArguments(cmd).reduce((max, argument) => {
|
|
348
|
+
return Math.max(max, helper.argumentTerm(argument).length);
|
|
349
|
+
}, 0);
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* Get the command usage to be displayed at the top of the built-in help.
|
|
353
|
+
*
|
|
354
|
+
* @param {Command} cmd
|
|
355
|
+
* @returns {string}
|
|
356
|
+
*/
|
|
357
|
+
commandUsage(cmd) {
|
|
358
|
+
let cmdName = cmd._name;
|
|
359
|
+
if (cmd._aliases[0]) {
|
|
360
|
+
cmdName = cmdName + "|" + cmd._aliases[0];
|
|
361
|
+
}
|
|
362
|
+
let ancestorCmdNames = "";
|
|
363
|
+
for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
|
|
364
|
+
ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
|
|
365
|
+
}
|
|
366
|
+
return ancestorCmdNames + cmdName + " " + cmd.usage();
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* Get the description for the command.
|
|
370
|
+
*
|
|
371
|
+
* @param {Command} cmd
|
|
372
|
+
* @returns {string}
|
|
373
|
+
*/
|
|
374
|
+
commandDescription(cmd) {
|
|
375
|
+
return cmd.description();
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* Get the subcommand summary to show in the list of subcommands.
|
|
379
|
+
* (Fallback to description for backwards compatibility.)
|
|
380
|
+
*
|
|
381
|
+
* @param {Command} cmd
|
|
382
|
+
* @returns {string}
|
|
383
|
+
*/
|
|
384
|
+
subcommandDescription(cmd) {
|
|
385
|
+
return cmd.summary() || cmd.description();
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* Get the option description to show in the list of options.
|
|
389
|
+
*
|
|
390
|
+
* @param {Option} option
|
|
391
|
+
* @return {string}
|
|
392
|
+
*/
|
|
393
|
+
optionDescription(option) {
|
|
394
|
+
const extraInfo = [];
|
|
395
|
+
if (option.argChoices) {
|
|
396
|
+
extraInfo.push(
|
|
397
|
+
// use stringify to match the display of the default value
|
|
398
|
+
`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
|
|
399
|
+
);
|
|
400
|
+
}
|
|
401
|
+
if (option.defaultValue !== void 0) {
|
|
402
|
+
const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
|
|
403
|
+
if (showDefault) {
|
|
404
|
+
extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
if (option.presetArg !== void 0 && option.optional) {
|
|
408
|
+
extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
|
|
409
|
+
}
|
|
410
|
+
if (option.envVar !== void 0) {
|
|
411
|
+
extraInfo.push(`env: ${option.envVar}`);
|
|
412
|
+
}
|
|
413
|
+
if (extraInfo.length > 0) {
|
|
414
|
+
return `${option.description} (${extraInfo.join(", ")})`;
|
|
415
|
+
}
|
|
416
|
+
return option.description;
|
|
417
|
+
}
|
|
418
|
+
/**
|
|
419
|
+
* Get the argument description to show in the list of arguments.
|
|
420
|
+
*
|
|
421
|
+
* @param {Argument} argument
|
|
422
|
+
* @return {string}
|
|
423
|
+
*/
|
|
424
|
+
argumentDescription(argument) {
|
|
425
|
+
const extraInfo = [];
|
|
426
|
+
if (argument.argChoices) {
|
|
427
|
+
extraInfo.push(
|
|
428
|
+
// use stringify to match the display of the default value
|
|
429
|
+
`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
|
|
430
|
+
);
|
|
431
|
+
}
|
|
432
|
+
if (argument.defaultValue !== void 0) {
|
|
433
|
+
extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
|
|
434
|
+
}
|
|
435
|
+
if (extraInfo.length > 0) {
|
|
436
|
+
const extraDescripton = `(${extraInfo.join(", ")})`;
|
|
437
|
+
if (argument.description) {
|
|
438
|
+
return `${argument.description} ${extraDescripton}`;
|
|
439
|
+
}
|
|
440
|
+
return extraDescripton;
|
|
441
|
+
}
|
|
442
|
+
return argument.description;
|
|
443
|
+
}
|
|
444
|
+
/**
|
|
445
|
+
* Generate the built-in help text.
|
|
446
|
+
*
|
|
447
|
+
* @param {Command} cmd
|
|
448
|
+
* @param {Help} helper
|
|
449
|
+
* @returns {string}
|
|
450
|
+
*/
|
|
451
|
+
formatHelp(cmd, helper) {
|
|
452
|
+
const termWidth = helper.padWidth(cmd, helper);
|
|
453
|
+
const helpWidth = helper.helpWidth || 80;
|
|
454
|
+
const itemIndentWidth = 2;
|
|
455
|
+
const itemSeparatorWidth = 2;
|
|
456
|
+
function formatItem(term, description) {
|
|
457
|
+
if (description) {
|
|
458
|
+
const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
|
|
459
|
+
return helper.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth);
|
|
460
|
+
}
|
|
461
|
+
return term;
|
|
462
|
+
}
|
|
463
|
+
function formatList(textArray) {
|
|
464
|
+
return textArray.join("\n").replace(/^/gm, " ".repeat(itemIndentWidth));
|
|
465
|
+
}
|
|
466
|
+
let output = [`Usage: ${helper.commandUsage(cmd)}`, ""];
|
|
467
|
+
const commandDescription = helper.commandDescription(cmd);
|
|
468
|
+
if (commandDescription.length > 0) {
|
|
469
|
+
output = output.concat([helper.wrap(commandDescription, helpWidth, 0), ""]);
|
|
470
|
+
}
|
|
471
|
+
const argumentList = helper.visibleArguments(cmd).map((argument) => {
|
|
472
|
+
return formatItem(helper.argumentTerm(argument), helper.argumentDescription(argument));
|
|
473
|
+
});
|
|
474
|
+
if (argumentList.length > 0) {
|
|
475
|
+
output = output.concat(["Arguments:", formatList(argumentList), ""]);
|
|
476
|
+
}
|
|
477
|
+
const optionList = helper.visibleOptions(cmd).map((option) => {
|
|
478
|
+
return formatItem(helper.optionTerm(option), helper.optionDescription(option));
|
|
479
|
+
});
|
|
480
|
+
if (optionList.length > 0) {
|
|
481
|
+
output = output.concat(["Options:", formatList(optionList), ""]);
|
|
482
|
+
}
|
|
483
|
+
if (this.showGlobalOptions) {
|
|
484
|
+
const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
|
|
485
|
+
return formatItem(helper.optionTerm(option), helper.optionDescription(option));
|
|
486
|
+
});
|
|
487
|
+
if (globalOptionList.length > 0) {
|
|
488
|
+
output = output.concat(["Global Options:", formatList(globalOptionList), ""]);
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
const commandList = helper.visibleCommands(cmd).map((cmd2) => {
|
|
492
|
+
return formatItem(helper.subcommandTerm(cmd2), helper.subcommandDescription(cmd2));
|
|
493
|
+
});
|
|
494
|
+
if (commandList.length > 0) {
|
|
495
|
+
output = output.concat(["Commands:", formatList(commandList), ""]);
|
|
496
|
+
}
|
|
497
|
+
return output.join("\n");
|
|
498
|
+
}
|
|
499
|
+
/**
|
|
500
|
+
* Calculate the pad width from the maximum term length.
|
|
501
|
+
*
|
|
502
|
+
* @param {Command} cmd
|
|
503
|
+
* @param {Help} helper
|
|
504
|
+
* @returns {number}
|
|
505
|
+
*/
|
|
506
|
+
padWidth(cmd, helper) {
|
|
507
|
+
return Math.max(
|
|
508
|
+
helper.longestOptionTermLength(cmd, helper),
|
|
509
|
+
helper.longestGlobalOptionTermLength(cmd, helper),
|
|
510
|
+
helper.longestSubcommandTermLength(cmd, helper),
|
|
511
|
+
helper.longestArgumentTermLength(cmd, helper)
|
|
512
|
+
);
|
|
513
|
+
}
|
|
514
|
+
/**
|
|
515
|
+
* Wrap the given string to width characters per line, with lines after the first indented.
|
|
516
|
+
* Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
|
|
517
|
+
*
|
|
518
|
+
* @param {string} str
|
|
519
|
+
* @param {number} width
|
|
520
|
+
* @param {number} indent
|
|
521
|
+
* @param {number} [minColumnWidth=40]
|
|
522
|
+
* @return {string}
|
|
523
|
+
*
|
|
524
|
+
*/
|
|
525
|
+
wrap(str, width, indent, minColumnWidth = 40) {
|
|
526
|
+
const indents = " \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF";
|
|
527
|
+
const manualIndent = new RegExp(`[\\n][${indents}]+`);
|
|
528
|
+
if (str.match(manualIndent)) return str;
|
|
529
|
+
const columnWidth = width - indent;
|
|
530
|
+
if (columnWidth < minColumnWidth) return str;
|
|
531
|
+
const leadingStr = str.slice(0, indent);
|
|
532
|
+
const columnText = str.slice(indent).replace("\r\n", "\n");
|
|
533
|
+
const indentString = " ".repeat(indent);
|
|
534
|
+
const zeroWidthSpace = "\u200B";
|
|
535
|
+
const breaks = `\\s${zeroWidthSpace}`;
|
|
536
|
+
const regex = new RegExp(`
|
|
537
|
+
|.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`, "g");
|
|
538
|
+
const lines = columnText.match(regex) || [];
|
|
539
|
+
return leadingStr + lines.map((line, i) => {
|
|
540
|
+
if (line === "\n") return "";
|
|
541
|
+
return (i > 0 ? indentString : "") + line.trimEnd();
|
|
542
|
+
}).join("\n");
|
|
543
|
+
}
|
|
544
|
+
};
|
|
545
|
+
exports.Help = Help2;
|
|
546
|
+
}
|
|
547
|
+
});
|
|
548
|
+
|
|
549
|
+
// node_modules/commander/lib/option.js
|
|
550
|
+
var require_option = __commonJS({
|
|
551
|
+
"node_modules/commander/lib/option.js"(exports) {
|
|
552
|
+
var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
|
|
553
|
+
var Option2 = class {
|
|
554
|
+
/**
|
|
555
|
+
* Initialize a new `Option` with the given `flags` and `description`.
|
|
556
|
+
*
|
|
557
|
+
* @param {string} flags
|
|
558
|
+
* @param {string} [description]
|
|
559
|
+
*/
|
|
560
|
+
constructor(flags, description) {
|
|
561
|
+
this.flags = flags;
|
|
562
|
+
this.description = description || "";
|
|
563
|
+
this.required = flags.includes("<");
|
|
564
|
+
this.optional = flags.includes("[");
|
|
565
|
+
this.variadic = /\w\.\.\.[>\]]$/.test(flags);
|
|
566
|
+
this.mandatory = false;
|
|
567
|
+
const optionFlags = splitOptionFlags(flags);
|
|
568
|
+
this.short = optionFlags.shortFlag;
|
|
569
|
+
this.long = optionFlags.longFlag;
|
|
570
|
+
this.negate = false;
|
|
571
|
+
if (this.long) {
|
|
572
|
+
this.negate = this.long.startsWith("--no-");
|
|
573
|
+
}
|
|
574
|
+
this.defaultValue = void 0;
|
|
575
|
+
this.defaultValueDescription = void 0;
|
|
576
|
+
this.presetArg = void 0;
|
|
577
|
+
this.envVar = void 0;
|
|
578
|
+
this.parseArg = void 0;
|
|
579
|
+
this.hidden = false;
|
|
580
|
+
this.argChoices = void 0;
|
|
581
|
+
this.conflictsWith = [];
|
|
582
|
+
this.implied = void 0;
|
|
583
|
+
}
|
|
584
|
+
/**
|
|
585
|
+
* Set the default value, and optionally supply the description to be displayed in the help.
|
|
586
|
+
*
|
|
587
|
+
* @param {*} value
|
|
588
|
+
* @param {string} [description]
|
|
589
|
+
* @return {Option}
|
|
590
|
+
*/
|
|
591
|
+
default(value, description) {
|
|
592
|
+
this.defaultValue = value;
|
|
593
|
+
this.defaultValueDescription = description;
|
|
594
|
+
return this;
|
|
595
|
+
}
|
|
596
|
+
/**
|
|
597
|
+
* Preset to use when option used without option-argument, especially optional but also boolean and negated.
|
|
598
|
+
* The custom processing (parseArg) is called.
|
|
599
|
+
*
|
|
600
|
+
* @example
|
|
601
|
+
* new Option('--color').default('GREYSCALE').preset('RGB');
|
|
602
|
+
* new Option('--donate [amount]').preset('20').argParser(parseFloat);
|
|
603
|
+
*
|
|
604
|
+
* @param {*} arg
|
|
605
|
+
* @return {Option}
|
|
606
|
+
*/
|
|
607
|
+
preset(arg) {
|
|
608
|
+
this.presetArg = arg;
|
|
609
|
+
return this;
|
|
610
|
+
}
|
|
611
|
+
/**
|
|
612
|
+
* Add option name(s) that conflict with this option.
|
|
613
|
+
* An error will be displayed if conflicting options are found during parsing.
|
|
614
|
+
*
|
|
615
|
+
* @example
|
|
616
|
+
* new Option('--rgb').conflicts('cmyk');
|
|
617
|
+
* new Option('--js').conflicts(['ts', 'jsx']);
|
|
618
|
+
*
|
|
619
|
+
* @param {(string | string[])} names
|
|
620
|
+
* @return {Option}
|
|
621
|
+
*/
|
|
622
|
+
conflicts(names) {
|
|
623
|
+
this.conflictsWith = this.conflictsWith.concat(names);
|
|
624
|
+
return this;
|
|
625
|
+
}
|
|
626
|
+
/**
|
|
627
|
+
* Specify implied option values for when this option is set and the implied options are not.
|
|
628
|
+
*
|
|
629
|
+
* The custom processing (parseArg) is not called on the implied values.
|
|
630
|
+
*
|
|
631
|
+
* @example
|
|
632
|
+
* program
|
|
633
|
+
* .addOption(new Option('--log', 'write logging information to file'))
|
|
634
|
+
* .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
|
|
635
|
+
*
|
|
636
|
+
* @param {Object} impliedOptionValues
|
|
637
|
+
* @return {Option}
|
|
638
|
+
*/
|
|
639
|
+
implies(impliedOptionValues) {
|
|
640
|
+
let newImplied = impliedOptionValues;
|
|
641
|
+
if (typeof impliedOptionValues === "string") {
|
|
642
|
+
newImplied = { [impliedOptionValues]: true };
|
|
643
|
+
}
|
|
644
|
+
this.implied = Object.assign(this.implied || {}, newImplied);
|
|
645
|
+
return this;
|
|
646
|
+
}
|
|
647
|
+
/**
|
|
648
|
+
* Set environment variable to check for option value.
|
|
649
|
+
*
|
|
650
|
+
* An environment variable is only used if when processed the current option value is
|
|
651
|
+
* undefined, or the source of the current value is 'default' or 'config' or 'env'.
|
|
652
|
+
*
|
|
653
|
+
* @param {string} name
|
|
654
|
+
* @return {Option}
|
|
655
|
+
*/
|
|
656
|
+
env(name) {
|
|
657
|
+
this.envVar = name;
|
|
658
|
+
return this;
|
|
659
|
+
}
|
|
660
|
+
/**
|
|
661
|
+
* Set the custom handler for processing CLI option arguments into option values.
|
|
662
|
+
*
|
|
663
|
+
* @param {Function} [fn]
|
|
664
|
+
* @return {Option}
|
|
665
|
+
*/
|
|
666
|
+
argParser(fn) {
|
|
667
|
+
this.parseArg = fn;
|
|
668
|
+
return this;
|
|
669
|
+
}
|
|
670
|
+
/**
|
|
671
|
+
* Whether the option is mandatory and must have a value after parsing.
|
|
672
|
+
*
|
|
673
|
+
* @param {boolean} [mandatory=true]
|
|
674
|
+
* @return {Option}
|
|
675
|
+
*/
|
|
676
|
+
makeOptionMandatory(mandatory = true) {
|
|
677
|
+
this.mandatory = !!mandatory;
|
|
678
|
+
return this;
|
|
679
|
+
}
|
|
680
|
+
/**
|
|
681
|
+
* Hide option in help.
|
|
682
|
+
*
|
|
683
|
+
* @param {boolean} [hide=true]
|
|
684
|
+
* @return {Option}
|
|
685
|
+
*/
|
|
686
|
+
hideHelp(hide = true) {
|
|
687
|
+
this.hidden = !!hide;
|
|
688
|
+
return this;
|
|
689
|
+
}
|
|
690
|
+
/**
|
|
691
|
+
* @package internal use only
|
|
692
|
+
*/
|
|
693
|
+
_concatValue(value, previous) {
|
|
694
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) {
|
|
695
|
+
return [value];
|
|
696
|
+
}
|
|
697
|
+
return previous.concat(value);
|
|
698
|
+
}
|
|
699
|
+
/**
|
|
700
|
+
* Only allow option value to be one of choices.
|
|
701
|
+
*
|
|
702
|
+
* @param {string[]} values
|
|
703
|
+
* @return {Option}
|
|
704
|
+
*/
|
|
705
|
+
choices(values) {
|
|
706
|
+
this.argChoices = values.slice();
|
|
707
|
+
this.parseArg = (arg, previous) => {
|
|
708
|
+
if (!this.argChoices.includes(arg)) {
|
|
709
|
+
throw new InvalidArgumentError2(`Allowed choices are ${this.argChoices.join(", ")}.`);
|
|
710
|
+
}
|
|
711
|
+
if (this.variadic) {
|
|
712
|
+
return this._concatValue(arg, previous);
|
|
713
|
+
}
|
|
714
|
+
return arg;
|
|
715
|
+
};
|
|
716
|
+
return this;
|
|
717
|
+
}
|
|
718
|
+
/**
|
|
719
|
+
* Return option name.
|
|
720
|
+
*
|
|
721
|
+
* @return {string}
|
|
722
|
+
*/
|
|
723
|
+
name() {
|
|
724
|
+
if (this.long) {
|
|
725
|
+
return this.long.replace(/^--/, "");
|
|
726
|
+
}
|
|
727
|
+
return this.short.replace(/^-/, "");
|
|
728
|
+
}
|
|
729
|
+
/**
|
|
730
|
+
* Return option name, in a camelcase format that can be used
|
|
731
|
+
* as a object attribute key.
|
|
732
|
+
*
|
|
733
|
+
* @return {string}
|
|
734
|
+
*/
|
|
735
|
+
attributeName() {
|
|
736
|
+
return camelcase(this.name().replace(/^no-/, ""));
|
|
737
|
+
}
|
|
738
|
+
/**
|
|
739
|
+
* Check if `arg` matches the short or long flag.
|
|
740
|
+
*
|
|
741
|
+
* @param {string} arg
|
|
742
|
+
* @return {boolean}
|
|
743
|
+
* @package internal use only
|
|
744
|
+
*/
|
|
745
|
+
is(arg) {
|
|
746
|
+
return this.short === arg || this.long === arg;
|
|
747
|
+
}
|
|
748
|
+
/**
|
|
749
|
+
* Return whether a boolean option.
|
|
750
|
+
*
|
|
751
|
+
* Options are one of boolean, negated, required argument, or optional argument.
|
|
752
|
+
*
|
|
753
|
+
* @return {boolean}
|
|
754
|
+
* @package internal use only
|
|
755
|
+
*/
|
|
756
|
+
isBoolean() {
|
|
757
|
+
return !this.required && !this.optional && !this.negate;
|
|
758
|
+
}
|
|
759
|
+
};
|
|
760
|
+
var DualOptions = class {
|
|
761
|
+
/**
|
|
762
|
+
* @param {Option[]} options
|
|
763
|
+
*/
|
|
764
|
+
constructor(options) {
|
|
765
|
+
this.positiveOptions = /* @__PURE__ */ new Map();
|
|
766
|
+
this.negativeOptions = /* @__PURE__ */ new Map();
|
|
767
|
+
this.dualOptions = /* @__PURE__ */ new Set();
|
|
768
|
+
options.forEach((option) => {
|
|
769
|
+
if (option.negate) {
|
|
770
|
+
this.negativeOptions.set(option.attributeName(), option);
|
|
771
|
+
} else {
|
|
772
|
+
this.positiveOptions.set(option.attributeName(), option);
|
|
773
|
+
}
|
|
774
|
+
});
|
|
775
|
+
this.negativeOptions.forEach((value, key) => {
|
|
776
|
+
if (this.positiveOptions.has(key)) {
|
|
777
|
+
this.dualOptions.add(key);
|
|
778
|
+
}
|
|
779
|
+
});
|
|
780
|
+
}
|
|
781
|
+
/**
|
|
782
|
+
* Did the value come from the option, and not from possible matching dual option?
|
|
783
|
+
*
|
|
784
|
+
* @param {*} value
|
|
785
|
+
* @param {Option} option
|
|
786
|
+
* @returns {boolean}
|
|
787
|
+
*/
|
|
788
|
+
valueFromOption(value, option) {
|
|
789
|
+
const optionKey = option.attributeName();
|
|
790
|
+
if (!this.dualOptions.has(optionKey)) return true;
|
|
791
|
+
const preset = this.negativeOptions.get(optionKey).presetArg;
|
|
792
|
+
const negativeValue = preset !== void 0 ? preset : false;
|
|
793
|
+
return option.negate === (negativeValue === value);
|
|
794
|
+
}
|
|
795
|
+
};
|
|
796
|
+
function camelcase(str) {
|
|
797
|
+
return str.split("-").reduce((str2, word) => {
|
|
798
|
+
return str2 + word[0].toUpperCase() + word.slice(1);
|
|
799
|
+
});
|
|
800
|
+
}
|
|
801
|
+
function splitOptionFlags(flags) {
|
|
802
|
+
let shortFlag;
|
|
803
|
+
let longFlag;
|
|
804
|
+
const flagParts = flags.split(/[ |,]+/);
|
|
805
|
+
if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1])) shortFlag = flagParts.shift();
|
|
806
|
+
longFlag = flagParts.shift();
|
|
807
|
+
if (!shortFlag && /^-[^-]$/.test(longFlag)) {
|
|
808
|
+
shortFlag = longFlag;
|
|
809
|
+
longFlag = void 0;
|
|
810
|
+
}
|
|
811
|
+
return { shortFlag, longFlag };
|
|
812
|
+
}
|
|
813
|
+
exports.Option = Option2;
|
|
814
|
+
exports.DualOptions = DualOptions;
|
|
815
|
+
}
|
|
816
|
+
});
|
|
817
|
+
|
|
818
|
+
// node_modules/commander/lib/suggestSimilar.js
|
|
819
|
+
var require_suggestSimilar = __commonJS({
|
|
820
|
+
"node_modules/commander/lib/suggestSimilar.js"(exports) {
|
|
821
|
+
var maxDistance = 3;
|
|
822
|
+
function editDistance(a, b) {
|
|
823
|
+
if (Math.abs(a.length - b.length) > maxDistance) return Math.max(a.length, b.length);
|
|
824
|
+
const d = [];
|
|
825
|
+
for (let i = 0; i <= a.length; i++) {
|
|
826
|
+
d[i] = [i];
|
|
827
|
+
}
|
|
828
|
+
for (let j = 0; j <= b.length; j++) {
|
|
829
|
+
d[0][j] = j;
|
|
830
|
+
}
|
|
831
|
+
for (let j = 1; j <= b.length; j++) {
|
|
832
|
+
for (let i = 1; i <= a.length; i++) {
|
|
833
|
+
let cost = 1;
|
|
834
|
+
if (a[i - 1] === b[j - 1]) {
|
|
835
|
+
cost = 0;
|
|
836
|
+
} else {
|
|
837
|
+
cost = 1;
|
|
838
|
+
}
|
|
839
|
+
d[i][j] = Math.min(
|
|
840
|
+
d[i - 1][j] + 1,
|
|
841
|
+
// deletion
|
|
842
|
+
d[i][j - 1] + 1,
|
|
843
|
+
// insertion
|
|
844
|
+
d[i - 1][j - 1] + cost
|
|
845
|
+
// substitution
|
|
846
|
+
);
|
|
847
|
+
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
|
|
848
|
+
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
return d[a.length][b.length];
|
|
853
|
+
}
|
|
854
|
+
function suggestSimilar(word, candidates) {
|
|
855
|
+
if (!candidates || candidates.length === 0) return "";
|
|
856
|
+
candidates = Array.from(new Set(candidates));
|
|
857
|
+
const searchingOptions = word.startsWith("--");
|
|
858
|
+
if (searchingOptions) {
|
|
859
|
+
word = word.slice(2);
|
|
860
|
+
candidates = candidates.map((candidate) => candidate.slice(2));
|
|
861
|
+
}
|
|
862
|
+
let similar = [];
|
|
863
|
+
let bestDistance = maxDistance;
|
|
864
|
+
const minSimilarity = 0.4;
|
|
865
|
+
candidates.forEach((candidate) => {
|
|
866
|
+
if (candidate.length <= 1) return;
|
|
867
|
+
const distance = editDistance(word, candidate);
|
|
868
|
+
const length = Math.max(word.length, candidate.length);
|
|
869
|
+
const similarity = (length - distance) / length;
|
|
870
|
+
if (similarity > minSimilarity) {
|
|
871
|
+
if (distance < bestDistance) {
|
|
872
|
+
bestDistance = distance;
|
|
873
|
+
similar = [candidate];
|
|
874
|
+
} else if (distance === bestDistance) {
|
|
875
|
+
similar.push(candidate);
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
});
|
|
879
|
+
similar.sort((a, b) => a.localeCompare(b));
|
|
880
|
+
if (searchingOptions) {
|
|
881
|
+
similar = similar.map((candidate) => `--${candidate}`);
|
|
882
|
+
}
|
|
883
|
+
if (similar.length > 1) {
|
|
884
|
+
return `
|
|
885
|
+
(Did you mean one of ${similar.join(", ")}?)`;
|
|
886
|
+
}
|
|
887
|
+
if (similar.length === 1) {
|
|
888
|
+
return `
|
|
889
|
+
(Did you mean ${similar[0]}?)`;
|
|
890
|
+
}
|
|
891
|
+
return "";
|
|
892
|
+
}
|
|
893
|
+
exports.suggestSimilar = suggestSimilar;
|
|
894
|
+
}
|
|
895
|
+
});
|
|
896
|
+
|
|
897
|
+
// node_modules/commander/lib/command.js
|
|
898
|
+
var require_command = __commonJS({
|
|
899
|
+
"node_modules/commander/lib/command.js"(exports) {
|
|
900
|
+
var EventEmitter = __require("events").EventEmitter;
|
|
901
|
+
var childProcess = __require("child_process");
|
|
902
|
+
var path11 = __require("path");
|
|
903
|
+
var fs9 = __require("fs");
|
|
904
|
+
var process2 = __require("process");
|
|
905
|
+
var { Argument: Argument2, humanReadableArgName } = require_argument();
|
|
906
|
+
var { CommanderError: CommanderError2 } = require_error();
|
|
907
|
+
var { Help: Help2 } = require_help();
|
|
908
|
+
var { Option: Option2, DualOptions } = require_option();
|
|
909
|
+
var { suggestSimilar } = require_suggestSimilar();
|
|
910
|
+
var Command2 = class _Command extends EventEmitter {
|
|
911
|
+
/**
|
|
912
|
+
* Initialize a new `Command`.
|
|
913
|
+
*
|
|
914
|
+
* @param {string} [name]
|
|
915
|
+
*/
|
|
916
|
+
constructor(name) {
|
|
917
|
+
super();
|
|
918
|
+
this.commands = [];
|
|
919
|
+
this.options = [];
|
|
920
|
+
this.parent = null;
|
|
921
|
+
this._allowUnknownOption = false;
|
|
922
|
+
this._allowExcessArguments = true;
|
|
923
|
+
this.registeredArguments = [];
|
|
924
|
+
this._args = this.registeredArguments;
|
|
925
|
+
this.args = [];
|
|
926
|
+
this.rawArgs = [];
|
|
927
|
+
this.processedArgs = [];
|
|
928
|
+
this._scriptPath = null;
|
|
929
|
+
this._name = name || "";
|
|
930
|
+
this._optionValues = {};
|
|
931
|
+
this._optionValueSources = {};
|
|
932
|
+
this._storeOptionsAsProperties = false;
|
|
933
|
+
this._actionHandler = null;
|
|
934
|
+
this._executableHandler = false;
|
|
935
|
+
this._executableFile = null;
|
|
936
|
+
this._executableDir = null;
|
|
937
|
+
this._defaultCommandName = null;
|
|
938
|
+
this._exitCallback = null;
|
|
939
|
+
this._aliases = [];
|
|
940
|
+
this._combineFlagAndOptionalValue = true;
|
|
941
|
+
this._description = "";
|
|
942
|
+
this._summary = "";
|
|
943
|
+
this._argsDescription = void 0;
|
|
944
|
+
this._enablePositionalOptions = false;
|
|
945
|
+
this._passThroughOptions = false;
|
|
946
|
+
this._lifeCycleHooks = {};
|
|
947
|
+
this._showHelpAfterError = false;
|
|
948
|
+
this._showSuggestionAfterError = true;
|
|
949
|
+
this._outputConfiguration = {
|
|
950
|
+
writeOut: (str) => process2.stdout.write(str),
|
|
951
|
+
writeErr: (str) => process2.stderr.write(str),
|
|
952
|
+
getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
|
|
953
|
+
getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
|
|
954
|
+
outputError: (str, write) => write(str)
|
|
955
|
+
};
|
|
956
|
+
this._hidden = false;
|
|
957
|
+
this._helpOption = void 0;
|
|
958
|
+
this._addImplicitHelpCommand = void 0;
|
|
959
|
+
this._helpCommand = void 0;
|
|
960
|
+
this._helpConfiguration = {};
|
|
961
|
+
}
|
|
962
|
+
/**
|
|
963
|
+
* Copy settings that are useful to have in common across root command and subcommands.
|
|
964
|
+
*
|
|
965
|
+
* (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
|
|
966
|
+
*
|
|
967
|
+
* @param {Command} sourceCommand
|
|
968
|
+
* @return {Command} `this` command for chaining
|
|
969
|
+
*/
|
|
970
|
+
copyInheritedSettings(sourceCommand) {
|
|
971
|
+
this._outputConfiguration = sourceCommand._outputConfiguration;
|
|
972
|
+
this._helpOption = sourceCommand._helpOption;
|
|
973
|
+
this._helpCommand = sourceCommand._helpCommand;
|
|
974
|
+
this._helpConfiguration = sourceCommand._helpConfiguration;
|
|
975
|
+
this._exitCallback = sourceCommand._exitCallback;
|
|
976
|
+
this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
|
|
977
|
+
this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
|
|
978
|
+
this._allowExcessArguments = sourceCommand._allowExcessArguments;
|
|
979
|
+
this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
|
|
980
|
+
this._showHelpAfterError = sourceCommand._showHelpAfterError;
|
|
981
|
+
this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
|
|
982
|
+
return this;
|
|
983
|
+
}
|
|
984
|
+
/**
|
|
985
|
+
* @returns {Command[]}
|
|
986
|
+
* @private
|
|
987
|
+
*/
|
|
988
|
+
_getCommandAndAncestors() {
|
|
989
|
+
const result = [];
|
|
990
|
+
for (let command = this; command; command = command.parent) {
|
|
991
|
+
result.push(command);
|
|
992
|
+
}
|
|
993
|
+
return result;
|
|
994
|
+
}
|
|
995
|
+
/**
|
|
996
|
+
* Define a command.
|
|
997
|
+
*
|
|
998
|
+
* There are two styles of command: pay attention to where to put the description.
|
|
999
|
+
*
|
|
1000
|
+
* @example
|
|
1001
|
+
* // Command implemented using action handler (description is supplied separately to `.command`)
|
|
1002
|
+
* program
|
|
1003
|
+
* .command('clone <source> [destination]')
|
|
1004
|
+
* .description('clone a repository into a newly created directory')
|
|
1005
|
+
* .action((source, destination) => {
|
|
1006
|
+
* console.log('clone command called');
|
|
1007
|
+
* });
|
|
1008
|
+
*
|
|
1009
|
+
* // Command implemented using separate executable file (description is second parameter to `.command`)
|
|
1010
|
+
* program
|
|
1011
|
+
* .command('start <service>', 'start named service')
|
|
1012
|
+
* .command('stop [service]', 'stop named service, or all if no name supplied');
|
|
1013
|
+
*
|
|
1014
|
+
* @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
|
|
1015
|
+
* @param {(Object|string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
|
|
1016
|
+
* @param {Object} [execOpts] - configuration options (for executable)
|
|
1017
|
+
* @return {Command} returns new command for action handler, or `this` for executable command
|
|
1018
|
+
*/
|
|
1019
|
+
command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
|
|
1020
|
+
let desc = actionOptsOrExecDesc;
|
|
1021
|
+
let opts = execOpts;
|
|
1022
|
+
if (typeof desc === "object" && desc !== null) {
|
|
1023
|
+
opts = desc;
|
|
1024
|
+
desc = null;
|
|
1025
|
+
}
|
|
1026
|
+
opts = opts || {};
|
|
1027
|
+
const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
|
|
1028
|
+
const cmd = this.createCommand(name);
|
|
1029
|
+
if (desc) {
|
|
1030
|
+
cmd.description(desc);
|
|
1031
|
+
cmd._executableHandler = true;
|
|
1032
|
+
}
|
|
1033
|
+
if (opts.isDefault) this._defaultCommandName = cmd._name;
|
|
1034
|
+
cmd._hidden = !!(opts.noHelp || opts.hidden);
|
|
1035
|
+
cmd._executableFile = opts.executableFile || null;
|
|
1036
|
+
if (args) cmd.arguments(args);
|
|
1037
|
+
this._registerCommand(cmd);
|
|
1038
|
+
cmd.parent = this;
|
|
1039
|
+
cmd.copyInheritedSettings(this);
|
|
1040
|
+
if (desc) return this;
|
|
1041
|
+
return cmd;
|
|
1042
|
+
}
|
|
1043
|
+
/**
|
|
1044
|
+
* Factory routine to create a new unattached command.
|
|
1045
|
+
*
|
|
1046
|
+
* See .command() for creating an attached subcommand, which uses this routine to
|
|
1047
|
+
* create the command. You can override createCommand to customise subcommands.
|
|
1048
|
+
*
|
|
1049
|
+
* @param {string} [name]
|
|
1050
|
+
* @return {Command} new command
|
|
1051
|
+
*/
|
|
1052
|
+
createCommand(name) {
|
|
1053
|
+
return new _Command(name);
|
|
1054
|
+
}
|
|
1055
|
+
/**
|
|
1056
|
+
* You can customise the help with a subclass of Help by overriding createHelp,
|
|
1057
|
+
* or by overriding Help properties using configureHelp().
|
|
1058
|
+
*
|
|
1059
|
+
* @return {Help}
|
|
1060
|
+
*/
|
|
1061
|
+
createHelp() {
|
|
1062
|
+
return Object.assign(new Help2(), this.configureHelp());
|
|
1063
|
+
}
|
|
1064
|
+
/**
|
|
1065
|
+
* You can customise the help by overriding Help properties using configureHelp(),
|
|
1066
|
+
* or with a subclass of Help by overriding createHelp().
|
|
1067
|
+
*
|
|
1068
|
+
* @param {Object} [configuration] - configuration options
|
|
1069
|
+
* @return {(Command|Object)} `this` command for chaining, or stored configuration
|
|
1070
|
+
*/
|
|
1071
|
+
configureHelp(configuration) {
|
|
1072
|
+
if (configuration === void 0) return this._helpConfiguration;
|
|
1073
|
+
this._helpConfiguration = configuration;
|
|
1074
|
+
return this;
|
|
1075
|
+
}
|
|
1076
|
+
/**
|
|
1077
|
+
* The default output goes to stdout and stderr. You can customise this for special
|
|
1078
|
+
* applications. You can also customise the display of errors by overriding outputError.
|
|
1079
|
+
*
|
|
1080
|
+
* The configuration properties are all functions:
|
|
1081
|
+
*
|
|
1082
|
+
* // functions to change where being written, stdout and stderr
|
|
1083
|
+
* writeOut(str)
|
|
1084
|
+
* writeErr(str)
|
|
1085
|
+
* // matching functions to specify width for wrapping help
|
|
1086
|
+
* getOutHelpWidth()
|
|
1087
|
+
* getErrHelpWidth()
|
|
1088
|
+
* // functions based on what is being written out
|
|
1089
|
+
* outputError(str, write) // used for displaying errors, and not used for displaying help
|
|
1090
|
+
*
|
|
1091
|
+
* @param {Object} [configuration] - configuration options
|
|
1092
|
+
* @return {(Command|Object)} `this` command for chaining, or stored configuration
|
|
1093
|
+
*/
|
|
1094
|
+
configureOutput(configuration) {
|
|
1095
|
+
if (configuration === void 0) return this._outputConfiguration;
|
|
1096
|
+
Object.assign(this._outputConfiguration, configuration);
|
|
1097
|
+
return this;
|
|
1098
|
+
}
|
|
1099
|
+
/**
|
|
1100
|
+
* Display the help or a custom message after an error occurs.
|
|
1101
|
+
*
|
|
1102
|
+
* @param {(boolean|string)} [displayHelp]
|
|
1103
|
+
* @return {Command} `this` command for chaining
|
|
1104
|
+
*/
|
|
1105
|
+
showHelpAfterError(displayHelp = true) {
|
|
1106
|
+
if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
|
|
1107
|
+
this._showHelpAfterError = displayHelp;
|
|
1108
|
+
return this;
|
|
1109
|
+
}
|
|
1110
|
+
/**
|
|
1111
|
+
* Display suggestion of similar commands for unknown commands, or options for unknown options.
|
|
1112
|
+
*
|
|
1113
|
+
* @param {boolean} [displaySuggestion]
|
|
1114
|
+
* @return {Command} `this` command for chaining
|
|
1115
|
+
*/
|
|
1116
|
+
showSuggestionAfterError(displaySuggestion = true) {
|
|
1117
|
+
this._showSuggestionAfterError = !!displaySuggestion;
|
|
1118
|
+
return this;
|
|
1119
|
+
}
|
|
1120
|
+
/**
|
|
1121
|
+
* Add a prepared subcommand.
|
|
1122
|
+
*
|
|
1123
|
+
* See .command() for creating an attached subcommand which inherits settings from its parent.
|
|
1124
|
+
*
|
|
1125
|
+
* @param {Command} cmd - new subcommand
|
|
1126
|
+
* @param {Object} [opts] - configuration options
|
|
1127
|
+
* @return {Command} `this` command for chaining
|
|
1128
|
+
*/
|
|
1129
|
+
addCommand(cmd, opts) {
|
|
1130
|
+
if (!cmd._name) {
|
|
1131
|
+
throw new Error(`Command passed to .addCommand() must have a name
|
|
1132
|
+
- specify the name in Command constructor or using .name()`);
|
|
1133
|
+
}
|
|
1134
|
+
opts = opts || {};
|
|
1135
|
+
if (opts.isDefault) this._defaultCommandName = cmd._name;
|
|
1136
|
+
if (opts.noHelp || opts.hidden) cmd._hidden = true;
|
|
1137
|
+
this._registerCommand(cmd);
|
|
1138
|
+
cmd.parent = this;
|
|
1139
|
+
cmd._checkForBrokenPassThrough();
|
|
1140
|
+
return this;
|
|
1141
|
+
}
|
|
1142
|
+
/**
|
|
1143
|
+
* Factory routine to create a new unattached argument.
|
|
1144
|
+
*
|
|
1145
|
+
* See .argument() for creating an attached argument, which uses this routine to
|
|
1146
|
+
* create the argument. You can override createArgument to return a custom argument.
|
|
1147
|
+
*
|
|
1148
|
+
* @param {string} name
|
|
1149
|
+
* @param {string} [description]
|
|
1150
|
+
* @return {Argument} new argument
|
|
1151
|
+
*/
|
|
1152
|
+
createArgument(name, description) {
|
|
1153
|
+
return new Argument2(name, description);
|
|
1154
|
+
}
|
|
1155
|
+
/**
|
|
1156
|
+
* Define argument syntax for command.
|
|
1157
|
+
*
|
|
1158
|
+
* The default is that the argument is required, and you can explicitly
|
|
1159
|
+
* indicate this with <> around the name. Put [] around the name for an optional argument.
|
|
1160
|
+
*
|
|
1161
|
+
* @example
|
|
1162
|
+
* program.argument('<input-file>');
|
|
1163
|
+
* program.argument('[output-file]');
|
|
1164
|
+
*
|
|
1165
|
+
* @param {string} name
|
|
1166
|
+
* @param {string} [description]
|
|
1167
|
+
* @param {(Function|*)} [fn] - custom argument processing function
|
|
1168
|
+
* @param {*} [defaultValue]
|
|
1169
|
+
* @return {Command} `this` command for chaining
|
|
1170
|
+
*/
|
|
1171
|
+
argument(name, description, fn, defaultValue) {
|
|
1172
|
+
const argument = this.createArgument(name, description);
|
|
1173
|
+
if (typeof fn === "function") {
|
|
1174
|
+
argument.default(defaultValue).argParser(fn);
|
|
1175
|
+
} else {
|
|
1176
|
+
argument.default(fn);
|
|
1177
|
+
}
|
|
1178
|
+
this.addArgument(argument);
|
|
1179
|
+
return this;
|
|
1180
|
+
}
|
|
1181
|
+
/**
|
|
1182
|
+
* Define argument syntax for command, adding multiple at once (without descriptions).
|
|
1183
|
+
*
|
|
1184
|
+
* See also .argument().
|
|
1185
|
+
*
|
|
1186
|
+
* @example
|
|
1187
|
+
* program.arguments('<cmd> [env]');
|
|
1188
|
+
*
|
|
1189
|
+
* @param {string} names
|
|
1190
|
+
* @return {Command} `this` command for chaining
|
|
1191
|
+
*/
|
|
1192
|
+
arguments(names) {
|
|
1193
|
+
names.trim().split(/ +/).forEach((detail) => {
|
|
1194
|
+
this.argument(detail);
|
|
1195
|
+
});
|
|
1196
|
+
return this;
|
|
1197
|
+
}
|
|
1198
|
+
/**
|
|
1199
|
+
* Define argument syntax for command, adding a prepared argument.
|
|
1200
|
+
*
|
|
1201
|
+
* @param {Argument} argument
|
|
1202
|
+
* @return {Command} `this` command for chaining
|
|
1203
|
+
*/
|
|
1204
|
+
addArgument(argument) {
|
|
1205
|
+
const previousArgument = this.registeredArguments.slice(-1)[0];
|
|
1206
|
+
if (previousArgument && previousArgument.variadic) {
|
|
1207
|
+
throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
|
|
1208
|
+
}
|
|
1209
|
+
if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
|
|
1210
|
+
throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
|
|
1211
|
+
}
|
|
1212
|
+
this.registeredArguments.push(argument);
|
|
1213
|
+
return this;
|
|
1214
|
+
}
|
|
1215
|
+
/**
|
|
1216
|
+
* Customise or override default help command. By default a help command is automatically added if your command has subcommands.
|
|
1217
|
+
*
|
|
1218
|
+
* program.helpCommand('help [cmd]');
|
|
1219
|
+
* program.helpCommand('help [cmd]', 'show help');
|
|
1220
|
+
* program.helpCommand(false); // suppress default help command
|
|
1221
|
+
* program.helpCommand(true); // add help command even if no subcommands
|
|
1222
|
+
*
|
|
1223
|
+
* @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
|
|
1224
|
+
* @param {string} [description] - custom description
|
|
1225
|
+
* @return {Command} `this` command for chaining
|
|
1226
|
+
*/
|
|
1227
|
+
helpCommand(enableOrNameAndArgs, description) {
|
|
1228
|
+
if (typeof enableOrNameAndArgs === "boolean") {
|
|
1229
|
+
this._addImplicitHelpCommand = enableOrNameAndArgs;
|
|
1230
|
+
return this;
|
|
1231
|
+
}
|
|
1232
|
+
enableOrNameAndArgs = enableOrNameAndArgs ?? "help [command]";
|
|
1233
|
+
const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
|
|
1234
|
+
const helpDescription = description ?? "display help for command";
|
|
1235
|
+
const helpCommand = this.createCommand(helpName);
|
|
1236
|
+
helpCommand.helpOption(false);
|
|
1237
|
+
if (helpArgs) helpCommand.arguments(helpArgs);
|
|
1238
|
+
if (helpDescription) helpCommand.description(helpDescription);
|
|
1239
|
+
this._addImplicitHelpCommand = true;
|
|
1240
|
+
this._helpCommand = helpCommand;
|
|
1241
|
+
return this;
|
|
1242
|
+
}
|
|
1243
|
+
/**
|
|
1244
|
+
* Add prepared custom help command.
|
|
1245
|
+
*
|
|
1246
|
+
* @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
|
|
1247
|
+
* @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
|
|
1248
|
+
* @return {Command} `this` command for chaining
|
|
1249
|
+
*/
|
|
1250
|
+
addHelpCommand(helpCommand, deprecatedDescription) {
|
|
1251
|
+
if (typeof helpCommand !== "object") {
|
|
1252
|
+
this.helpCommand(helpCommand, deprecatedDescription);
|
|
1253
|
+
return this;
|
|
1254
|
+
}
|
|
1255
|
+
this._addImplicitHelpCommand = true;
|
|
1256
|
+
this._helpCommand = helpCommand;
|
|
1257
|
+
return this;
|
|
1258
|
+
}
|
|
1259
|
+
/**
|
|
1260
|
+
* Lazy create help command.
|
|
1261
|
+
*
|
|
1262
|
+
* @return {(Command|null)}
|
|
1263
|
+
* @package
|
|
1264
|
+
*/
|
|
1265
|
+
_getHelpCommand() {
|
|
1266
|
+
const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
|
|
1267
|
+
if (hasImplicitHelpCommand) {
|
|
1268
|
+
if (this._helpCommand === void 0) {
|
|
1269
|
+
this.helpCommand(void 0, void 0);
|
|
1270
|
+
}
|
|
1271
|
+
return this._helpCommand;
|
|
1272
|
+
}
|
|
1273
|
+
return null;
|
|
1274
|
+
}
|
|
1275
|
+
/**
|
|
1276
|
+
* Add hook for life cycle event.
|
|
1277
|
+
*
|
|
1278
|
+
* @param {string} event
|
|
1279
|
+
* @param {Function} listener
|
|
1280
|
+
* @return {Command} `this` command for chaining
|
|
1281
|
+
*/
|
|
1282
|
+
hook(event, listener) {
|
|
1283
|
+
const allowedValues = ["preSubcommand", "preAction", "postAction"];
|
|
1284
|
+
if (!allowedValues.includes(event)) {
|
|
1285
|
+
throw new Error(`Unexpected value for event passed to hook : '${event}'.
|
|
1286
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
1287
|
+
}
|
|
1288
|
+
if (this._lifeCycleHooks[event]) {
|
|
1289
|
+
this._lifeCycleHooks[event].push(listener);
|
|
1290
|
+
} else {
|
|
1291
|
+
this._lifeCycleHooks[event] = [listener];
|
|
1292
|
+
}
|
|
1293
|
+
return this;
|
|
1294
|
+
}
|
|
1295
|
+
/**
|
|
1296
|
+
* Register callback to use as replacement for calling process.exit.
|
|
1297
|
+
*
|
|
1298
|
+
* @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
|
|
1299
|
+
* @return {Command} `this` command for chaining
|
|
1300
|
+
*/
|
|
1301
|
+
exitOverride(fn) {
|
|
1302
|
+
if (fn) {
|
|
1303
|
+
this._exitCallback = fn;
|
|
1304
|
+
} else {
|
|
1305
|
+
this._exitCallback = (err) => {
|
|
1306
|
+
if (err.code !== "commander.executeSubCommandAsync") {
|
|
1307
|
+
throw err;
|
|
1308
|
+
}
|
|
1309
|
+
};
|
|
1310
|
+
}
|
|
1311
|
+
return this;
|
|
1312
|
+
}
|
|
1313
|
+
/**
|
|
1314
|
+
* Call process.exit, and _exitCallback if defined.
|
|
1315
|
+
*
|
|
1316
|
+
* @param {number} exitCode exit code for using with process.exit
|
|
1317
|
+
* @param {string} code an id string representing the error
|
|
1318
|
+
* @param {string} message human-readable description of the error
|
|
1319
|
+
* @return never
|
|
1320
|
+
* @private
|
|
1321
|
+
*/
|
|
1322
|
+
_exit(exitCode, code, message) {
|
|
1323
|
+
if (this._exitCallback) {
|
|
1324
|
+
this._exitCallback(new CommanderError2(exitCode, code, message));
|
|
1325
|
+
}
|
|
1326
|
+
process2.exit(exitCode);
|
|
1327
|
+
}
|
|
1328
|
+
/**
|
|
1329
|
+
* Register callback `fn` for the command.
|
|
1330
|
+
*
|
|
1331
|
+
* @example
|
|
1332
|
+
* program
|
|
1333
|
+
* .command('serve')
|
|
1334
|
+
* .description('start service')
|
|
1335
|
+
* .action(function() {
|
|
1336
|
+
* // do work here
|
|
1337
|
+
* });
|
|
1338
|
+
*
|
|
1339
|
+
* @param {Function} fn
|
|
1340
|
+
* @return {Command} `this` command for chaining
|
|
1341
|
+
*/
|
|
1342
|
+
action(fn) {
|
|
1343
|
+
const listener = (args) => {
|
|
1344
|
+
const expectedArgsCount = this.registeredArguments.length;
|
|
1345
|
+
const actionArgs = args.slice(0, expectedArgsCount);
|
|
1346
|
+
if (this._storeOptionsAsProperties) {
|
|
1347
|
+
actionArgs[expectedArgsCount] = this;
|
|
1348
|
+
} else {
|
|
1349
|
+
actionArgs[expectedArgsCount] = this.opts();
|
|
1350
|
+
}
|
|
1351
|
+
actionArgs.push(this);
|
|
1352
|
+
return fn.apply(this, actionArgs);
|
|
1353
|
+
};
|
|
1354
|
+
this._actionHandler = listener;
|
|
1355
|
+
return this;
|
|
1356
|
+
}
|
|
1357
|
+
/**
|
|
1358
|
+
* Factory routine to create a new unattached option.
|
|
1359
|
+
*
|
|
1360
|
+
* See .option() for creating an attached option, which uses this routine to
|
|
1361
|
+
* create the option. You can override createOption to return a custom option.
|
|
1362
|
+
*
|
|
1363
|
+
* @param {string} flags
|
|
1364
|
+
* @param {string} [description]
|
|
1365
|
+
* @return {Option} new option
|
|
1366
|
+
*/
|
|
1367
|
+
createOption(flags, description) {
|
|
1368
|
+
return new Option2(flags, description);
|
|
1369
|
+
}
|
|
1370
|
+
/**
|
|
1371
|
+
* Wrap parseArgs to catch 'commander.invalidArgument'.
|
|
1372
|
+
*
|
|
1373
|
+
* @param {(Option | Argument)} target
|
|
1374
|
+
* @param {string} value
|
|
1375
|
+
* @param {*} previous
|
|
1376
|
+
* @param {string} invalidArgumentMessage
|
|
1377
|
+
* @private
|
|
1378
|
+
*/
|
|
1379
|
+
_callParseArg(target, value, previous, invalidArgumentMessage) {
|
|
1380
|
+
try {
|
|
1381
|
+
return target.parseArg(value, previous);
|
|
1382
|
+
} catch (err) {
|
|
1383
|
+
if (err.code === "commander.invalidArgument") {
|
|
1384
|
+
const message = `${invalidArgumentMessage} ${err.message}`;
|
|
1385
|
+
this.error(message, { exitCode: err.exitCode, code: err.code });
|
|
1386
|
+
}
|
|
1387
|
+
throw err;
|
|
1388
|
+
}
|
|
1389
|
+
}
|
|
1390
|
+
/**
|
|
1391
|
+
* Check for option flag conflicts.
|
|
1392
|
+
* Register option if no conflicts found, or throw on conflict.
|
|
1393
|
+
*
|
|
1394
|
+
* @param {Option} option
|
|
1395
|
+
* @api private
|
|
1396
|
+
*/
|
|
1397
|
+
_registerOption(option) {
|
|
1398
|
+
const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
|
|
1399
|
+
if (matchingOption) {
|
|
1400
|
+
const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
|
|
1401
|
+
throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
|
|
1402
|
+
- already used by option '${matchingOption.flags}'`);
|
|
1403
|
+
}
|
|
1404
|
+
this.options.push(option);
|
|
1405
|
+
}
|
|
1406
|
+
/**
|
|
1407
|
+
* Check for command name and alias conflicts with existing commands.
|
|
1408
|
+
* Register command if no conflicts found, or throw on conflict.
|
|
1409
|
+
*
|
|
1410
|
+
* @param {Command} command
|
|
1411
|
+
* @api private
|
|
1412
|
+
*/
|
|
1413
|
+
_registerCommand(command) {
|
|
1414
|
+
const knownBy = (cmd) => {
|
|
1415
|
+
return [cmd.name()].concat(cmd.aliases());
|
|
1416
|
+
};
|
|
1417
|
+
const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
|
|
1418
|
+
if (alreadyUsed) {
|
|
1419
|
+
const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
|
|
1420
|
+
const newCmd = knownBy(command).join("|");
|
|
1421
|
+
throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
|
|
1422
|
+
}
|
|
1423
|
+
this.commands.push(command);
|
|
1424
|
+
}
|
|
1425
|
+
/**
|
|
1426
|
+
* Add an option.
|
|
1427
|
+
*
|
|
1428
|
+
* @param {Option} option
|
|
1429
|
+
* @return {Command} `this` command for chaining
|
|
1430
|
+
*/
|
|
1431
|
+
addOption(option) {
|
|
1432
|
+
this._registerOption(option);
|
|
1433
|
+
const oname = option.name();
|
|
1434
|
+
const name = option.attributeName();
|
|
1435
|
+
if (option.negate) {
|
|
1436
|
+
const positiveLongFlag = option.long.replace(/^--no-/, "--");
|
|
1437
|
+
if (!this._findOption(positiveLongFlag)) {
|
|
1438
|
+
this.setOptionValueWithSource(name, option.defaultValue === void 0 ? true : option.defaultValue, "default");
|
|
1439
|
+
}
|
|
1440
|
+
} else if (option.defaultValue !== void 0) {
|
|
1441
|
+
this.setOptionValueWithSource(name, option.defaultValue, "default");
|
|
1442
|
+
}
|
|
1443
|
+
const handleOptionValue = (val, invalidValueMessage, valueSource) => {
|
|
1444
|
+
if (val == null && option.presetArg !== void 0) {
|
|
1445
|
+
val = option.presetArg;
|
|
1446
|
+
}
|
|
1447
|
+
const oldValue = this.getOptionValue(name);
|
|
1448
|
+
if (val !== null && option.parseArg) {
|
|
1449
|
+
val = this._callParseArg(option, val, oldValue, invalidValueMessage);
|
|
1450
|
+
} else if (val !== null && option.variadic) {
|
|
1451
|
+
val = option._concatValue(val, oldValue);
|
|
1452
|
+
}
|
|
1453
|
+
if (val == null) {
|
|
1454
|
+
if (option.negate) {
|
|
1455
|
+
val = false;
|
|
1456
|
+
} else if (option.isBoolean() || option.optional) {
|
|
1457
|
+
val = true;
|
|
1458
|
+
} else {
|
|
1459
|
+
val = "";
|
|
1460
|
+
}
|
|
1461
|
+
}
|
|
1462
|
+
this.setOptionValueWithSource(name, val, valueSource);
|
|
1463
|
+
};
|
|
1464
|
+
this.on("option:" + oname, (val) => {
|
|
1465
|
+
const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
|
|
1466
|
+
handleOptionValue(val, invalidValueMessage, "cli");
|
|
1467
|
+
});
|
|
1468
|
+
if (option.envVar) {
|
|
1469
|
+
this.on("optionEnv:" + oname, (val) => {
|
|
1470
|
+
const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
|
|
1471
|
+
handleOptionValue(val, invalidValueMessage, "env");
|
|
1472
|
+
});
|
|
1473
|
+
}
|
|
1474
|
+
return this;
|
|
1475
|
+
}
|
|
1476
|
+
/**
|
|
1477
|
+
* Internal implementation shared by .option() and .requiredOption()
|
|
1478
|
+
*
|
|
1479
|
+
* @private
|
|
1480
|
+
*/
|
|
1481
|
+
_optionEx(config, flags, description, fn, defaultValue) {
|
|
1482
|
+
if (typeof flags === "object" && flags instanceof Option2) {
|
|
1483
|
+
throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
|
|
1484
|
+
}
|
|
1485
|
+
const option = this.createOption(flags, description);
|
|
1486
|
+
option.makeOptionMandatory(!!config.mandatory);
|
|
1487
|
+
if (typeof fn === "function") {
|
|
1488
|
+
option.default(defaultValue).argParser(fn);
|
|
1489
|
+
} else if (fn instanceof RegExp) {
|
|
1490
|
+
const regex = fn;
|
|
1491
|
+
fn = (val, def) => {
|
|
1492
|
+
const m = regex.exec(val);
|
|
1493
|
+
return m ? m[0] : def;
|
|
1494
|
+
};
|
|
1495
|
+
option.default(defaultValue).argParser(fn);
|
|
1496
|
+
} else {
|
|
1497
|
+
option.default(fn);
|
|
1498
|
+
}
|
|
1499
|
+
return this.addOption(option);
|
|
1500
|
+
}
|
|
1501
|
+
/**
|
|
1502
|
+
* Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
|
|
1503
|
+
*
|
|
1504
|
+
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
|
|
1505
|
+
* option-argument is indicated by `<>` and an optional option-argument by `[]`.
|
|
1506
|
+
*
|
|
1507
|
+
* See the README for more details, and see also addOption() and requiredOption().
|
|
1508
|
+
*
|
|
1509
|
+
* @example
|
|
1510
|
+
* program
|
|
1511
|
+
* .option('-p, --pepper', 'add pepper')
|
|
1512
|
+
* .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument
|
|
1513
|
+
* .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
|
|
1514
|
+
* .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
|
|
1515
|
+
*
|
|
1516
|
+
* @param {string} flags
|
|
1517
|
+
* @param {string} [description]
|
|
1518
|
+
* @param {(Function|*)} [parseArg] - custom option processing function or default value
|
|
1519
|
+
* @param {*} [defaultValue]
|
|
1520
|
+
* @return {Command} `this` command for chaining
|
|
1521
|
+
*/
|
|
1522
|
+
option(flags, description, parseArg, defaultValue) {
|
|
1523
|
+
return this._optionEx({}, flags, description, parseArg, defaultValue);
|
|
1524
|
+
}
|
|
1525
|
+
/**
|
|
1526
|
+
* Add a required option which must have a value after parsing. This usually means
|
|
1527
|
+
* the option must be specified on the command line. (Otherwise the same as .option().)
|
|
1528
|
+
*
|
|
1529
|
+
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
|
|
1530
|
+
*
|
|
1531
|
+
* @param {string} flags
|
|
1532
|
+
* @param {string} [description]
|
|
1533
|
+
* @param {(Function|*)} [parseArg] - custom option processing function or default value
|
|
1534
|
+
* @param {*} [defaultValue]
|
|
1535
|
+
* @return {Command} `this` command for chaining
|
|
1536
|
+
*/
|
|
1537
|
+
requiredOption(flags, description, parseArg, defaultValue) {
|
|
1538
|
+
return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
|
|
1539
|
+
}
|
|
1540
|
+
/**
|
|
1541
|
+
* Alter parsing of short flags with optional values.
|
|
1542
|
+
*
|
|
1543
|
+
* @example
|
|
1544
|
+
* // for `.option('-f,--flag [value]'):
|
|
1545
|
+
* program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
|
|
1546
|
+
* program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
|
|
1547
|
+
*
|
|
1548
|
+
* @param {boolean} [combine=true] - if `true` or omitted, an optional value can be specified directly after the flag.
|
|
1549
|
+
*/
|
|
1550
|
+
combineFlagAndOptionalValue(combine = true) {
|
|
1551
|
+
this._combineFlagAndOptionalValue = !!combine;
|
|
1552
|
+
return this;
|
|
1553
|
+
}
|
|
1554
|
+
/**
|
|
1555
|
+
* Allow unknown options on the command line.
|
|
1556
|
+
*
|
|
1557
|
+
* @param {boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown
|
|
1558
|
+
* for unknown options.
|
|
1559
|
+
*/
|
|
1560
|
+
allowUnknownOption(allowUnknown = true) {
|
|
1561
|
+
this._allowUnknownOption = !!allowUnknown;
|
|
1562
|
+
return this;
|
|
1563
|
+
}
|
|
1564
|
+
/**
|
|
1565
|
+
* Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
|
|
1566
|
+
*
|
|
1567
|
+
* @param {boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown
|
|
1568
|
+
* for excess arguments.
|
|
1569
|
+
*/
|
|
1570
|
+
allowExcessArguments(allowExcess = true) {
|
|
1571
|
+
this._allowExcessArguments = !!allowExcess;
|
|
1572
|
+
return this;
|
|
1573
|
+
}
|
|
1574
|
+
/**
|
|
1575
|
+
* Enable positional options. Positional means global options are specified before subcommands which lets
|
|
1576
|
+
* subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
|
|
1577
|
+
* The default behaviour is non-positional and global options may appear anywhere on the command line.
|
|
1578
|
+
*
|
|
1579
|
+
* @param {boolean} [positional=true]
|
|
1580
|
+
*/
|
|
1581
|
+
enablePositionalOptions(positional = true) {
|
|
1582
|
+
this._enablePositionalOptions = !!positional;
|
|
1583
|
+
return this;
|
|
1584
|
+
}
|
|
1585
|
+
/**
|
|
1586
|
+
* Pass through options that come after command-arguments rather than treat them as command-options,
|
|
1587
|
+
* so actual command-options come before command-arguments. Turning this on for a subcommand requires
|
|
1588
|
+
* positional options to have been enabled on the program (parent commands).
|
|
1589
|
+
* The default behaviour is non-positional and options may appear before or after command-arguments.
|
|
1590
|
+
*
|
|
1591
|
+
* @param {boolean} [passThrough=true]
|
|
1592
|
+
* for unknown options.
|
|
1593
|
+
*/
|
|
1594
|
+
passThroughOptions(passThrough = true) {
|
|
1595
|
+
this._passThroughOptions = !!passThrough;
|
|
1596
|
+
this._checkForBrokenPassThrough();
|
|
1597
|
+
return this;
|
|
1598
|
+
}
|
|
1599
|
+
/**
|
|
1600
|
+
* @private
|
|
1601
|
+
*/
|
|
1602
|
+
_checkForBrokenPassThrough() {
|
|
1603
|
+
if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
|
|
1604
|
+
throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
|
|
1605
|
+
}
|
|
1606
|
+
}
|
|
1607
|
+
/**
|
|
1608
|
+
* Whether to store option values as properties on command object,
|
|
1609
|
+
* or store separately (specify false). In both cases the option values can be accessed using .opts().
|
|
1610
|
+
*
|
|
1611
|
+
* @param {boolean} [storeAsProperties=true]
|
|
1612
|
+
* @return {Command} `this` command for chaining
|
|
1613
|
+
*/
|
|
1614
|
+
storeOptionsAsProperties(storeAsProperties = true) {
|
|
1615
|
+
if (this.options.length) {
|
|
1616
|
+
throw new Error("call .storeOptionsAsProperties() before adding options");
|
|
1617
|
+
}
|
|
1618
|
+
if (Object.keys(this._optionValues).length) {
|
|
1619
|
+
throw new Error("call .storeOptionsAsProperties() before setting option values");
|
|
1620
|
+
}
|
|
1621
|
+
this._storeOptionsAsProperties = !!storeAsProperties;
|
|
1622
|
+
return this;
|
|
1623
|
+
}
|
|
1624
|
+
/**
|
|
1625
|
+
* Retrieve option value.
|
|
1626
|
+
*
|
|
1627
|
+
* @param {string} key
|
|
1628
|
+
* @return {Object} value
|
|
1629
|
+
*/
|
|
1630
|
+
getOptionValue(key) {
|
|
1631
|
+
if (this._storeOptionsAsProperties) {
|
|
1632
|
+
return this[key];
|
|
1633
|
+
}
|
|
1634
|
+
return this._optionValues[key];
|
|
1635
|
+
}
|
|
1636
|
+
/**
|
|
1637
|
+
* Store option value.
|
|
1638
|
+
*
|
|
1639
|
+
* @param {string} key
|
|
1640
|
+
* @param {Object} value
|
|
1641
|
+
* @return {Command} `this` command for chaining
|
|
1642
|
+
*/
|
|
1643
|
+
setOptionValue(key, value) {
|
|
1644
|
+
return this.setOptionValueWithSource(key, value, void 0);
|
|
1645
|
+
}
|
|
1646
|
+
/**
|
|
1647
|
+
* Store option value and where the value came from.
|
|
1648
|
+
*
|
|
1649
|
+
* @param {string} key
|
|
1650
|
+
* @param {Object} value
|
|
1651
|
+
* @param {string} source - expected values are default/config/env/cli/implied
|
|
1652
|
+
* @return {Command} `this` command for chaining
|
|
1653
|
+
*/
|
|
1654
|
+
setOptionValueWithSource(key, value, source) {
|
|
1655
|
+
if (this._storeOptionsAsProperties) {
|
|
1656
|
+
this[key] = value;
|
|
1657
|
+
} else {
|
|
1658
|
+
this._optionValues[key] = value;
|
|
1659
|
+
}
|
|
1660
|
+
this._optionValueSources[key] = source;
|
|
1661
|
+
return this;
|
|
1662
|
+
}
|
|
1663
|
+
/**
|
|
1664
|
+
* Get source of option value.
|
|
1665
|
+
* Expected values are default | config | env | cli | implied
|
|
1666
|
+
*
|
|
1667
|
+
* @param {string} key
|
|
1668
|
+
* @return {string}
|
|
1669
|
+
*/
|
|
1670
|
+
getOptionValueSource(key) {
|
|
1671
|
+
return this._optionValueSources[key];
|
|
1672
|
+
}
|
|
1673
|
+
/**
|
|
1674
|
+
* Get source of option value. See also .optsWithGlobals().
|
|
1675
|
+
* Expected values are default | config | env | cli | implied
|
|
1676
|
+
*
|
|
1677
|
+
* @param {string} key
|
|
1678
|
+
* @return {string}
|
|
1679
|
+
*/
|
|
1680
|
+
getOptionValueSourceWithGlobals(key) {
|
|
1681
|
+
let source;
|
|
1682
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
1683
|
+
if (cmd.getOptionValueSource(key) !== void 0) {
|
|
1684
|
+
source = cmd.getOptionValueSource(key);
|
|
1685
|
+
}
|
|
1686
|
+
});
|
|
1687
|
+
return source;
|
|
1688
|
+
}
|
|
1689
|
+
/**
|
|
1690
|
+
* Get user arguments from implied or explicit arguments.
|
|
1691
|
+
* Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
|
|
1692
|
+
*
|
|
1693
|
+
* @private
|
|
1694
|
+
*/
|
|
1695
|
+
_prepareUserArgs(argv, parseOptions) {
|
|
1696
|
+
if (argv !== void 0 && !Array.isArray(argv)) {
|
|
1697
|
+
throw new Error("first parameter to parse must be array or undefined");
|
|
1698
|
+
}
|
|
1699
|
+
parseOptions = parseOptions || {};
|
|
1700
|
+
if (argv === void 0) {
|
|
1701
|
+
argv = process2.argv;
|
|
1702
|
+
if (process2.versions && process2.versions.electron) {
|
|
1703
|
+
parseOptions.from = "electron";
|
|
1704
|
+
}
|
|
1705
|
+
}
|
|
1706
|
+
this.rawArgs = argv.slice();
|
|
1707
|
+
let userArgs;
|
|
1708
|
+
switch (parseOptions.from) {
|
|
1709
|
+
case void 0:
|
|
1710
|
+
case "node":
|
|
1711
|
+
this._scriptPath = argv[1];
|
|
1712
|
+
userArgs = argv.slice(2);
|
|
1713
|
+
break;
|
|
1714
|
+
case "electron":
|
|
1715
|
+
if (process2.defaultApp) {
|
|
1716
|
+
this._scriptPath = argv[1];
|
|
1717
|
+
userArgs = argv.slice(2);
|
|
1718
|
+
} else {
|
|
1719
|
+
userArgs = argv.slice(1);
|
|
1720
|
+
}
|
|
1721
|
+
break;
|
|
1722
|
+
case "user":
|
|
1723
|
+
userArgs = argv.slice(0);
|
|
1724
|
+
break;
|
|
1725
|
+
default:
|
|
1726
|
+
throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
|
|
1727
|
+
}
|
|
1728
|
+
if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);
|
|
1729
|
+
this._name = this._name || "program";
|
|
1730
|
+
return userArgs;
|
|
1731
|
+
}
|
|
1732
|
+
/**
|
|
1733
|
+
* Parse `argv`, setting options and invoking commands when defined.
|
|
1734
|
+
*
|
|
1735
|
+
* The default expectation is that the arguments are from node and have the application as argv[0]
|
|
1736
|
+
* and the script being run in argv[1], with user parameters after that.
|
|
1737
|
+
*
|
|
1738
|
+
* @example
|
|
1739
|
+
* program.parse(process.argv);
|
|
1740
|
+
* program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions
|
|
1741
|
+
* program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
|
|
1742
|
+
*
|
|
1743
|
+
* @param {string[]} [argv] - optional, defaults to process.argv
|
|
1744
|
+
* @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron
|
|
1745
|
+
* @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
|
|
1746
|
+
* @return {Command} `this` command for chaining
|
|
1747
|
+
*/
|
|
1748
|
+
parse(argv, parseOptions) {
|
|
1749
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
1750
|
+
this._parseCommand([], userArgs);
|
|
1751
|
+
return this;
|
|
1752
|
+
}
|
|
1753
|
+
/**
|
|
1754
|
+
* Parse `argv`, setting options and invoking commands when defined.
|
|
1755
|
+
*
|
|
1756
|
+
* Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.
|
|
1757
|
+
*
|
|
1758
|
+
* The default expectation is that the arguments are from node and have the application as argv[0]
|
|
1759
|
+
* and the script being run in argv[1], with user parameters after that.
|
|
1760
|
+
*
|
|
1761
|
+
* @example
|
|
1762
|
+
* await program.parseAsync(process.argv);
|
|
1763
|
+
* await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions
|
|
1764
|
+
* await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
|
|
1765
|
+
*
|
|
1766
|
+
* @param {string[]} [argv]
|
|
1767
|
+
* @param {Object} [parseOptions]
|
|
1768
|
+
* @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
|
|
1769
|
+
* @return {Promise}
|
|
1770
|
+
*/
|
|
1771
|
+
async parseAsync(argv, parseOptions) {
|
|
1772
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
1773
|
+
await this._parseCommand([], userArgs);
|
|
1774
|
+
return this;
|
|
1775
|
+
}
|
|
1776
|
+
/**
|
|
1777
|
+
* Execute a sub-command executable.
|
|
1778
|
+
*
|
|
1779
|
+
* @private
|
|
1780
|
+
*/
|
|
1781
|
+
_executeSubCommand(subcommand, args) {
|
|
1782
|
+
args = args.slice();
|
|
1783
|
+
let launchWithNode = false;
|
|
1784
|
+
const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
|
|
1785
|
+
function findFile(baseDir, baseName) {
|
|
1786
|
+
const localBin = path11.resolve(baseDir, baseName);
|
|
1787
|
+
if (fs9.existsSync(localBin)) return localBin;
|
|
1788
|
+
if (sourceExt.includes(path11.extname(baseName))) return void 0;
|
|
1789
|
+
const foundExt = sourceExt.find((ext) => fs9.existsSync(`${localBin}${ext}`));
|
|
1790
|
+
if (foundExt) return `${localBin}${foundExt}`;
|
|
1791
|
+
return void 0;
|
|
1792
|
+
}
|
|
1793
|
+
this._checkForMissingMandatoryOptions();
|
|
1794
|
+
this._checkForConflictingOptions();
|
|
1795
|
+
let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
|
|
1796
|
+
let executableDir = this._executableDir || "";
|
|
1797
|
+
if (this._scriptPath) {
|
|
1798
|
+
let resolvedScriptPath;
|
|
1799
|
+
try {
|
|
1800
|
+
resolvedScriptPath = fs9.realpathSync(this._scriptPath);
|
|
1801
|
+
} catch (err) {
|
|
1802
|
+
resolvedScriptPath = this._scriptPath;
|
|
1803
|
+
}
|
|
1804
|
+
executableDir = path11.resolve(path11.dirname(resolvedScriptPath), executableDir);
|
|
1805
|
+
}
|
|
1806
|
+
if (executableDir) {
|
|
1807
|
+
let localFile = findFile(executableDir, executableFile);
|
|
1808
|
+
if (!localFile && !subcommand._executableFile && this._scriptPath) {
|
|
1809
|
+
const legacyName = path11.basename(this._scriptPath, path11.extname(this._scriptPath));
|
|
1810
|
+
if (legacyName !== this._name) {
|
|
1811
|
+
localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
|
|
1812
|
+
}
|
|
1813
|
+
}
|
|
1814
|
+
executableFile = localFile || executableFile;
|
|
1815
|
+
}
|
|
1816
|
+
launchWithNode = sourceExt.includes(path11.extname(executableFile));
|
|
1817
|
+
let proc;
|
|
1818
|
+
if (process2.platform !== "win32") {
|
|
1819
|
+
if (launchWithNode) {
|
|
1820
|
+
args.unshift(executableFile);
|
|
1821
|
+
args = incrementNodeInspectorPort(process2.execArgv).concat(args);
|
|
1822
|
+
proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
|
|
1823
|
+
} else {
|
|
1824
|
+
proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
|
|
1825
|
+
}
|
|
1826
|
+
} else {
|
|
1827
|
+
args.unshift(executableFile);
|
|
1828
|
+
args = incrementNodeInspectorPort(process2.execArgv).concat(args);
|
|
1829
|
+
proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
|
|
1830
|
+
}
|
|
1831
|
+
if (!proc.killed) {
|
|
1832
|
+
const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
|
|
1833
|
+
signals.forEach((signal) => {
|
|
1834
|
+
process2.on(signal, () => {
|
|
1835
|
+
if (proc.killed === false && proc.exitCode === null) {
|
|
1836
|
+
proc.kill(signal);
|
|
1837
|
+
}
|
|
1838
|
+
});
|
|
1839
|
+
});
|
|
1840
|
+
}
|
|
1841
|
+
const exitCallback = this._exitCallback;
|
|
1842
|
+
proc.on("close", (code, _signal) => {
|
|
1843
|
+
code = code ?? 1;
|
|
1844
|
+
if (!exitCallback) {
|
|
1845
|
+
process2.exit(code);
|
|
1846
|
+
} else {
|
|
1847
|
+
exitCallback(new CommanderError2(code, "commander.executeSubCommandAsync", "(close)"));
|
|
1848
|
+
}
|
|
1849
|
+
});
|
|
1850
|
+
proc.on("error", (err) => {
|
|
1851
|
+
if (err.code === "ENOENT") {
|
|
1852
|
+
const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
|
|
1853
|
+
const executableMissing = `'${executableFile}' does not exist
|
|
1854
|
+
- if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
1855
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
1856
|
+
- ${executableDirMessage}`;
|
|
1857
|
+
throw new Error(executableMissing);
|
|
1858
|
+
} else if (err.code === "EACCES") {
|
|
1859
|
+
throw new Error(`'${executableFile}' not executable`);
|
|
1860
|
+
}
|
|
1861
|
+
if (!exitCallback) {
|
|
1862
|
+
process2.exit(1);
|
|
1863
|
+
} else {
|
|
1864
|
+
const wrappedError = new CommanderError2(1, "commander.executeSubCommandAsync", "(error)");
|
|
1865
|
+
wrappedError.nestedError = err;
|
|
1866
|
+
exitCallback(wrappedError);
|
|
1867
|
+
}
|
|
1868
|
+
});
|
|
1869
|
+
this.runningCommand = proc;
|
|
1870
|
+
}
|
|
1871
|
+
/**
|
|
1872
|
+
* @private
|
|
1873
|
+
*/
|
|
1874
|
+
_dispatchSubcommand(commandName, operands, unknown) {
|
|
1875
|
+
const subCommand = this._findCommand(commandName);
|
|
1876
|
+
if (!subCommand) this.help({ error: true });
|
|
1877
|
+
let promiseChain;
|
|
1878
|
+
promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
|
|
1879
|
+
promiseChain = this._chainOrCall(promiseChain, () => {
|
|
1880
|
+
if (subCommand._executableHandler) {
|
|
1881
|
+
this._executeSubCommand(subCommand, operands.concat(unknown));
|
|
1882
|
+
} else {
|
|
1883
|
+
return subCommand._parseCommand(operands, unknown);
|
|
1884
|
+
}
|
|
1885
|
+
});
|
|
1886
|
+
return promiseChain;
|
|
1887
|
+
}
|
|
1888
|
+
/**
|
|
1889
|
+
* Invoke help directly if possible, or dispatch if necessary.
|
|
1890
|
+
* e.g. help foo
|
|
1891
|
+
*
|
|
1892
|
+
* @private
|
|
1893
|
+
*/
|
|
1894
|
+
_dispatchHelpCommand(subcommandName) {
|
|
1895
|
+
if (!subcommandName) {
|
|
1896
|
+
this.help();
|
|
1897
|
+
}
|
|
1898
|
+
const subCommand = this._findCommand(subcommandName);
|
|
1899
|
+
if (subCommand && !subCommand._executableHandler) {
|
|
1900
|
+
subCommand.help();
|
|
1901
|
+
}
|
|
1902
|
+
return this._dispatchSubcommand(subcommandName, [], [
|
|
1903
|
+
this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"
|
|
1904
|
+
]);
|
|
1905
|
+
}
|
|
1906
|
+
/**
|
|
1907
|
+
* Check this.args against expected this.registeredArguments.
|
|
1908
|
+
*
|
|
1909
|
+
* @private
|
|
1910
|
+
*/
|
|
1911
|
+
_checkNumberOfArguments() {
|
|
1912
|
+
this.registeredArguments.forEach((arg, i) => {
|
|
1913
|
+
if (arg.required && this.args[i] == null) {
|
|
1914
|
+
this.missingArgument(arg.name());
|
|
1915
|
+
}
|
|
1916
|
+
});
|
|
1917
|
+
if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
|
|
1918
|
+
return;
|
|
1919
|
+
}
|
|
1920
|
+
if (this.args.length > this.registeredArguments.length) {
|
|
1921
|
+
this._excessArguments(this.args);
|
|
1922
|
+
}
|
|
1923
|
+
}
|
|
1924
|
+
/**
|
|
1925
|
+
* Process this.args using this.registeredArguments and save as this.processedArgs!
|
|
1926
|
+
*
|
|
1927
|
+
* @private
|
|
1928
|
+
*/
|
|
1929
|
+
_processArguments() {
|
|
1930
|
+
const myParseArg = (argument, value, previous) => {
|
|
1931
|
+
let parsedValue = value;
|
|
1932
|
+
if (value !== null && argument.parseArg) {
|
|
1933
|
+
const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
|
|
1934
|
+
parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
|
|
1935
|
+
}
|
|
1936
|
+
return parsedValue;
|
|
1937
|
+
};
|
|
1938
|
+
this._checkNumberOfArguments();
|
|
1939
|
+
const processedArgs = [];
|
|
1940
|
+
this.registeredArguments.forEach((declaredArg, index) => {
|
|
1941
|
+
let value = declaredArg.defaultValue;
|
|
1942
|
+
if (declaredArg.variadic) {
|
|
1943
|
+
if (index < this.args.length) {
|
|
1944
|
+
value = this.args.slice(index);
|
|
1945
|
+
if (declaredArg.parseArg) {
|
|
1946
|
+
value = value.reduce((processed, v) => {
|
|
1947
|
+
return myParseArg(declaredArg, v, processed);
|
|
1948
|
+
}, declaredArg.defaultValue);
|
|
1949
|
+
}
|
|
1950
|
+
} else if (value === void 0) {
|
|
1951
|
+
value = [];
|
|
1952
|
+
}
|
|
1953
|
+
} else if (index < this.args.length) {
|
|
1954
|
+
value = this.args[index];
|
|
1955
|
+
if (declaredArg.parseArg) {
|
|
1956
|
+
value = myParseArg(declaredArg, value, declaredArg.defaultValue);
|
|
1957
|
+
}
|
|
1958
|
+
}
|
|
1959
|
+
processedArgs[index] = value;
|
|
1960
|
+
});
|
|
1961
|
+
this.processedArgs = processedArgs;
|
|
1962
|
+
}
|
|
1963
|
+
/**
|
|
1964
|
+
* Once we have a promise we chain, but call synchronously until then.
|
|
1965
|
+
*
|
|
1966
|
+
* @param {(Promise|undefined)} promise
|
|
1967
|
+
* @param {Function} fn
|
|
1968
|
+
* @return {(Promise|undefined)}
|
|
1969
|
+
* @private
|
|
1970
|
+
*/
|
|
1971
|
+
_chainOrCall(promise, fn) {
|
|
1972
|
+
if (promise && promise.then && typeof promise.then === "function") {
|
|
1973
|
+
return promise.then(() => fn());
|
|
1974
|
+
}
|
|
1975
|
+
return fn();
|
|
1976
|
+
}
|
|
1977
|
+
/**
|
|
1978
|
+
*
|
|
1979
|
+
* @param {(Promise|undefined)} promise
|
|
1980
|
+
* @param {string} event
|
|
1981
|
+
* @return {(Promise|undefined)}
|
|
1982
|
+
* @private
|
|
1983
|
+
*/
|
|
1984
|
+
_chainOrCallHooks(promise, event) {
|
|
1985
|
+
let result = promise;
|
|
1986
|
+
const hooks = [];
|
|
1987
|
+
this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
|
|
1988
|
+
hookedCommand._lifeCycleHooks[event].forEach((callback) => {
|
|
1989
|
+
hooks.push({ hookedCommand, callback });
|
|
1990
|
+
});
|
|
1991
|
+
});
|
|
1992
|
+
if (event === "postAction") {
|
|
1993
|
+
hooks.reverse();
|
|
1994
|
+
}
|
|
1995
|
+
hooks.forEach((hookDetail) => {
|
|
1996
|
+
result = this._chainOrCall(result, () => {
|
|
1997
|
+
return hookDetail.callback(hookDetail.hookedCommand, this);
|
|
1998
|
+
});
|
|
1999
|
+
});
|
|
2000
|
+
return result;
|
|
2001
|
+
}
|
|
2002
|
+
/**
|
|
2003
|
+
*
|
|
2004
|
+
* @param {(Promise|undefined)} promise
|
|
2005
|
+
* @param {Command} subCommand
|
|
2006
|
+
* @param {string} event
|
|
2007
|
+
* @return {(Promise|undefined)}
|
|
2008
|
+
* @private
|
|
2009
|
+
*/
|
|
2010
|
+
_chainOrCallSubCommandHook(promise, subCommand, event) {
|
|
2011
|
+
let result = promise;
|
|
2012
|
+
if (this._lifeCycleHooks[event] !== void 0) {
|
|
2013
|
+
this._lifeCycleHooks[event].forEach((hook) => {
|
|
2014
|
+
result = this._chainOrCall(result, () => {
|
|
2015
|
+
return hook(this, subCommand);
|
|
2016
|
+
});
|
|
2017
|
+
});
|
|
2018
|
+
}
|
|
2019
|
+
return result;
|
|
2020
|
+
}
|
|
2021
|
+
/**
|
|
2022
|
+
* Process arguments in context of this command.
|
|
2023
|
+
* Returns action result, in case it is a promise.
|
|
2024
|
+
*
|
|
2025
|
+
* @private
|
|
2026
|
+
*/
|
|
2027
|
+
_parseCommand(operands, unknown) {
|
|
2028
|
+
const parsed = this.parseOptions(unknown);
|
|
2029
|
+
this._parseOptionsEnv();
|
|
2030
|
+
this._parseOptionsImplied();
|
|
2031
|
+
operands = operands.concat(parsed.operands);
|
|
2032
|
+
unknown = parsed.unknown;
|
|
2033
|
+
this.args = operands.concat(unknown);
|
|
2034
|
+
if (operands && this._findCommand(operands[0])) {
|
|
2035
|
+
return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
|
|
2036
|
+
}
|
|
2037
|
+
if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
|
|
2038
|
+
return this._dispatchHelpCommand(operands[1]);
|
|
2039
|
+
}
|
|
2040
|
+
if (this._defaultCommandName) {
|
|
2041
|
+
this._outputHelpIfRequested(unknown);
|
|
2042
|
+
return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
|
|
2043
|
+
}
|
|
2044
|
+
if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
|
|
2045
|
+
this.help({ error: true });
|
|
2046
|
+
}
|
|
2047
|
+
this._outputHelpIfRequested(parsed.unknown);
|
|
2048
|
+
this._checkForMissingMandatoryOptions();
|
|
2049
|
+
this._checkForConflictingOptions();
|
|
2050
|
+
const checkForUnknownOptions = () => {
|
|
2051
|
+
if (parsed.unknown.length > 0) {
|
|
2052
|
+
this.unknownOption(parsed.unknown[0]);
|
|
2053
|
+
}
|
|
2054
|
+
};
|
|
2055
|
+
const commandEvent = `command:${this.name()}`;
|
|
2056
|
+
if (this._actionHandler) {
|
|
2057
|
+
checkForUnknownOptions();
|
|
2058
|
+
this._processArguments();
|
|
2059
|
+
let promiseChain;
|
|
2060
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
|
|
2061
|
+
promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
|
|
2062
|
+
if (this.parent) {
|
|
2063
|
+
promiseChain = this._chainOrCall(promiseChain, () => {
|
|
2064
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
2065
|
+
});
|
|
2066
|
+
}
|
|
2067
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
|
|
2068
|
+
return promiseChain;
|
|
2069
|
+
}
|
|
2070
|
+
if (this.parent && this.parent.listenerCount(commandEvent)) {
|
|
2071
|
+
checkForUnknownOptions();
|
|
2072
|
+
this._processArguments();
|
|
2073
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
2074
|
+
} else if (operands.length) {
|
|
2075
|
+
if (this._findCommand("*")) {
|
|
2076
|
+
return this._dispatchSubcommand("*", operands, unknown);
|
|
2077
|
+
}
|
|
2078
|
+
if (this.listenerCount("command:*")) {
|
|
2079
|
+
this.emit("command:*", operands, unknown);
|
|
2080
|
+
} else if (this.commands.length) {
|
|
2081
|
+
this.unknownCommand();
|
|
2082
|
+
} else {
|
|
2083
|
+
checkForUnknownOptions();
|
|
2084
|
+
this._processArguments();
|
|
2085
|
+
}
|
|
2086
|
+
} else if (this.commands.length) {
|
|
2087
|
+
checkForUnknownOptions();
|
|
2088
|
+
this.help({ error: true });
|
|
2089
|
+
} else {
|
|
2090
|
+
checkForUnknownOptions();
|
|
2091
|
+
this._processArguments();
|
|
2092
|
+
}
|
|
2093
|
+
}
|
|
2094
|
+
/**
|
|
2095
|
+
* Find matching command.
|
|
2096
|
+
*
|
|
2097
|
+
* @private
|
|
2098
|
+
*/
|
|
2099
|
+
_findCommand(name) {
|
|
2100
|
+
if (!name) return void 0;
|
|
2101
|
+
return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
|
|
2102
|
+
}
|
|
2103
|
+
/**
|
|
2104
|
+
* Return an option matching `arg` if any.
|
|
2105
|
+
*
|
|
2106
|
+
* @param {string} arg
|
|
2107
|
+
* @return {Option}
|
|
2108
|
+
* @package internal use only
|
|
2109
|
+
*/
|
|
2110
|
+
_findOption(arg) {
|
|
2111
|
+
return this.options.find((option) => option.is(arg));
|
|
2112
|
+
}
|
|
2113
|
+
/**
|
|
2114
|
+
* Display an error message if a mandatory option does not have a value.
|
|
2115
|
+
* Called after checking for help flags in leaf subcommand.
|
|
2116
|
+
*
|
|
2117
|
+
* @private
|
|
2118
|
+
*/
|
|
2119
|
+
_checkForMissingMandatoryOptions() {
|
|
2120
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
2121
|
+
cmd.options.forEach((anOption) => {
|
|
2122
|
+
if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
|
|
2123
|
+
cmd.missingMandatoryOptionValue(anOption);
|
|
2124
|
+
}
|
|
2125
|
+
});
|
|
2126
|
+
});
|
|
2127
|
+
}
|
|
2128
|
+
/**
|
|
2129
|
+
* Display an error message if conflicting options are used together in this.
|
|
2130
|
+
*
|
|
2131
|
+
* @private
|
|
2132
|
+
*/
|
|
2133
|
+
_checkForConflictingLocalOptions() {
|
|
2134
|
+
const definedNonDefaultOptions = this.options.filter(
|
|
2135
|
+
(option) => {
|
|
2136
|
+
const optionKey = option.attributeName();
|
|
2137
|
+
if (this.getOptionValue(optionKey) === void 0) {
|
|
2138
|
+
return false;
|
|
2139
|
+
}
|
|
2140
|
+
return this.getOptionValueSource(optionKey) !== "default";
|
|
2141
|
+
}
|
|
2142
|
+
);
|
|
2143
|
+
const optionsWithConflicting = definedNonDefaultOptions.filter(
|
|
2144
|
+
(option) => option.conflictsWith.length > 0
|
|
2145
|
+
);
|
|
2146
|
+
optionsWithConflicting.forEach((option) => {
|
|
2147
|
+
const conflictingAndDefined = definedNonDefaultOptions.find(
|
|
2148
|
+
(defined) => option.conflictsWith.includes(defined.attributeName())
|
|
2149
|
+
);
|
|
2150
|
+
if (conflictingAndDefined) {
|
|
2151
|
+
this._conflictingOption(option, conflictingAndDefined);
|
|
2152
|
+
}
|
|
2153
|
+
});
|
|
2154
|
+
}
|
|
2155
|
+
/**
|
|
2156
|
+
* Display an error message if conflicting options are used together.
|
|
2157
|
+
* Called after checking for help flags in leaf subcommand.
|
|
2158
|
+
*
|
|
2159
|
+
* @private
|
|
2160
|
+
*/
|
|
2161
|
+
_checkForConflictingOptions() {
|
|
2162
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
2163
|
+
cmd._checkForConflictingLocalOptions();
|
|
2164
|
+
});
|
|
2165
|
+
}
|
|
2166
|
+
/**
|
|
2167
|
+
* Parse options from `argv` removing known options,
|
|
2168
|
+
* and return argv split into operands and unknown arguments.
|
|
2169
|
+
*
|
|
2170
|
+
* Examples:
|
|
2171
|
+
*
|
|
2172
|
+
* argv => operands, unknown
|
|
2173
|
+
* --known kkk op => [op], []
|
|
2174
|
+
* op --known kkk => [op], []
|
|
2175
|
+
* sub --unknown uuu op => [sub], [--unknown uuu op]
|
|
2176
|
+
* sub -- --unknown uuu op => [sub --unknown uuu op], []
|
|
2177
|
+
*
|
|
2178
|
+
* @param {string[]} argv
|
|
2179
|
+
* @return {{operands: string[], unknown: string[]}}
|
|
2180
|
+
*/
|
|
2181
|
+
parseOptions(argv) {
|
|
2182
|
+
const operands = [];
|
|
2183
|
+
const unknown = [];
|
|
2184
|
+
let dest = operands;
|
|
2185
|
+
const args = argv.slice();
|
|
2186
|
+
function maybeOption(arg) {
|
|
2187
|
+
return arg.length > 1 && arg[0] === "-";
|
|
2188
|
+
}
|
|
2189
|
+
let activeVariadicOption = null;
|
|
2190
|
+
while (args.length) {
|
|
2191
|
+
const arg = args.shift();
|
|
2192
|
+
if (arg === "--") {
|
|
2193
|
+
if (dest === unknown) dest.push(arg);
|
|
2194
|
+
dest.push(...args);
|
|
2195
|
+
break;
|
|
2196
|
+
}
|
|
2197
|
+
if (activeVariadicOption && !maybeOption(arg)) {
|
|
2198
|
+
this.emit(`option:${activeVariadicOption.name()}`, arg);
|
|
2199
|
+
continue;
|
|
2200
|
+
}
|
|
2201
|
+
activeVariadicOption = null;
|
|
2202
|
+
if (maybeOption(arg)) {
|
|
2203
|
+
const option = this._findOption(arg);
|
|
2204
|
+
if (option) {
|
|
2205
|
+
if (option.required) {
|
|
2206
|
+
const value = args.shift();
|
|
2207
|
+
if (value === void 0) this.optionMissingArgument(option);
|
|
2208
|
+
this.emit(`option:${option.name()}`, value);
|
|
2209
|
+
} else if (option.optional) {
|
|
2210
|
+
let value = null;
|
|
2211
|
+
if (args.length > 0 && !maybeOption(args[0])) {
|
|
2212
|
+
value = args.shift();
|
|
2213
|
+
}
|
|
2214
|
+
this.emit(`option:${option.name()}`, value);
|
|
2215
|
+
} else {
|
|
2216
|
+
this.emit(`option:${option.name()}`);
|
|
2217
|
+
}
|
|
2218
|
+
activeVariadicOption = option.variadic ? option : null;
|
|
2219
|
+
continue;
|
|
2220
|
+
}
|
|
2221
|
+
}
|
|
2222
|
+
if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
|
|
2223
|
+
const option = this._findOption(`-${arg[1]}`);
|
|
2224
|
+
if (option) {
|
|
2225
|
+
if (option.required || option.optional && this._combineFlagAndOptionalValue) {
|
|
2226
|
+
this.emit(`option:${option.name()}`, arg.slice(2));
|
|
2227
|
+
} else {
|
|
2228
|
+
this.emit(`option:${option.name()}`);
|
|
2229
|
+
args.unshift(`-${arg.slice(2)}`);
|
|
2230
|
+
}
|
|
2231
|
+
continue;
|
|
2232
|
+
}
|
|
2233
|
+
}
|
|
2234
|
+
if (/^--[^=]+=/.test(arg)) {
|
|
2235
|
+
const index = arg.indexOf("=");
|
|
2236
|
+
const option = this._findOption(arg.slice(0, index));
|
|
2237
|
+
if (option && (option.required || option.optional)) {
|
|
2238
|
+
this.emit(`option:${option.name()}`, arg.slice(index + 1));
|
|
2239
|
+
continue;
|
|
2240
|
+
}
|
|
2241
|
+
}
|
|
2242
|
+
if (maybeOption(arg)) {
|
|
2243
|
+
dest = unknown;
|
|
2244
|
+
}
|
|
2245
|
+
if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
|
|
2246
|
+
if (this._findCommand(arg)) {
|
|
2247
|
+
operands.push(arg);
|
|
2248
|
+
if (args.length > 0) unknown.push(...args);
|
|
2249
|
+
break;
|
|
2250
|
+
} else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
|
|
2251
|
+
operands.push(arg);
|
|
2252
|
+
if (args.length > 0) operands.push(...args);
|
|
2253
|
+
break;
|
|
2254
|
+
} else if (this._defaultCommandName) {
|
|
2255
|
+
unknown.push(arg);
|
|
2256
|
+
if (args.length > 0) unknown.push(...args);
|
|
2257
|
+
break;
|
|
2258
|
+
}
|
|
2259
|
+
}
|
|
2260
|
+
if (this._passThroughOptions) {
|
|
2261
|
+
dest.push(arg);
|
|
2262
|
+
if (args.length > 0) dest.push(...args);
|
|
2263
|
+
break;
|
|
2264
|
+
}
|
|
2265
|
+
dest.push(arg);
|
|
2266
|
+
}
|
|
2267
|
+
return { operands, unknown };
|
|
2268
|
+
}
|
|
2269
|
+
/**
|
|
2270
|
+
* Return an object containing local option values as key-value pairs.
|
|
2271
|
+
*
|
|
2272
|
+
* @return {Object}
|
|
2273
|
+
*/
|
|
2274
|
+
opts() {
|
|
2275
|
+
if (this._storeOptionsAsProperties) {
|
|
2276
|
+
const result = {};
|
|
2277
|
+
const len = this.options.length;
|
|
2278
|
+
for (let i = 0; i < len; i++) {
|
|
2279
|
+
const key = this.options[i].attributeName();
|
|
2280
|
+
result[key] = key === this._versionOptionName ? this._version : this[key];
|
|
2281
|
+
}
|
|
2282
|
+
return result;
|
|
2283
|
+
}
|
|
2284
|
+
return this._optionValues;
|
|
2285
|
+
}
|
|
2286
|
+
/**
|
|
2287
|
+
* Return an object containing merged local and global option values as key-value pairs.
|
|
2288
|
+
*
|
|
2289
|
+
* @return {Object}
|
|
2290
|
+
*/
|
|
2291
|
+
optsWithGlobals() {
|
|
2292
|
+
return this._getCommandAndAncestors().reduce(
|
|
2293
|
+
(combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
|
|
2294
|
+
{}
|
|
2295
|
+
);
|
|
2296
|
+
}
|
|
2297
|
+
/**
|
|
2298
|
+
* Display error message and exit (or call exitOverride).
|
|
2299
|
+
*
|
|
2300
|
+
* @param {string} message
|
|
2301
|
+
* @param {Object} [errorOptions]
|
|
2302
|
+
* @param {string} [errorOptions.code] - an id string representing the error
|
|
2303
|
+
* @param {number} [errorOptions.exitCode] - used with process.exit
|
|
2304
|
+
*/
|
|
2305
|
+
error(message, errorOptions) {
|
|
2306
|
+
this._outputConfiguration.outputError(`${message}
|
|
2307
|
+
`, this._outputConfiguration.writeErr);
|
|
2308
|
+
if (typeof this._showHelpAfterError === "string") {
|
|
2309
|
+
this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
2310
|
+
`);
|
|
2311
|
+
} else if (this._showHelpAfterError) {
|
|
2312
|
+
this._outputConfiguration.writeErr("\n");
|
|
2313
|
+
this.outputHelp({ error: true });
|
|
2314
|
+
}
|
|
2315
|
+
const config = errorOptions || {};
|
|
2316
|
+
const exitCode = config.exitCode || 1;
|
|
2317
|
+
const code = config.code || "commander.error";
|
|
2318
|
+
this._exit(exitCode, code, message);
|
|
2319
|
+
}
|
|
2320
|
+
/**
|
|
2321
|
+
* Apply any option related environment variables, if option does
|
|
2322
|
+
* not have a value from cli or client code.
|
|
2323
|
+
*
|
|
2324
|
+
* @private
|
|
2325
|
+
*/
|
|
2326
|
+
_parseOptionsEnv() {
|
|
2327
|
+
this.options.forEach((option) => {
|
|
2328
|
+
if (option.envVar && option.envVar in process2.env) {
|
|
2329
|
+
const optionKey = option.attributeName();
|
|
2330
|
+
if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
|
|
2331
|
+
if (option.required || option.optional) {
|
|
2332
|
+
this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
|
|
2333
|
+
} else {
|
|
2334
|
+
this.emit(`optionEnv:${option.name()}`);
|
|
2335
|
+
}
|
|
2336
|
+
}
|
|
2337
|
+
}
|
|
2338
|
+
});
|
|
2339
|
+
}
|
|
2340
|
+
/**
|
|
2341
|
+
* Apply any implied option values, if option is undefined or default value.
|
|
2342
|
+
*
|
|
2343
|
+
* @private
|
|
2344
|
+
*/
|
|
2345
|
+
_parseOptionsImplied() {
|
|
2346
|
+
const dualHelper = new DualOptions(this.options);
|
|
2347
|
+
const hasCustomOptionValue = (optionKey) => {
|
|
2348
|
+
return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
|
|
2349
|
+
};
|
|
2350
|
+
this.options.filter((option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
|
|
2351
|
+
Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
|
|
2352
|
+
this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
|
|
2353
|
+
});
|
|
2354
|
+
});
|
|
2355
|
+
}
|
|
2356
|
+
/**
|
|
2357
|
+
* Argument `name` is missing.
|
|
2358
|
+
*
|
|
2359
|
+
* @param {string} name
|
|
2360
|
+
* @private
|
|
2361
|
+
*/
|
|
2362
|
+
missingArgument(name) {
|
|
2363
|
+
const message = `error: missing required argument '${name}'`;
|
|
2364
|
+
this.error(message, { code: "commander.missingArgument" });
|
|
2365
|
+
}
|
|
2366
|
+
/**
|
|
2367
|
+
* `Option` is missing an argument.
|
|
2368
|
+
*
|
|
2369
|
+
* @param {Option} option
|
|
2370
|
+
* @private
|
|
2371
|
+
*/
|
|
2372
|
+
optionMissingArgument(option) {
|
|
2373
|
+
const message = `error: option '${option.flags}' argument missing`;
|
|
2374
|
+
this.error(message, { code: "commander.optionMissingArgument" });
|
|
2375
|
+
}
|
|
2376
|
+
/**
|
|
2377
|
+
* `Option` does not have a value, and is a mandatory option.
|
|
2378
|
+
*
|
|
2379
|
+
* @param {Option} option
|
|
2380
|
+
* @private
|
|
2381
|
+
*/
|
|
2382
|
+
missingMandatoryOptionValue(option) {
|
|
2383
|
+
const message = `error: required option '${option.flags}' not specified`;
|
|
2384
|
+
this.error(message, { code: "commander.missingMandatoryOptionValue" });
|
|
2385
|
+
}
|
|
2386
|
+
/**
|
|
2387
|
+
* `Option` conflicts with another option.
|
|
2388
|
+
*
|
|
2389
|
+
* @param {Option} option
|
|
2390
|
+
* @param {Option} conflictingOption
|
|
2391
|
+
* @private
|
|
2392
|
+
*/
|
|
2393
|
+
_conflictingOption(option, conflictingOption) {
|
|
2394
|
+
const findBestOptionFromValue = (option2) => {
|
|
2395
|
+
const optionKey = option2.attributeName();
|
|
2396
|
+
const optionValue = this.getOptionValue(optionKey);
|
|
2397
|
+
const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
|
|
2398
|
+
const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
|
|
2399
|
+
if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
|
|
2400
|
+
return negativeOption;
|
|
2401
|
+
}
|
|
2402
|
+
return positiveOption || option2;
|
|
2403
|
+
};
|
|
2404
|
+
const getErrorMessage = (option2) => {
|
|
2405
|
+
const bestOption = findBestOptionFromValue(option2);
|
|
2406
|
+
const optionKey = bestOption.attributeName();
|
|
2407
|
+
const source = this.getOptionValueSource(optionKey);
|
|
2408
|
+
if (source === "env") {
|
|
2409
|
+
return `environment variable '${bestOption.envVar}'`;
|
|
2410
|
+
}
|
|
2411
|
+
return `option '${bestOption.flags}'`;
|
|
2412
|
+
};
|
|
2413
|
+
const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
|
|
2414
|
+
this.error(message, { code: "commander.conflictingOption" });
|
|
2415
|
+
}
|
|
2416
|
+
/**
|
|
2417
|
+
* Unknown option `flag`.
|
|
2418
|
+
*
|
|
2419
|
+
* @param {string} flag
|
|
2420
|
+
* @private
|
|
2421
|
+
*/
|
|
2422
|
+
unknownOption(flag) {
|
|
2423
|
+
if (this._allowUnknownOption) return;
|
|
2424
|
+
let suggestion = "";
|
|
2425
|
+
if (flag.startsWith("--") && this._showSuggestionAfterError) {
|
|
2426
|
+
let candidateFlags = [];
|
|
2427
|
+
let command = this;
|
|
2428
|
+
do {
|
|
2429
|
+
const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
|
|
2430
|
+
candidateFlags = candidateFlags.concat(moreFlags);
|
|
2431
|
+
command = command.parent;
|
|
2432
|
+
} while (command && !command._enablePositionalOptions);
|
|
2433
|
+
suggestion = suggestSimilar(flag, candidateFlags);
|
|
2434
|
+
}
|
|
2435
|
+
const message = `error: unknown option '${flag}'${suggestion}`;
|
|
2436
|
+
this.error(message, { code: "commander.unknownOption" });
|
|
2437
|
+
}
|
|
2438
|
+
/**
|
|
2439
|
+
* Excess arguments, more than expected.
|
|
2440
|
+
*
|
|
2441
|
+
* @param {string[]} receivedArgs
|
|
2442
|
+
* @private
|
|
2443
|
+
*/
|
|
2444
|
+
_excessArguments(receivedArgs) {
|
|
2445
|
+
if (this._allowExcessArguments) return;
|
|
2446
|
+
const expected = this.registeredArguments.length;
|
|
2447
|
+
const s = expected === 1 ? "" : "s";
|
|
2448
|
+
const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
|
|
2449
|
+
const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
|
|
2450
|
+
this.error(message, { code: "commander.excessArguments" });
|
|
2451
|
+
}
|
|
2452
|
+
/**
|
|
2453
|
+
* Unknown command.
|
|
2454
|
+
*
|
|
2455
|
+
* @private
|
|
2456
|
+
*/
|
|
2457
|
+
unknownCommand() {
|
|
2458
|
+
const unknownName = this.args[0];
|
|
2459
|
+
let suggestion = "";
|
|
2460
|
+
if (this._showSuggestionAfterError) {
|
|
2461
|
+
const candidateNames = [];
|
|
2462
|
+
this.createHelp().visibleCommands(this).forEach((command) => {
|
|
2463
|
+
candidateNames.push(command.name());
|
|
2464
|
+
if (command.alias()) candidateNames.push(command.alias());
|
|
2465
|
+
});
|
|
2466
|
+
suggestion = suggestSimilar(unknownName, candidateNames);
|
|
2467
|
+
}
|
|
2468
|
+
const message = `error: unknown command '${unknownName}'${suggestion}`;
|
|
2469
|
+
this.error(message, { code: "commander.unknownCommand" });
|
|
2470
|
+
}
|
|
2471
|
+
/**
|
|
2472
|
+
* Get or set the program version.
|
|
2473
|
+
*
|
|
2474
|
+
* This method auto-registers the "-V, --version" option which will print the version number.
|
|
2475
|
+
*
|
|
2476
|
+
* You can optionally supply the flags and description to override the defaults.
|
|
2477
|
+
*
|
|
2478
|
+
* @param {string} [str]
|
|
2479
|
+
* @param {string} [flags]
|
|
2480
|
+
* @param {string} [description]
|
|
2481
|
+
* @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
|
|
2482
|
+
*/
|
|
2483
|
+
version(str, flags, description) {
|
|
2484
|
+
if (str === void 0) return this._version;
|
|
2485
|
+
this._version = str;
|
|
2486
|
+
flags = flags || "-V, --version";
|
|
2487
|
+
description = description || "output the version number";
|
|
2488
|
+
const versionOption = this.createOption(flags, description);
|
|
2489
|
+
this._versionOptionName = versionOption.attributeName();
|
|
2490
|
+
this._registerOption(versionOption);
|
|
2491
|
+
this.on("option:" + versionOption.name(), () => {
|
|
2492
|
+
this._outputConfiguration.writeOut(`${str}
|
|
2493
|
+
`);
|
|
2494
|
+
this._exit(0, "commander.version", str);
|
|
2495
|
+
});
|
|
2496
|
+
return this;
|
|
2497
|
+
}
|
|
2498
|
+
/**
|
|
2499
|
+
* Set the description.
|
|
2500
|
+
*
|
|
2501
|
+
* @param {string} [str]
|
|
2502
|
+
* @param {Object} [argsDescription]
|
|
2503
|
+
* @return {(string|Command)}
|
|
2504
|
+
*/
|
|
2505
|
+
description(str, argsDescription) {
|
|
2506
|
+
if (str === void 0 && argsDescription === void 0) return this._description;
|
|
2507
|
+
this._description = str;
|
|
2508
|
+
if (argsDescription) {
|
|
2509
|
+
this._argsDescription = argsDescription;
|
|
2510
|
+
}
|
|
2511
|
+
return this;
|
|
2512
|
+
}
|
|
2513
|
+
/**
|
|
2514
|
+
* Set the summary. Used when listed as subcommand of parent.
|
|
2515
|
+
*
|
|
2516
|
+
* @param {string} [str]
|
|
2517
|
+
* @return {(string|Command)}
|
|
2518
|
+
*/
|
|
2519
|
+
summary(str) {
|
|
2520
|
+
if (str === void 0) return this._summary;
|
|
2521
|
+
this._summary = str;
|
|
2522
|
+
return this;
|
|
2523
|
+
}
|
|
2524
|
+
/**
|
|
2525
|
+
* Set an alias for the command.
|
|
2526
|
+
*
|
|
2527
|
+
* You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
|
|
2528
|
+
*
|
|
2529
|
+
* @param {string} [alias]
|
|
2530
|
+
* @return {(string|Command)}
|
|
2531
|
+
*/
|
|
2532
|
+
alias(alias) {
|
|
2533
|
+
if (alias === void 0) return this._aliases[0];
|
|
2534
|
+
let command = this;
|
|
2535
|
+
if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
|
|
2536
|
+
command = this.commands[this.commands.length - 1];
|
|
2537
|
+
}
|
|
2538
|
+
if (alias === command._name) throw new Error("Command alias can't be the same as its name");
|
|
2539
|
+
const matchingCommand = this.parent?._findCommand(alias);
|
|
2540
|
+
if (matchingCommand) {
|
|
2541
|
+
const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
|
|
2542
|
+
throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
|
|
2543
|
+
}
|
|
2544
|
+
command._aliases.push(alias);
|
|
2545
|
+
return this;
|
|
2546
|
+
}
|
|
2547
|
+
/**
|
|
2548
|
+
* Set aliases for the command.
|
|
2549
|
+
*
|
|
2550
|
+
* Only the first alias is shown in the auto-generated help.
|
|
2551
|
+
*
|
|
2552
|
+
* @param {string[]} [aliases]
|
|
2553
|
+
* @return {(string[]|Command)}
|
|
2554
|
+
*/
|
|
2555
|
+
aliases(aliases) {
|
|
2556
|
+
if (aliases === void 0) return this._aliases;
|
|
2557
|
+
aliases.forEach((alias) => this.alias(alias));
|
|
2558
|
+
return this;
|
|
2559
|
+
}
|
|
2560
|
+
/**
|
|
2561
|
+
* Set / get the command usage `str`.
|
|
2562
|
+
*
|
|
2563
|
+
* @param {string} [str]
|
|
2564
|
+
* @return {(string|Command)}
|
|
2565
|
+
*/
|
|
2566
|
+
usage(str) {
|
|
2567
|
+
if (str === void 0) {
|
|
2568
|
+
if (this._usage) return this._usage;
|
|
2569
|
+
const args = this.registeredArguments.map((arg) => {
|
|
2570
|
+
return humanReadableArgName(arg);
|
|
2571
|
+
});
|
|
2572
|
+
return [].concat(
|
|
2573
|
+
this.options.length || this._helpOption !== null ? "[options]" : [],
|
|
2574
|
+
this.commands.length ? "[command]" : [],
|
|
2575
|
+
this.registeredArguments.length ? args : []
|
|
2576
|
+
).join(" ");
|
|
2577
|
+
}
|
|
2578
|
+
this._usage = str;
|
|
2579
|
+
return this;
|
|
2580
|
+
}
|
|
2581
|
+
/**
|
|
2582
|
+
* Get or set the name of the command.
|
|
2583
|
+
*
|
|
2584
|
+
* @param {string} [str]
|
|
2585
|
+
* @return {(string|Command)}
|
|
2586
|
+
*/
|
|
2587
|
+
name(str) {
|
|
2588
|
+
if (str === void 0) return this._name;
|
|
2589
|
+
this._name = str;
|
|
2590
|
+
return this;
|
|
2591
|
+
}
|
|
2592
|
+
/**
|
|
2593
|
+
* Set the name of the command from script filename, such as process.argv[1],
|
|
2594
|
+
* or require.main.filename, or __filename.
|
|
2595
|
+
*
|
|
2596
|
+
* (Used internally and public although not documented in README.)
|
|
2597
|
+
*
|
|
2598
|
+
* @example
|
|
2599
|
+
* program.nameFromFilename(require.main.filename);
|
|
2600
|
+
*
|
|
2601
|
+
* @param {string} filename
|
|
2602
|
+
* @return {Command}
|
|
2603
|
+
*/
|
|
2604
|
+
nameFromFilename(filename) {
|
|
2605
|
+
this._name = path11.basename(filename, path11.extname(filename));
|
|
2606
|
+
return this;
|
|
2607
|
+
}
|
|
2608
|
+
/**
|
|
2609
|
+
* Get or set the directory for searching for executable subcommands of this command.
|
|
2610
|
+
*
|
|
2611
|
+
* @example
|
|
2612
|
+
* program.executableDir(__dirname);
|
|
2613
|
+
* // or
|
|
2614
|
+
* program.executableDir('subcommands');
|
|
2615
|
+
*
|
|
2616
|
+
* @param {string} [path]
|
|
2617
|
+
* @return {(string|null|Command)}
|
|
2618
|
+
*/
|
|
2619
|
+
executableDir(path12) {
|
|
2620
|
+
if (path12 === void 0) return this._executableDir;
|
|
2621
|
+
this._executableDir = path12;
|
|
2622
|
+
return this;
|
|
2623
|
+
}
|
|
2624
|
+
/**
|
|
2625
|
+
* Return program help documentation.
|
|
2626
|
+
*
|
|
2627
|
+
* @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
|
|
2628
|
+
* @return {string}
|
|
2629
|
+
*/
|
|
2630
|
+
helpInformation(contextOptions) {
|
|
2631
|
+
const helper = this.createHelp();
|
|
2632
|
+
if (helper.helpWidth === void 0) {
|
|
2633
|
+
helper.helpWidth = contextOptions && contextOptions.error ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
|
|
2634
|
+
}
|
|
2635
|
+
return helper.formatHelp(this, helper);
|
|
2636
|
+
}
|
|
2637
|
+
/**
|
|
2638
|
+
* @private
|
|
2639
|
+
*/
|
|
2640
|
+
_getHelpContext(contextOptions) {
|
|
2641
|
+
contextOptions = contextOptions || {};
|
|
2642
|
+
const context2 = { error: !!contextOptions.error };
|
|
2643
|
+
let write;
|
|
2644
|
+
if (context2.error) {
|
|
2645
|
+
write = (arg) => this._outputConfiguration.writeErr(arg);
|
|
2646
|
+
} else {
|
|
2647
|
+
write = (arg) => this._outputConfiguration.writeOut(arg);
|
|
2648
|
+
}
|
|
2649
|
+
context2.write = contextOptions.write || write;
|
|
2650
|
+
context2.command = this;
|
|
2651
|
+
return context2;
|
|
2652
|
+
}
|
|
2653
|
+
/**
|
|
2654
|
+
* Output help information for this command.
|
|
2655
|
+
*
|
|
2656
|
+
* Outputs built-in help, and custom text added using `.addHelpText()`.
|
|
2657
|
+
*
|
|
2658
|
+
* @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
|
|
2659
|
+
*/
|
|
2660
|
+
outputHelp(contextOptions) {
|
|
2661
|
+
let deprecatedCallback;
|
|
2662
|
+
if (typeof contextOptions === "function") {
|
|
2663
|
+
deprecatedCallback = contextOptions;
|
|
2664
|
+
contextOptions = void 0;
|
|
2665
|
+
}
|
|
2666
|
+
const context2 = this._getHelpContext(contextOptions);
|
|
2667
|
+
this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", context2));
|
|
2668
|
+
this.emit("beforeHelp", context2);
|
|
2669
|
+
let helpInformation = this.helpInformation(context2);
|
|
2670
|
+
if (deprecatedCallback) {
|
|
2671
|
+
helpInformation = deprecatedCallback(helpInformation);
|
|
2672
|
+
if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
|
|
2673
|
+
throw new Error("outputHelp callback must return a string or a Buffer");
|
|
2674
|
+
}
|
|
2675
|
+
}
|
|
2676
|
+
context2.write(helpInformation);
|
|
2677
|
+
if (this._getHelpOption()?.long) {
|
|
2678
|
+
this.emit(this._getHelpOption().long);
|
|
2679
|
+
}
|
|
2680
|
+
this.emit("afterHelp", context2);
|
|
2681
|
+
this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", context2));
|
|
2682
|
+
}
|
|
2683
|
+
/**
|
|
2684
|
+
* You can pass in flags and a description to customise the built-in help option.
|
|
2685
|
+
* Pass in false to disable the built-in help option.
|
|
2686
|
+
*
|
|
2687
|
+
* @example
|
|
2688
|
+
* program.helpOption('-?, --help' 'show help'); // customise
|
|
2689
|
+
* program.helpOption(false); // disable
|
|
2690
|
+
*
|
|
2691
|
+
* @param {(string | boolean)} flags
|
|
2692
|
+
* @param {string} [description]
|
|
2693
|
+
* @return {Command} `this` command for chaining
|
|
2694
|
+
*/
|
|
2695
|
+
helpOption(flags, description) {
|
|
2696
|
+
if (typeof flags === "boolean") {
|
|
2697
|
+
if (flags) {
|
|
2698
|
+
this._helpOption = this._helpOption ?? void 0;
|
|
2699
|
+
} else {
|
|
2700
|
+
this._helpOption = null;
|
|
2701
|
+
}
|
|
2702
|
+
return this;
|
|
2703
|
+
}
|
|
2704
|
+
flags = flags ?? "-h, --help";
|
|
2705
|
+
description = description ?? "display help for command";
|
|
2706
|
+
this._helpOption = this.createOption(flags, description);
|
|
2707
|
+
return this;
|
|
2708
|
+
}
|
|
2709
|
+
/**
|
|
2710
|
+
* Lazy create help option.
|
|
2711
|
+
* Returns null if has been disabled with .helpOption(false).
|
|
2712
|
+
*
|
|
2713
|
+
* @returns {(Option | null)} the help option
|
|
2714
|
+
* @package internal use only
|
|
2715
|
+
*/
|
|
2716
|
+
_getHelpOption() {
|
|
2717
|
+
if (this._helpOption === void 0) {
|
|
2718
|
+
this.helpOption(void 0, void 0);
|
|
2719
|
+
}
|
|
2720
|
+
return this._helpOption;
|
|
2721
|
+
}
|
|
2722
|
+
/**
|
|
2723
|
+
* Supply your own option to use for the built-in help option.
|
|
2724
|
+
* This is an alternative to using helpOption() to customise the flags and description etc.
|
|
2725
|
+
*
|
|
2726
|
+
* @param {Option} option
|
|
2727
|
+
* @return {Command} `this` command for chaining
|
|
2728
|
+
*/
|
|
2729
|
+
addHelpOption(option) {
|
|
2730
|
+
this._helpOption = option;
|
|
2731
|
+
return this;
|
|
2732
|
+
}
|
|
2733
|
+
/**
|
|
2734
|
+
* Output help information and exit.
|
|
2735
|
+
*
|
|
2736
|
+
* Outputs built-in help, and custom text added using `.addHelpText()`.
|
|
2737
|
+
*
|
|
2738
|
+
* @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
|
|
2739
|
+
*/
|
|
2740
|
+
help(contextOptions) {
|
|
2741
|
+
this.outputHelp(contextOptions);
|
|
2742
|
+
let exitCode = process2.exitCode || 0;
|
|
2743
|
+
if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
|
|
2744
|
+
exitCode = 1;
|
|
2745
|
+
}
|
|
2746
|
+
this._exit(exitCode, "commander.help", "(outputHelp)");
|
|
2747
|
+
}
|
|
2748
|
+
/**
|
|
2749
|
+
* Add additional text to be displayed with the built-in help.
|
|
2750
|
+
*
|
|
2751
|
+
* Position is 'before' or 'after' to affect just this command,
|
|
2752
|
+
* and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
|
|
2753
|
+
*
|
|
2754
|
+
* @param {string} position - before or after built-in help
|
|
2755
|
+
* @param {(string | Function)} text - string to add, or a function returning a string
|
|
2756
|
+
* @return {Command} `this` command for chaining
|
|
2757
|
+
*/
|
|
2758
|
+
addHelpText(position, text) {
|
|
2759
|
+
const allowedValues = ["beforeAll", "before", "after", "afterAll"];
|
|
2760
|
+
if (!allowedValues.includes(position)) {
|
|
2761
|
+
throw new Error(`Unexpected value for position to addHelpText.
|
|
2762
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
2763
|
+
}
|
|
2764
|
+
const helpEvent = `${position}Help`;
|
|
2765
|
+
this.on(helpEvent, (context2) => {
|
|
2766
|
+
let helpStr;
|
|
2767
|
+
if (typeof text === "function") {
|
|
2768
|
+
helpStr = text({ error: context2.error, command: context2.command });
|
|
2769
|
+
} else {
|
|
2770
|
+
helpStr = text;
|
|
2771
|
+
}
|
|
2772
|
+
if (helpStr) {
|
|
2773
|
+
context2.write(`${helpStr}
|
|
2774
|
+
`);
|
|
2775
|
+
}
|
|
2776
|
+
});
|
|
2777
|
+
return this;
|
|
2778
|
+
}
|
|
2779
|
+
/**
|
|
2780
|
+
* Output help information if help flags specified
|
|
2781
|
+
*
|
|
2782
|
+
* @param {Array} args - array of options to search for help flags
|
|
2783
|
+
* @private
|
|
2784
|
+
*/
|
|
2785
|
+
_outputHelpIfRequested(args) {
|
|
2786
|
+
const helpOption = this._getHelpOption();
|
|
2787
|
+
const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
|
|
2788
|
+
if (helpRequested) {
|
|
2789
|
+
this.outputHelp();
|
|
2790
|
+
this._exit(0, "commander.helpDisplayed", "(outputHelp)");
|
|
2791
|
+
}
|
|
2792
|
+
}
|
|
2793
|
+
};
|
|
2794
|
+
function incrementNodeInspectorPort(args) {
|
|
2795
|
+
return args.map((arg) => {
|
|
2796
|
+
if (!arg.startsWith("--inspect")) {
|
|
2797
|
+
return arg;
|
|
2798
|
+
}
|
|
2799
|
+
let debugOption;
|
|
2800
|
+
let debugHost = "127.0.0.1";
|
|
2801
|
+
let debugPort = "9229";
|
|
2802
|
+
let match;
|
|
2803
|
+
if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
|
|
2804
|
+
debugOption = match[1];
|
|
2805
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
|
|
2806
|
+
debugOption = match[1];
|
|
2807
|
+
if (/^\d+$/.test(match[3])) {
|
|
2808
|
+
debugPort = match[3];
|
|
2809
|
+
} else {
|
|
2810
|
+
debugHost = match[3];
|
|
2811
|
+
}
|
|
2812
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
|
|
2813
|
+
debugOption = match[1];
|
|
2814
|
+
debugHost = match[3];
|
|
2815
|
+
debugPort = match[4];
|
|
2816
|
+
}
|
|
2817
|
+
if (debugOption && debugPort !== "0") {
|
|
2818
|
+
return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
|
|
2819
|
+
}
|
|
2820
|
+
return arg;
|
|
2821
|
+
});
|
|
2822
|
+
}
|
|
2823
|
+
exports.Command = Command2;
|
|
2824
|
+
}
|
|
2825
|
+
});
|
|
2826
|
+
|
|
2827
|
+
// node_modules/commander/index.js
|
|
2828
|
+
var require_commander = __commonJS({
|
|
2829
|
+
"node_modules/commander/index.js"(exports) {
|
|
2830
|
+
var { Argument: Argument2 } = require_argument();
|
|
2831
|
+
var { Command: Command2 } = require_command();
|
|
2832
|
+
var { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = require_error();
|
|
2833
|
+
var { Help: Help2 } = require_help();
|
|
2834
|
+
var { Option: Option2 } = require_option();
|
|
2835
|
+
exports.program = new Command2();
|
|
2836
|
+
exports.createCommand = (name) => new Command2(name);
|
|
2837
|
+
exports.createOption = (flags, description) => new Option2(flags, description);
|
|
2838
|
+
exports.createArgument = (name, description) => new Argument2(name, description);
|
|
2839
|
+
exports.Command = Command2;
|
|
2840
|
+
exports.Option = Option2;
|
|
2841
|
+
exports.Argument = Argument2;
|
|
2842
|
+
exports.Help = Help2;
|
|
2843
|
+
exports.CommanderError = CommanderError2;
|
|
2844
|
+
exports.InvalidArgumentError = InvalidArgumentError2;
|
|
2845
|
+
exports.InvalidOptionArgumentError = InvalidArgumentError2;
|
|
2846
|
+
}
|
|
2847
|
+
});
|
|
2848
|
+
|
|
2849
|
+
// ../../node_modules/uWebSockets.js/uws_darwin_arm64_108.node
|
|
2850
|
+
var require_uws_darwin_arm64_108 = __commonJS({
|
|
2851
|
+
"../../node_modules/uWebSockets.js/uws_darwin_arm64_108.node"(exports, module) {
|
|
2852
|
+
module.exports = "./uws_darwin_arm64_108-CLFXMYPI.node";
|
|
2853
|
+
}
|
|
2854
|
+
});
|
|
2855
|
+
|
|
2856
|
+
// ../../node_modules/uWebSockets.js/uws_darwin_arm64_115.node
|
|
2857
|
+
var require_uws_darwin_arm64_115 = __commonJS({
|
|
2858
|
+
"../../node_modules/uWebSockets.js/uws_darwin_arm64_115.node"(exports, module) {
|
|
2859
|
+
module.exports = "./uws_darwin_arm64_115-7FFEG3YF.node";
|
|
2860
|
+
}
|
|
2861
|
+
});
|
|
2862
|
+
|
|
2863
|
+
// ../../node_modules/uWebSockets.js/uws_darwin_arm64_120.node
|
|
2864
|
+
var require_uws_darwin_arm64_120 = __commonJS({
|
|
2865
|
+
"../../node_modules/uWebSockets.js/uws_darwin_arm64_120.node"(exports, module) {
|
|
2866
|
+
module.exports = "./uws_darwin_arm64_120-GFZT7CLS.node";
|
|
2867
|
+
}
|
|
2868
|
+
});
|
|
2869
|
+
|
|
2870
|
+
// ../../node_modules/uWebSockets.js/uws_darwin_arm64_127.node
|
|
2871
|
+
var require_uws_darwin_arm64_127 = __commonJS({
|
|
2872
|
+
"../../node_modules/uWebSockets.js/uws_darwin_arm64_127.node"(exports, module) {
|
|
2873
|
+
module.exports = "./uws_darwin_arm64_127-KHC2FVAM.node";
|
|
2874
|
+
}
|
|
2875
|
+
});
|
|
2876
|
+
|
|
2877
|
+
// ../../node_modules/uWebSockets.js/uws_darwin_x64_108.node
|
|
2878
|
+
var require_uws_darwin_x64_108 = __commonJS({
|
|
2879
|
+
"../../node_modules/uWebSockets.js/uws_darwin_x64_108.node"(exports, module) {
|
|
2880
|
+
module.exports = "./uws_darwin_x64_108-BRGT45AT.node";
|
|
2881
|
+
}
|
|
2882
|
+
});
|
|
2883
|
+
|
|
2884
|
+
// ../../node_modules/uWebSockets.js/uws_darwin_x64_115.node
|
|
2885
|
+
var require_uws_darwin_x64_115 = __commonJS({
|
|
2886
|
+
"../../node_modules/uWebSockets.js/uws_darwin_x64_115.node"(exports, module) {
|
|
2887
|
+
module.exports = "./uws_darwin_x64_115-4HGPQGDD.node";
|
|
2888
|
+
}
|
|
2889
|
+
});
|
|
2890
|
+
|
|
2891
|
+
// ../../node_modules/uWebSockets.js/uws_darwin_x64_120.node
|
|
2892
|
+
var require_uws_darwin_x64_120 = __commonJS({
|
|
2893
|
+
"../../node_modules/uWebSockets.js/uws_darwin_x64_120.node"(exports, module) {
|
|
2894
|
+
module.exports = "./uws_darwin_x64_120-C2SGUHP4.node";
|
|
2895
|
+
}
|
|
14
2896
|
});
|
|
2897
|
+
|
|
2898
|
+
// ../../node_modules/uWebSockets.js/uws_darwin_x64_127.node
|
|
2899
|
+
var require_uws_darwin_x64_127 = __commonJS({
|
|
2900
|
+
"../../node_modules/uWebSockets.js/uws_darwin_x64_127.node"(exports, module) {
|
|
2901
|
+
module.exports = "./uws_darwin_x64_127-NHKQMMST.node";
|
|
2902
|
+
}
|
|
2903
|
+
});
|
|
2904
|
+
|
|
2905
|
+
// ../../node_modules/uWebSockets.js/uws_linux_arm64_108.node
|
|
2906
|
+
var require_uws_linux_arm64_108 = __commonJS({
|
|
2907
|
+
"../../node_modules/uWebSockets.js/uws_linux_arm64_108.node"(exports, module) {
|
|
2908
|
+
module.exports = "./uws_linux_arm64_108-YHK7ACON.node";
|
|
2909
|
+
}
|
|
2910
|
+
});
|
|
2911
|
+
|
|
2912
|
+
// ../../node_modules/uWebSockets.js/uws_linux_arm64_115.node
|
|
2913
|
+
var require_uws_linux_arm64_115 = __commonJS({
|
|
2914
|
+
"../../node_modules/uWebSockets.js/uws_linux_arm64_115.node"(exports, module) {
|
|
2915
|
+
module.exports = "./uws_linux_arm64_115-EIAAY4WO.node";
|
|
2916
|
+
}
|
|
2917
|
+
});
|
|
2918
|
+
|
|
2919
|
+
// ../../node_modules/uWebSockets.js/uws_linux_arm64_120.node
|
|
2920
|
+
var require_uws_linux_arm64_120 = __commonJS({
|
|
2921
|
+
"../../node_modules/uWebSockets.js/uws_linux_arm64_120.node"(exports, module) {
|
|
2922
|
+
module.exports = "./uws_linux_arm64_120-OADY5FIN.node";
|
|
2923
|
+
}
|
|
2924
|
+
});
|
|
2925
|
+
|
|
2926
|
+
// ../../node_modules/uWebSockets.js/uws_linux_arm64_127.node
|
|
2927
|
+
var require_uws_linux_arm64_127 = __commonJS({
|
|
2928
|
+
"../../node_modules/uWebSockets.js/uws_linux_arm64_127.node"(exports, module) {
|
|
2929
|
+
module.exports = "./uws_linux_arm64_127-U2SRLYQM.node";
|
|
2930
|
+
}
|
|
2931
|
+
});
|
|
2932
|
+
|
|
2933
|
+
// ../../node_modules/uWebSockets.js/uws_linux_arm_108.node
|
|
2934
|
+
var require_uws_linux_arm_108 = __commonJS({
|
|
2935
|
+
"../../node_modules/uWebSockets.js/uws_linux_arm_108.node"(exports, module) {
|
|
2936
|
+
module.exports = "./uws_linux_arm_108-BKVITVZA.node";
|
|
2937
|
+
}
|
|
2938
|
+
});
|
|
2939
|
+
|
|
2940
|
+
// ../../node_modules/uWebSockets.js/uws_linux_arm_115.node
|
|
2941
|
+
var require_uws_linux_arm_115 = __commonJS({
|
|
2942
|
+
"../../node_modules/uWebSockets.js/uws_linux_arm_115.node"(exports, module) {
|
|
2943
|
+
module.exports = "./uws_linux_arm_115-7IORQF77.node";
|
|
2944
|
+
}
|
|
2945
|
+
});
|
|
2946
|
+
|
|
2947
|
+
// ../../node_modules/uWebSockets.js/uws_linux_arm_120.node
|
|
2948
|
+
var require_uws_linux_arm_120 = __commonJS({
|
|
2949
|
+
"../../node_modules/uWebSockets.js/uws_linux_arm_120.node"(exports, module) {
|
|
2950
|
+
module.exports = "./uws_linux_arm_120-LCX4ED5F.node";
|
|
2951
|
+
}
|
|
2952
|
+
});
|
|
2953
|
+
|
|
2954
|
+
// ../../node_modules/uWebSockets.js/uws_linux_arm_127.node
|
|
2955
|
+
var require_uws_linux_arm_127 = __commonJS({
|
|
2956
|
+
"../../node_modules/uWebSockets.js/uws_linux_arm_127.node"(exports, module) {
|
|
2957
|
+
module.exports = "./uws_linux_arm_127-6UTO7TL6.node";
|
|
2958
|
+
}
|
|
2959
|
+
});
|
|
2960
|
+
|
|
2961
|
+
// ../../node_modules/uWebSockets.js/uws_linux_x64_108.node
|
|
2962
|
+
var require_uws_linux_x64_108 = __commonJS({
|
|
2963
|
+
"../../node_modules/uWebSockets.js/uws_linux_x64_108.node"(exports, module) {
|
|
2964
|
+
module.exports = "./uws_linux_x64_108-QSNE6XWU.node";
|
|
2965
|
+
}
|
|
2966
|
+
});
|
|
2967
|
+
|
|
2968
|
+
// ../../node_modules/uWebSockets.js/uws_linux_x64_115.node
|
|
2969
|
+
var require_uws_linux_x64_115 = __commonJS({
|
|
2970
|
+
"../../node_modules/uWebSockets.js/uws_linux_x64_115.node"(exports, module) {
|
|
2971
|
+
module.exports = "./uws_linux_x64_115-7AAZWMWE.node";
|
|
2972
|
+
}
|
|
2973
|
+
});
|
|
2974
|
+
|
|
2975
|
+
// ../../node_modules/uWebSockets.js/uws_linux_x64_120.node
|
|
2976
|
+
var require_uws_linux_x64_120 = __commonJS({
|
|
2977
|
+
"../../node_modules/uWebSockets.js/uws_linux_x64_120.node"(exports, module) {
|
|
2978
|
+
module.exports = "./uws_linux_x64_120-AIZ6RIW2.node";
|
|
2979
|
+
}
|
|
2980
|
+
});
|
|
2981
|
+
|
|
2982
|
+
// ../../node_modules/uWebSockets.js/uws_linux_x64_127.node
|
|
2983
|
+
var require_uws_linux_x64_127 = __commonJS({
|
|
2984
|
+
"../../node_modules/uWebSockets.js/uws_linux_x64_127.node"(exports, module) {
|
|
2985
|
+
module.exports = "./uws_linux_x64_127-HBA6RNSU.node";
|
|
2986
|
+
}
|
|
2987
|
+
});
|
|
2988
|
+
|
|
2989
|
+
// ../../node_modules/uWebSockets.js/uws_win32_x64_108.node
|
|
2990
|
+
var require_uws_win32_x64_108 = __commonJS({
|
|
2991
|
+
"../../node_modules/uWebSockets.js/uws_win32_x64_108.node"(exports, module) {
|
|
2992
|
+
module.exports = "./uws_win32_x64_108-J6KONPDM.node";
|
|
2993
|
+
}
|
|
2994
|
+
});
|
|
2995
|
+
|
|
2996
|
+
// ../../node_modules/uWebSockets.js/uws_win32_x64_115.node
|
|
2997
|
+
var require_uws_win32_x64_115 = __commonJS({
|
|
2998
|
+
"../../node_modules/uWebSockets.js/uws_win32_x64_115.node"(exports, module) {
|
|
2999
|
+
module.exports = "./uws_win32_x64_115-V5N4NHJ5.node";
|
|
3000
|
+
}
|
|
3001
|
+
});
|
|
3002
|
+
|
|
3003
|
+
// ../../node_modules/uWebSockets.js/uws_win32_x64_120.node
|
|
3004
|
+
var require_uws_win32_x64_120 = __commonJS({
|
|
3005
|
+
"../../node_modules/uWebSockets.js/uws_win32_x64_120.node"(exports, module) {
|
|
3006
|
+
module.exports = "./uws_win32_x64_120-XH4MVJGN.node";
|
|
3007
|
+
}
|
|
3008
|
+
});
|
|
3009
|
+
|
|
3010
|
+
// ../../node_modules/uWebSockets.js/uws_win32_x64_127.node
|
|
3011
|
+
var require_uws_win32_x64_127 = __commonJS({
|
|
3012
|
+
"../../node_modules/uWebSockets.js/uws_win32_x64_127.node"(exports, module) {
|
|
3013
|
+
module.exports = "./uws_win32_x64_127-JBAEKR4X.node";
|
|
3014
|
+
}
|
|
3015
|
+
});
|
|
3016
|
+
|
|
3017
|
+
// require("./uws_*_*_*.node") in ../../node_modules/uWebSockets.js/uws.js
|
|
3018
|
+
var globRequire_uws______node;
|
|
3019
|
+
var init_ = __esm({
|
|
3020
|
+
'require("./uws_*_*_*.node") in ../../node_modules/uWebSockets.js/uws.js'() {
|
|
3021
|
+
globRequire_uws______node = __glob({
|
|
3022
|
+
"./uws_darwin_arm64_108.node": () => require_uws_darwin_arm64_108(),
|
|
3023
|
+
"./uws_darwin_arm64_115.node": () => require_uws_darwin_arm64_115(),
|
|
3024
|
+
"./uws_darwin_arm64_120.node": () => require_uws_darwin_arm64_120(),
|
|
3025
|
+
"./uws_darwin_arm64_127.node": () => require_uws_darwin_arm64_127(),
|
|
3026
|
+
"./uws_darwin_x64_108.node": () => require_uws_darwin_x64_108(),
|
|
3027
|
+
"./uws_darwin_x64_115.node": () => require_uws_darwin_x64_115(),
|
|
3028
|
+
"./uws_darwin_x64_120.node": () => require_uws_darwin_x64_120(),
|
|
3029
|
+
"./uws_darwin_x64_127.node": () => require_uws_darwin_x64_127(),
|
|
3030
|
+
"./uws_linux_arm64_108.node": () => require_uws_linux_arm64_108(),
|
|
3031
|
+
"./uws_linux_arm64_115.node": () => require_uws_linux_arm64_115(),
|
|
3032
|
+
"./uws_linux_arm64_120.node": () => require_uws_linux_arm64_120(),
|
|
3033
|
+
"./uws_linux_arm64_127.node": () => require_uws_linux_arm64_127(),
|
|
3034
|
+
"./uws_linux_arm_108.node": () => require_uws_linux_arm_108(),
|
|
3035
|
+
"./uws_linux_arm_115.node": () => require_uws_linux_arm_115(),
|
|
3036
|
+
"./uws_linux_arm_120.node": () => require_uws_linux_arm_120(),
|
|
3037
|
+
"./uws_linux_arm_127.node": () => require_uws_linux_arm_127(),
|
|
3038
|
+
"./uws_linux_x64_108.node": () => require_uws_linux_x64_108(),
|
|
3039
|
+
"./uws_linux_x64_115.node": () => require_uws_linux_x64_115(),
|
|
3040
|
+
"./uws_linux_x64_120.node": () => require_uws_linux_x64_120(),
|
|
3041
|
+
"./uws_linux_x64_127.node": () => require_uws_linux_x64_127(),
|
|
3042
|
+
"./uws_win32_x64_108.node": () => require_uws_win32_x64_108(),
|
|
3043
|
+
"./uws_win32_x64_115.node": () => require_uws_win32_x64_115(),
|
|
3044
|
+
"./uws_win32_x64_120.node": () => require_uws_win32_x64_120(),
|
|
3045
|
+
"./uws_win32_x64_127.node": () => require_uws_win32_x64_127()
|
|
3046
|
+
});
|
|
3047
|
+
}
|
|
3048
|
+
});
|
|
3049
|
+
|
|
3050
|
+
// ../../node_modules/uWebSockets.js/uws.js
|
|
3051
|
+
var require_uws = __commonJS({
|
|
3052
|
+
"../../node_modules/uWebSockets.js/uws.js"(exports, module) {
|
|
3053
|
+
init_();
|
|
3054
|
+
module.exports = (() => {
|
|
3055
|
+
try {
|
|
3056
|
+
return globRequire_uws______node("./uws_" + process.platform + "_" + process.arch + "_" + process.versions.modules + ".node");
|
|
3057
|
+
} catch (e) {
|
|
3058
|
+
throw new Error("This version of uWS.js supports only Node.js versions 18, 20, 21 and 22 on (glibc) Linux, macOS and Windows, on Tier 1 platforms (https://github.com/nodejs/node/blob/master/BUILDING.md#platform-list).\n\n" + e.toString());
|
|
3059
|
+
}
|
|
3060
|
+
})();
|
|
3061
|
+
module.exports.DeclarativeResponse = class DeclarativeResponse {
|
|
3062
|
+
constructor() {
|
|
3063
|
+
this.instructions = [];
|
|
3064
|
+
}
|
|
3065
|
+
// Utility method to encode text and append instruction
|
|
3066
|
+
_appendInstruction(opcode, ...text) {
|
|
3067
|
+
this.instructions.push(opcode);
|
|
3068
|
+
text.forEach((str) => {
|
|
3069
|
+
const bytes = typeof str === "string" ? new TextEncoder().encode(str) : str;
|
|
3070
|
+
this.instructions.push(bytes.length, ...bytes);
|
|
3071
|
+
});
|
|
3072
|
+
}
|
|
3073
|
+
// Utility method to append 2-byte length text in little-endian format
|
|
3074
|
+
_appendInstructionWithLength(opcode, text) {
|
|
3075
|
+
this.instructions.push(opcode);
|
|
3076
|
+
const bytes = new TextEncoder().encode(text);
|
|
3077
|
+
const length = bytes.length;
|
|
3078
|
+
this.instructions.push(length & 255, length >> 8 & 255, ...bytes);
|
|
3079
|
+
}
|
|
3080
|
+
writeHeader(key, value) {
|
|
3081
|
+
return this._appendInstruction(1, key, value), this;
|
|
3082
|
+
}
|
|
3083
|
+
writeBody() {
|
|
3084
|
+
return this.instructions.push(2), this;
|
|
3085
|
+
}
|
|
3086
|
+
writeQueryValue(key) {
|
|
3087
|
+
return this._appendInstruction(3, key), this;
|
|
3088
|
+
}
|
|
3089
|
+
writeHeaderValue(key) {
|
|
3090
|
+
return this._appendInstruction(4, key), this;
|
|
3091
|
+
}
|
|
3092
|
+
write(value) {
|
|
3093
|
+
return this._appendInstructionWithLength(5, value), this;
|
|
3094
|
+
}
|
|
3095
|
+
writeParameterValue(key) {
|
|
3096
|
+
return this._appendInstruction(6, key), this;
|
|
3097
|
+
}
|
|
3098
|
+
end(value) {
|
|
3099
|
+
const bytes = new TextEncoder().encode(value);
|
|
3100
|
+
const length = bytes.length;
|
|
3101
|
+
this.instructions.push(0, length & 255, length >> 8 & 255, ...bytes);
|
|
3102
|
+
return new Uint8Array(this.instructions).buffer;
|
|
3103
|
+
}
|
|
3104
|
+
};
|
|
3105
|
+
}
|
|
3106
|
+
});
|
|
3107
|
+
|
|
3108
|
+
// node_modules/commander/esm.mjs
|
|
3109
|
+
var import_index = __toESM(require_commander(), 1);
|
|
3110
|
+
var {
|
|
3111
|
+
program,
|
|
3112
|
+
createCommand,
|
|
3113
|
+
createArgument,
|
|
3114
|
+
createOption,
|
|
3115
|
+
CommanderError,
|
|
3116
|
+
InvalidArgumentError,
|
|
3117
|
+
InvalidOptionArgumentError,
|
|
3118
|
+
// deprecated old name
|
|
3119
|
+
Command,
|
|
3120
|
+
Argument,
|
|
3121
|
+
Option,
|
|
3122
|
+
Help
|
|
3123
|
+
} = import_index.default;
|
|
3124
|
+
|
|
3125
|
+
// package.json
|
|
3126
|
+
var package_default = {
|
|
3127
|
+
version: "6.0.0-rc.2"};
|
|
3128
|
+
var ALWAYS_EXTERNAL = ["uWebSockets.js"];
|
|
15
3129
|
function getUserExternals(cwd) {
|
|
3130
|
+
let pkgExternals = [];
|
|
3131
|
+
try {
|
|
3132
|
+
const pkgPath = path7.join(cwd, "package.json");
|
|
3133
|
+
if (fs.existsSync(pkgPath)) {
|
|
3134
|
+
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
|
|
3135
|
+
const deps = Object.keys(pkg.dependencies || {});
|
|
3136
|
+
const devDeps = Object.keys(pkg.devDependencies || {});
|
|
3137
|
+
pkgExternals = [...deps, ...devDeps];
|
|
3138
|
+
}
|
|
3139
|
+
} catch (err) {
|
|
3140
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
3141
|
+
console.warn(
|
|
3142
|
+
`[Axiomify CLI] Failed to read package.json (${message}); defaulting to empty externals.`
|
|
3143
|
+
);
|
|
3144
|
+
}
|
|
3145
|
+
return Array.from(/* @__PURE__ */ new Set([...ALWAYS_EXTERNAL, ...pkgExternals]));
|
|
3146
|
+
}
|
|
3147
|
+
|
|
3148
|
+
// src/commands/build.ts
|
|
3149
|
+
async function buildProject(entry) {
|
|
3150
|
+
const entryPath = path7.resolve(process.cwd(), entry);
|
|
3151
|
+
const outPath = path7.resolve(process.cwd(), "dist/index.js");
|
|
3152
|
+
const userExternals = getUserExternals(process.cwd());
|
|
3153
|
+
console.log(`\u{1F528} Building production bundle from ${entry}...`);
|
|
3154
|
+
try {
|
|
3155
|
+
await esbuild.build({
|
|
3156
|
+
entryPoints: [entryPath],
|
|
3157
|
+
bundle: true,
|
|
3158
|
+
platform: "node",
|
|
3159
|
+
target: "node18",
|
|
3160
|
+
outfile: outPath,
|
|
3161
|
+
minify: true,
|
|
3162
|
+
keepNames: true,
|
|
3163
|
+
external: [.../* @__PURE__ */ new Set([...userExternals, "node:*"])]
|
|
3164
|
+
});
|
|
3165
|
+
console.log(`\u2705 Build successful: ${outPath}`);
|
|
3166
|
+
} catch (error) {
|
|
3167
|
+
console.error("\u274C Build failed:", error);
|
|
3168
|
+
process.exit(1);
|
|
3169
|
+
}
|
|
3170
|
+
}
|
|
3171
|
+
function colourMethod(method) {
|
|
3172
|
+
const m = method.toUpperCase();
|
|
3173
|
+
const padded = m.padEnd(7);
|
|
3174
|
+
switch (m) {
|
|
3175
|
+
case "GET":
|
|
3176
|
+
return pc.bold(pc.green(padded));
|
|
3177
|
+
case "POST":
|
|
3178
|
+
return pc.bold(pc.blue(padded));
|
|
3179
|
+
case "PUT":
|
|
3180
|
+
return pc.bold(pc.yellow(padded));
|
|
3181
|
+
case "PATCH":
|
|
3182
|
+
return pc.bold(pc.magenta(padded));
|
|
3183
|
+
case "DELETE":
|
|
3184
|
+
return pc.bold(pc.red(padded));
|
|
3185
|
+
case "HEAD":
|
|
3186
|
+
return pc.dim(padded);
|
|
3187
|
+
case "OPTIONS":
|
|
3188
|
+
return pc.dim(padded);
|
|
3189
|
+
case "WS":
|
|
3190
|
+
return pc.bold(pc.cyan(padded));
|
|
3191
|
+
default:
|
|
3192
|
+
return padded;
|
|
3193
|
+
}
|
|
3194
|
+
}
|
|
3195
|
+
var badge = {
|
|
3196
|
+
validation(label) {
|
|
3197
|
+
return pc.cyan(label);
|
|
3198
|
+
},
|
|
3199
|
+
deprecated() {
|
|
3200
|
+
return pc.bold(pc.red("\u2298 DEPRECATED"));
|
|
3201
|
+
},
|
|
3202
|
+
timeout(ms) {
|
|
3203
|
+
return pc.dim(`${ms}ms`);
|
|
3204
|
+
},
|
|
3205
|
+
tags(tags) {
|
|
3206
|
+
if (!tags.length) return "";
|
|
3207
|
+
return tags.map((t) => pc.dim(`#${t}`)).join(" ");
|
|
3208
|
+
}
|
|
3209
|
+
};
|
|
3210
|
+
function visibleLength(s) {
|
|
3211
|
+
return s.replace(/\x1b\[[0-9;]*m/g, "").length;
|
|
3212
|
+
}
|
|
3213
|
+
function pad(s, width, align) {
|
|
3214
|
+
const v = visibleLength(s);
|
|
3215
|
+
if (v >= width) return s;
|
|
3216
|
+
const filler = " ".repeat(width - v);
|
|
3217
|
+
return align === "right" ? filler + s : s + filler;
|
|
3218
|
+
}
|
|
3219
|
+
function truncate(s, max) {
|
|
3220
|
+
if (visibleLength(s) <= max) return s;
|
|
3221
|
+
const stripped = s.replace(/\x1b\[[0-9;]*m/g, "");
|
|
3222
|
+
return stripped.slice(0, max - 1) + pc.dim("\u2026");
|
|
3223
|
+
}
|
|
3224
|
+
function renderTable(columns, rows, terminalWidth = process.stdout.columns || 100) {
|
|
3225
|
+
const widths = columns.map((col, i) => {
|
|
3226
|
+
const headerW = visibleLength(col.header);
|
|
3227
|
+
const cellW = Math.max(
|
|
3228
|
+
headerW,
|
|
3229
|
+
...rows.map((r) => visibleLength(r[i] ?? ""))
|
|
3230
|
+
);
|
|
3231
|
+
let w = Math.max(headerW, cellW);
|
|
3232
|
+
if (col.minWidth) w = Math.max(w, col.minWidth);
|
|
3233
|
+
if (col.maxWidth) w = Math.min(w, col.maxWidth);
|
|
3234
|
+
return w;
|
|
3235
|
+
});
|
|
3236
|
+
const overheadPerSep = 3;
|
|
3237
|
+
const overhead = (columns.length + 1) * 2 + overheadPerSep * (columns.length - 1);
|
|
3238
|
+
let total = widths.reduce((a, b) => a + b, 0) + overhead;
|
|
3239
|
+
if (total > terminalWidth) {
|
|
3240
|
+
const flexIdx = columns.map((c, i) => ({ c, i })).filter(({ c }) => !c.minWidth).map(({ i }) => i);
|
|
3241
|
+
let excess = total - terminalWidth;
|
|
3242
|
+
for (let pass = 0; pass < 8 && excess > 0; pass++) {
|
|
3243
|
+
for (const i of flexIdx) {
|
|
3244
|
+
if (excess <= 0) break;
|
|
3245
|
+
if (widths[i] > 8) {
|
|
3246
|
+
widths[i]--;
|
|
3247
|
+
excess--;
|
|
3248
|
+
total--;
|
|
3249
|
+
}
|
|
3250
|
+
}
|
|
3251
|
+
}
|
|
3252
|
+
}
|
|
3253
|
+
const bar = (l, m, r) => l + widths.map((w) => "\u2500".repeat(w + 2)).join(m) + r;
|
|
3254
|
+
const lines = [];
|
|
3255
|
+
lines.push(pc.dim(bar("\u250C", "\u252C", "\u2510")));
|
|
3256
|
+
lines.push(
|
|
3257
|
+
pc.dim("\u2502 ") + columns.map((c, i) => pc.bold(pad(c.header, widths[i], c.align ?? "left"))).join(pc.dim(" \u2502 ")) + pc.dim(" \u2502")
|
|
3258
|
+
);
|
|
3259
|
+
lines.push(pc.dim(bar("\u251C", "\u253C", "\u2524")));
|
|
3260
|
+
for (const row of rows) {
|
|
3261
|
+
lines.push(
|
|
3262
|
+
pc.dim("\u2502 ") + columns.map((c, i) => {
|
|
3263
|
+
const cell = row[i] ?? "";
|
|
3264
|
+
const truncated = c.maxWidth ? truncate(cell, widths[i]) : cell;
|
|
3265
|
+
return pad(truncated, widths[i], c.align ?? "left");
|
|
3266
|
+
}).join(pc.dim(" \u2502 ")) + pc.dim(" \u2502")
|
|
3267
|
+
);
|
|
3268
|
+
}
|
|
3269
|
+
lines.push(pc.dim(bar("\u2514", "\u2534", "\u2518")));
|
|
3270
|
+
return lines.join("\n");
|
|
3271
|
+
}
|
|
3272
|
+
function pluralise(n, singular, plural) {
|
|
3273
|
+
return n === 1 ? `${n} ${singular}` : `${n} ${plural ?? singular + "s"}`;
|
|
3274
|
+
}
|
|
3275
|
+
var symbols = {
|
|
3276
|
+
ok: pc.green("\u2713"),
|
|
3277
|
+
warn: pc.yellow("\u26A0"),
|
|
3278
|
+
fail: pc.red("\u2717"),
|
|
3279
|
+
info: pc.cyan("\u2139"),
|
|
3280
|
+
bullet: pc.dim("\u2022"),
|
|
3281
|
+
arrow: pc.dim("\u2192")
|
|
3282
|
+
};
|
|
3283
|
+
async function loadApp(entry) {
|
|
3284
|
+
const entryPath = path7.resolve(process.cwd(), entry);
|
|
3285
|
+
const tempDir = path7.resolve(process.cwd(), ".axiomify");
|
|
3286
|
+
const tempPath = path7.join(tempDir, "inspect.cjs");
|
|
3287
|
+
const userExternals = getUserExternals(process.cwd());
|
|
3288
|
+
await esbuild.build({
|
|
3289
|
+
entryPoints: [entryPath],
|
|
3290
|
+
bundle: true,
|
|
3291
|
+
platform: "node",
|
|
3292
|
+
format: "cjs",
|
|
3293
|
+
outfile: tempPath,
|
|
3294
|
+
external: [.../* @__PURE__ */ new Set([...userExternals, "node:*"])],
|
|
3295
|
+
// Silence esbuild's own progress chatter — the CLI command above is
|
|
3296
|
+
// responsible for its own user-facing output.
|
|
3297
|
+
logLevel: "error"
|
|
3298
|
+
});
|
|
3299
|
+
try {
|
|
3300
|
+
delete __require.cache[__require.resolve(tempPath)];
|
|
3301
|
+
} catch {
|
|
3302
|
+
}
|
|
3303
|
+
const hangTimer = setTimeout(() => {
|
|
3304
|
+
process.stderr.write(
|
|
3305
|
+
"\n" + pc.yellow("\u26A0 CLI inspection is taking longer than expected.") + "\n Your entry file may be starting a server unconditionally.\n Wrap the listen() call in " + pc.cyan("if (require.main === module) { ... }") + " so it only runs when executed directly.\n\n"
|
|
3306
|
+
);
|
|
3307
|
+
}, 5e3);
|
|
3308
|
+
hangTimer.unref();
|
|
3309
|
+
let mod;
|
|
3310
|
+
try {
|
|
3311
|
+
mod = __require(tempPath);
|
|
3312
|
+
} finally {
|
|
3313
|
+
clearTimeout(hangTimer);
|
|
3314
|
+
}
|
|
3315
|
+
const app = mod.app ?? mod.default;
|
|
3316
|
+
if (!app || typeof app.registeredRoutes === "undefined") {
|
|
3317
|
+
await fs5.rm(tempDir, { recursive: true, force: true }).catch(() => {
|
|
3318
|
+
});
|
|
3319
|
+
throw new Error(
|
|
3320
|
+
"Could not find an exported Axiomify instance.\nEnsure your entry file exports the app:\n export const app = new Axiomify();\nor:\n export default app;"
|
|
3321
|
+
);
|
|
3322
|
+
}
|
|
3323
|
+
const cleanup = async () => {
|
|
3324
|
+
await fs5.rm(tempDir, { recursive: true, force: true }).catch(() => {
|
|
3325
|
+
});
|
|
3326
|
+
};
|
|
3327
|
+
return { app, cleanup };
|
|
3328
|
+
}
|
|
3329
|
+
|
|
3330
|
+
// src/commands/check.ts
|
|
3331
|
+
function add(ctx, f) {
|
|
3332
|
+
ctx.findings.push(f);
|
|
3333
|
+
}
|
|
3334
|
+
function checkRequestId(ctx) {
|
|
3335
|
+
const onRequest = ctx.app.hooks?.hooks?.onRequest ?? [];
|
|
3336
|
+
if (onRequest.length === 0) {
|
|
3337
|
+
add(ctx, {
|
|
3338
|
+
severity: "warn",
|
|
3339
|
+
area: "observability",
|
|
3340
|
+
message: "`app.enableRequestId()` has not been called",
|
|
3341
|
+
hint: "Distributed-trace correlation will be impossible without an X-Request-Id header. Add `app.enableRequestId()` after construction unless you handle this elsewhere."
|
|
3342
|
+
});
|
|
3343
|
+
return;
|
|
3344
|
+
}
|
|
3345
|
+
add(ctx, {
|
|
3346
|
+
severity: "ok",
|
|
3347
|
+
area: "observability",
|
|
3348
|
+
message: `onRequest hooks: ${onRequest.length} registered`
|
|
3349
|
+
});
|
|
3350
|
+
}
|
|
3351
|
+
function checkEnvVars(ctx) {
|
|
3352
|
+
const expectedInProd = ["JWT_SECRET", "NODE_ENV"];
|
|
3353
|
+
for (const key of expectedInProd) {
|
|
3354
|
+
if (!ctx.envKeys.has(key)) continue;
|
|
3355
|
+
if (process.env[key]) {
|
|
3356
|
+
add(ctx, { severity: "ok", area: "env", message: `${key} is set` });
|
|
3357
|
+
} else {
|
|
3358
|
+
add(ctx, {
|
|
3359
|
+
severity: "warn",
|
|
3360
|
+
area: "env",
|
|
3361
|
+
message: `${key} referenced in source but not set in environment`,
|
|
3362
|
+
hint: key === "JWT_SECRET" ? "Set this before deploying. Generate one via `node -e \"console.log(require('crypto').randomBytes(48).toString('base64'))\"`" : `Ensure ${key} is set in your deployment environment.`
|
|
3363
|
+
});
|
|
3364
|
+
}
|
|
3365
|
+
}
|
|
3366
|
+
}
|
|
3367
|
+
function checkResponseSchemas(ctx) {
|
|
3368
|
+
const routes = ctx.app.registeredRoutes ?? [];
|
|
3369
|
+
const missing = routes.filter(
|
|
3370
|
+
(r) => r.schema?.body && !r.schema?.response
|
|
3371
|
+
);
|
|
3372
|
+
if (missing.length > 0) {
|
|
3373
|
+
add(ctx, {
|
|
3374
|
+
severity: "warn",
|
|
3375
|
+
area: "validation",
|
|
3376
|
+
message: `${missing.length} route${missing.length === 1 ? "" : "s"} with body schema but no response schema`,
|
|
3377
|
+
hint: `Declaring \`schema.response\` pins the API contract \u2014 without it, internal model field names leak to clients and breaking changes go undetected. First offender: ${missing[0].method} ${missing[0].path}`
|
|
3378
|
+
});
|
|
3379
|
+
} else if (routes.length > 0) {
|
|
3380
|
+
add(ctx, {
|
|
3381
|
+
severity: "ok",
|
|
3382
|
+
area: "validation",
|
|
3383
|
+
message: "every route with a body schema also declares a response schema"
|
|
3384
|
+
});
|
|
3385
|
+
}
|
|
3386
|
+
}
|
|
3387
|
+
function checkOpenApiNaming(ctx) {
|
|
3388
|
+
const routes = ctx.app.registeredRoutes ?? [];
|
|
3389
|
+
const usingMeta = routes.filter((r) => r.meta);
|
|
3390
|
+
if (usingMeta.length > 0) {
|
|
3391
|
+
add(ctx, {
|
|
3392
|
+
severity: "fail",
|
|
3393
|
+
area: "api",
|
|
3394
|
+
message: `${usingMeta.length} route${usingMeta.length === 1 ? "" : "s"} use the removed \`meta:\` field`,
|
|
3395
|
+
hint: `The \`meta:\` field was removed in 6.0. Rename to \`openapi:\` \u2014 shape is identical. First offender: ${usingMeta[0].method} ${usingMeta[0].path}`
|
|
3396
|
+
});
|
|
3397
|
+
}
|
|
3398
|
+
}
|
|
3399
|
+
function checkHealthCheck(ctx) {
|
|
3400
|
+
const routes = ctx.app.registeredRoutes ?? [];
|
|
3401
|
+
const hasHealth = routes.some(
|
|
3402
|
+
(r) => r.method === "GET" && ["/health", "/healthz", "/-/health", "/ping", "/live", "/ready"].some(
|
|
3403
|
+
(p) => r.path === p
|
|
3404
|
+
)
|
|
3405
|
+
);
|
|
3406
|
+
if (hasHealth) {
|
|
3407
|
+
add(ctx, { severity: "ok", area: "ops", message: "health-check route registered" });
|
|
3408
|
+
} else {
|
|
3409
|
+
add(ctx, {
|
|
3410
|
+
severity: "warn",
|
|
3411
|
+
area: "ops",
|
|
3412
|
+
message: "no health-check route detected",
|
|
3413
|
+
hint: 'Kubernetes, ECS, and load balancers expect a `/health` (or similar) endpoint. Register one via `app.healthCheck("/health")` from `@axiomify/core`.'
|
|
3414
|
+
});
|
|
3415
|
+
}
|
|
3416
|
+
}
|
|
3417
|
+
function checkOpenApiExposure(ctx) {
|
|
3418
|
+
const routes = ctx.app.registeredRoutes ?? [];
|
|
3419
|
+
const docsRoute = routes.find(
|
|
3420
|
+
(r) => r.method === "GET" && (r.path === "/docs" || r.path.endsWith("/docs"))
|
|
3421
|
+
);
|
|
3422
|
+
const specRoute = routes.find(
|
|
3423
|
+
(r) => r.method === "GET" && r.path.endsWith("/openapi.json")
|
|
3424
|
+
);
|
|
3425
|
+
if (docsRoute || specRoute) {
|
|
3426
|
+
add(ctx, {
|
|
3427
|
+
severity: "warn",
|
|
3428
|
+
area: "security",
|
|
3429
|
+
message: "OpenAPI docs endpoint is registered",
|
|
3430
|
+
hint: "In production, supply `protect: (req) => ...` to `useOpenAPI()` (or set `allowPublicInProduction: true` if exposure is intentional). The runtime warning is logged on the first request."
|
|
3431
|
+
});
|
|
3432
|
+
}
|
|
3433
|
+
}
|
|
3434
|
+
function checkRoutesLockState(ctx) {
|
|
3435
|
+
if (ctx.app._routesLocked) {
|
|
3436
|
+
add(ctx, {
|
|
3437
|
+
severity: "warn",
|
|
3438
|
+
area: "config",
|
|
3439
|
+
message: "app.lockRoutes() has already been called",
|
|
3440
|
+
hint: "The entry file appears to construct an adapter at the top level. Wrap adapter construction in `if (require.main === module) { ... }` so the CLI can introspect the app without triggering it."
|
|
3441
|
+
});
|
|
3442
|
+
}
|
|
3443
|
+
}
|
|
3444
|
+
function checkSecurityPlugins(ctx) {
|
|
3445
|
+
const onRequest = ctx.app.hooks?.hooks?.onRequest ?? [];
|
|
3446
|
+
if (onRequest.length < 2) {
|
|
3447
|
+
add(ctx, {
|
|
3448
|
+
severity: "warn",
|
|
3449
|
+
area: "security",
|
|
3450
|
+
message: "few onRequest hooks detected \u2014 security plugins may not be registered",
|
|
3451
|
+
hint: "`@axiomify/helmet`, `@axiomify/cors`, and `@axiomify/security` each install onRequest hooks. If you are not using these, ensure equivalent defences are in place elsewhere."
|
|
3452
|
+
});
|
|
3453
|
+
} else {
|
|
3454
|
+
add(ctx, {
|
|
3455
|
+
severity: "ok",
|
|
3456
|
+
area: "security",
|
|
3457
|
+
message: `${onRequest.length} onRequest hooks registered (security plugins likely active)`
|
|
3458
|
+
});
|
|
3459
|
+
}
|
|
3460
|
+
}
|
|
3461
|
+
function collectEnvKeysFromBundle(bundlePath) {
|
|
3462
|
+
const keys = /* @__PURE__ */ new Set();
|
|
16
3463
|
try {
|
|
17
|
-
const
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
return [...deps, ...devDeps];
|
|
3464
|
+
const src = fs.readFileSync(bundlePath, "utf8");
|
|
3465
|
+
const re = /process\.env\.([A-Z][A-Z0-9_]*)|process\.env\[(['"])([A-Z][A-Z0-9_]*)\2\]/g;
|
|
3466
|
+
let m;
|
|
3467
|
+
while ((m = re.exec(src)) !== null) {
|
|
3468
|
+
keys.add(m[1] ?? m[3]);
|
|
23
3469
|
}
|
|
24
|
-
} catch
|
|
25
|
-
console.warn(
|
|
26
|
-
"[Axiomify CLI] Failed to read package.json, defaulting to empty externals."
|
|
27
|
-
);
|
|
3470
|
+
} catch {
|
|
28
3471
|
}
|
|
29
|
-
return
|
|
3472
|
+
return keys;
|
|
30
3473
|
}
|
|
31
|
-
|
|
32
|
-
// src/commands/build.ts
|
|
33
|
-
async function buildProject(entry) {
|
|
34
|
-
const entryPath = path4.resolve(process.cwd(), entry);
|
|
35
|
-
const outPath = path4.resolve(process.cwd(), "dist/index.js");
|
|
36
|
-
const userExternals = getUserExternals(process.cwd());
|
|
37
|
-
console.log(`\u{1F528} Building production bundle from ${entry}...`);
|
|
3474
|
+
function loadPkgJson(cwd) {
|
|
38
3475
|
try {
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
3476
|
+
return JSON.parse(fs.readFileSync(path7.join(cwd, "package.json"), "utf8"));
|
|
3477
|
+
} catch {
|
|
3478
|
+
return null;
|
|
3479
|
+
}
|
|
3480
|
+
}
|
|
3481
|
+
async function runCheck(entry) {
|
|
3482
|
+
let app;
|
|
3483
|
+
let cleanup = async () => {
|
|
3484
|
+
};
|
|
3485
|
+
let bundlePath = "";
|
|
3486
|
+
try {
|
|
3487
|
+
const loaded = await loadApp(entry);
|
|
3488
|
+
app = loaded.app;
|
|
3489
|
+
cleanup = loaded.cleanup;
|
|
3490
|
+
bundlePath = path7.resolve(process.cwd(), ".axiomify/inspect.cjs");
|
|
3491
|
+
} catch (err) {
|
|
3492
|
+
console.error(pc.red("\u2717 Failed to load app:"));
|
|
3493
|
+
console.error(err.message);
|
|
52
3494
|
process.exit(1);
|
|
53
3495
|
}
|
|
3496
|
+
const ctx = {
|
|
3497
|
+
app,
|
|
3498
|
+
cwd: process.cwd(),
|
|
3499
|
+
findings: [],
|
|
3500
|
+
pkgJson: loadPkgJson(process.cwd()),
|
|
3501
|
+
envKeys: collectEnvKeysFromBundle(bundlePath)
|
|
3502
|
+
};
|
|
3503
|
+
checkEnvVars(ctx);
|
|
3504
|
+
checkRequestId(ctx);
|
|
3505
|
+
checkRoutesLockState(ctx);
|
|
3506
|
+
checkOpenApiNaming(ctx);
|
|
3507
|
+
checkSecurityPlugins(ctx);
|
|
3508
|
+
checkOpenApiExposure(ctx);
|
|
3509
|
+
checkResponseSchemas(ctx);
|
|
3510
|
+
checkHealthCheck(ctx);
|
|
3511
|
+
await cleanup();
|
|
3512
|
+
console.log();
|
|
3513
|
+
console.log(pc.bold(" \u{1F50D} Production-readiness check"));
|
|
3514
|
+
console.log();
|
|
3515
|
+
const sevOrder = { fail: 0, warn: 1, ok: 2 };
|
|
3516
|
+
ctx.findings.sort(
|
|
3517
|
+
(a, b) => sevOrder[a.severity] - sevOrder[b.severity] || a.area.localeCompare(b.area)
|
|
3518
|
+
);
|
|
3519
|
+
const sym = {
|
|
3520
|
+
ok: symbols.ok,
|
|
3521
|
+
warn: symbols.warn,
|
|
3522
|
+
fail: symbols.fail
|
|
3523
|
+
};
|
|
3524
|
+
for (const f of ctx.findings) {
|
|
3525
|
+
const tag = pc.dim(`[${f.area}]`);
|
|
3526
|
+
console.log(` ${sym[f.severity]} ${tag} ${f.message}`);
|
|
3527
|
+
if (f.hint && f.severity !== "ok") {
|
|
3528
|
+
const wrapped = f.hint.replace(/(.{1,80})(\s+|$)/g, "\n " + pc.dim("$1"));
|
|
3529
|
+
console.log(wrapped);
|
|
3530
|
+
}
|
|
3531
|
+
}
|
|
3532
|
+
const fails = ctx.findings.filter((f) => f.severity === "fail").length;
|
|
3533
|
+
const warns = ctx.findings.filter((f) => f.severity === "warn").length;
|
|
3534
|
+
const oks = ctx.findings.filter((f) => f.severity === "ok").length;
|
|
3535
|
+
console.log();
|
|
3536
|
+
const summary = ` ${symbols.ok} ${pluralise(oks, "pass", "passes")}` + pc.dim(" \xB7 ") + (warns > 0 ? `${symbols.warn} ${pluralise(warns, "warning")}` : pc.dim("0 warnings")) + pc.dim(" \xB7 ") + (fails > 0 ? `${symbols.fail} ${pluralise(fails, "failure")}` : pc.dim("0 failures"));
|
|
3537
|
+
console.log(summary);
|
|
3538
|
+
console.log();
|
|
3539
|
+
if (fails > 0) process.exit(1);
|
|
54
3540
|
}
|
|
55
3541
|
async function devServer(entry) {
|
|
56
|
-
const entryPath =
|
|
57
|
-
const outPath =
|
|
3542
|
+
const entryPath = path7.resolve(process.cwd(), entry);
|
|
3543
|
+
const outPath = path7.resolve(process.cwd(), ".axiomify/dev.js");
|
|
58
3544
|
let child = null;
|
|
3545
|
+
let firstBuild = true;
|
|
3546
|
+
const startChild = () => {
|
|
3547
|
+
child = spawn("node", [outPath], { stdio: "inherit" });
|
|
3548
|
+
child.on("error", (err) => {
|
|
3549
|
+
console.error("\u274C Failed to start process:", err);
|
|
3550
|
+
});
|
|
3551
|
+
};
|
|
3552
|
+
const GRACEFUL_KILL_MS = 3e3;
|
|
59
3553
|
const restartServer = () => {
|
|
60
|
-
if (child) {
|
|
3554
|
+
if (child && child.exitCode === null && child.signalCode === null) {
|
|
61
3555
|
child.removeAllListeners("exit");
|
|
62
|
-
|
|
63
|
-
|
|
3556
|
+
const oldChild = child;
|
|
3557
|
+
oldChild.once("exit", () => {
|
|
3558
|
+
startChild();
|
|
64
3559
|
});
|
|
65
|
-
|
|
3560
|
+
oldChild.kill("SIGTERM");
|
|
3561
|
+
const forceKill = setTimeout(() => {
|
|
3562
|
+
if (oldChild.exitCode === null && oldChild.signalCode === null) {
|
|
3563
|
+
oldChild.kill("SIGKILL");
|
|
3564
|
+
}
|
|
3565
|
+
}, GRACEFUL_KILL_MS);
|
|
3566
|
+
forceKill.unref();
|
|
66
3567
|
} else {
|
|
67
|
-
|
|
3568
|
+
startChild();
|
|
68
3569
|
}
|
|
69
3570
|
};
|
|
70
3571
|
const watchPlugin = {
|
|
71
3572
|
name: "watch-plugin",
|
|
72
3573
|
setup(build3) {
|
|
73
3574
|
build3.onEnd((result) => {
|
|
74
|
-
if (result.errors.length
|
|
75
|
-
|
|
3575
|
+
if (result.errors.length === 0) {
|
|
3576
|
+
if (firstBuild) {
|
|
3577
|
+
firstBuild = false;
|
|
3578
|
+
restartServer();
|
|
3579
|
+
} else {
|
|
3580
|
+
console.log("\u{1F504} Changes detected, restarting...");
|
|
3581
|
+
restartServer();
|
|
3582
|
+
}
|
|
76
3583
|
} else {
|
|
77
|
-
|
|
3584
|
+
console.error("\u274C Build failed. Fix errors to trigger a restart.");
|
|
78
3585
|
}
|
|
79
3586
|
});
|
|
80
3587
|
}
|
|
@@ -84,6 +3591,7 @@ async function devServer(entry) {
|
|
|
84
3591
|
entryPoints: [entryPath],
|
|
85
3592
|
bundle: true,
|
|
86
3593
|
platform: "node",
|
|
3594
|
+
format: "cjs",
|
|
87
3595
|
outfile: outPath,
|
|
88
3596
|
external: [.../* @__PURE__ */ new Set([...userExternals, "node:*"])],
|
|
89
3597
|
plugins: [watchPlugin]
|
|
@@ -98,7 +3606,7 @@ async function devServer(entry) {
|
|
|
98
3606
|
child.removeAllListeners("exit");
|
|
99
3607
|
child.kill("SIGTERM");
|
|
100
3608
|
setTimeout(() => {
|
|
101
|
-
if (child &&
|
|
3609
|
+
if (child && child.exitCode === null) child.kill("SIGKILL");
|
|
102
3610
|
}, 2e3).unref();
|
|
103
3611
|
}
|
|
104
3612
|
try {
|
|
@@ -112,43 +3620,383 @@ async function devServer(entry) {
|
|
|
112
3620
|
console.log(`\u{1F440} Axiomify Dev Engine watching for changes...`);
|
|
113
3621
|
await ctx.watch();
|
|
114
3622
|
}
|
|
3623
|
+
function add2(findings, f) {
|
|
3624
|
+
findings.push(f);
|
|
3625
|
+
}
|
|
3626
|
+
function probePort(port) {
|
|
3627
|
+
return new Promise((resolve) => {
|
|
3628
|
+
const server = createServer();
|
|
3629
|
+
server.once("error", (err) => {
|
|
3630
|
+
if (err.code === "EADDRINUSE") resolve("busy");
|
|
3631
|
+
else if (err.code === "EACCES") resolve("denied");
|
|
3632
|
+
else resolve("busy");
|
|
3633
|
+
});
|
|
3634
|
+
server.once("listening", () => {
|
|
3635
|
+
server.close(() => resolve("free"));
|
|
3636
|
+
});
|
|
3637
|
+
server.listen(port, "127.0.0.1");
|
|
3638
|
+
});
|
|
3639
|
+
}
|
|
3640
|
+
function checkNodeVersion(findings) {
|
|
3641
|
+
const major = parseInt(process.versions.node.split(".")[0], 10);
|
|
3642
|
+
if (major < 18) {
|
|
3643
|
+
add2(findings, {
|
|
3644
|
+
severity: "fail",
|
|
3645
|
+
area: "node",
|
|
3646
|
+
message: `Node ${process.versions.node} is below the supported minimum`,
|
|
3647
|
+
hint: "Axiomify requires Node 18 or later. Upgrade via nvm: `nvm install 22 && nvm use 22`."
|
|
3648
|
+
});
|
|
3649
|
+
} else if (major > 22) {
|
|
3650
|
+
add2(findings, {
|
|
3651
|
+
severity: "warn",
|
|
3652
|
+
area: "node",
|
|
3653
|
+
message: `Node ${process.versions.node} \u2014 uWebSockets.js has no prebuilt binary for this version`,
|
|
3654
|
+
hint: "Tests and benchmarks that need a real uWS listener will skip; the framework still builds. For a runnable production deploy, downgrade to Node 22 LTS."
|
|
3655
|
+
});
|
|
3656
|
+
} else {
|
|
3657
|
+
add2(findings, {
|
|
3658
|
+
severity: "ok",
|
|
3659
|
+
area: "node",
|
|
3660
|
+
message: `Node ${process.versions.node} (uWS prebuilt available)`
|
|
3661
|
+
});
|
|
3662
|
+
}
|
|
3663
|
+
}
|
|
3664
|
+
function checkPlatform(findings) {
|
|
3665
|
+
if (process.platform === "linux") {
|
|
3666
|
+
add2(findings, {
|
|
3667
|
+
severity: "ok",
|
|
3668
|
+
area: "platform",
|
|
3669
|
+
message: "Linux \u2014 SO_REUSEPORT clustering supported natively"
|
|
3670
|
+
});
|
|
3671
|
+
} else {
|
|
3672
|
+
add2(findings, {
|
|
3673
|
+
severity: "warn",
|
|
3674
|
+
area: "platform",
|
|
3675
|
+
message: `${process.platform} \u2014 \`listenClustered()\` requires \`allowUserspaceProxy: true\``,
|
|
3676
|
+
hint: "Clustering on non-Linux falls back to a userspace L4 proxy that adds two event-loop hops per byte. Single-process `listen()` is the recommended path on this OS."
|
|
3677
|
+
});
|
|
3678
|
+
}
|
|
3679
|
+
}
|
|
3680
|
+
function checkDependencyDrift(findings) {
|
|
3681
|
+
try {
|
|
3682
|
+
const pkgPath = path7.join(process.cwd(), "package.json");
|
|
3683
|
+
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
|
|
3684
|
+
const all = { ...pkg.dependencies, ...pkg.devDependencies };
|
|
3685
|
+
const axiomifyDeps = Object.entries(all).filter(
|
|
3686
|
+
([k]) => k.startsWith("@axiomify/")
|
|
3687
|
+
);
|
|
3688
|
+
if (axiomifyDeps.length === 0) {
|
|
3689
|
+
add2(findings, {
|
|
3690
|
+
severity: "warn",
|
|
3691
|
+
area: "deps",
|
|
3692
|
+
message: "No @axiomify/* packages found in package.json",
|
|
3693
|
+
hint: "Run this from the root of a project that uses Axiomify."
|
|
3694
|
+
});
|
|
3695
|
+
return;
|
|
3696
|
+
}
|
|
3697
|
+
const versions = new Set(
|
|
3698
|
+
axiomifyDeps.map(([, v]) => v.replace(/^[\^~]/, "").replace(/^\*$/, "workspace"))
|
|
3699
|
+
);
|
|
3700
|
+
if (versions.size > 1) {
|
|
3701
|
+
add2(findings, {
|
|
3702
|
+
severity: "warn",
|
|
3703
|
+
area: "deps",
|
|
3704
|
+
message: `@axiomify/* packages are on ${versions.size} different versions`,
|
|
3705
|
+
hint: "Mixed @axiomify/* versions can cause subtle compat issues. Pin them all to the same version: " + [...versions].join(", ")
|
|
3706
|
+
});
|
|
3707
|
+
} else {
|
|
3708
|
+
add2(findings, {
|
|
3709
|
+
severity: "ok",
|
|
3710
|
+
area: "deps",
|
|
3711
|
+
message: `${axiomifyDeps.length} @axiomify/* packages aligned (${[...versions][0]})`
|
|
3712
|
+
});
|
|
3713
|
+
}
|
|
3714
|
+
} catch {
|
|
3715
|
+
add2(findings, {
|
|
3716
|
+
severity: "warn",
|
|
3717
|
+
area: "deps",
|
|
3718
|
+
message: "Could not read package.json",
|
|
3719
|
+
hint: "Run `axiomify doctor` from a project root."
|
|
3720
|
+
});
|
|
3721
|
+
}
|
|
3722
|
+
}
|
|
3723
|
+
function checkUwsLoads(findings) {
|
|
3724
|
+
try {
|
|
3725
|
+
require_uws();
|
|
3726
|
+
add2(findings, {
|
|
3727
|
+
severity: "ok",
|
|
3728
|
+
area: "uws",
|
|
3729
|
+
message: "uWebSockets.js loads successfully"
|
|
3730
|
+
});
|
|
3731
|
+
} catch (err) {
|
|
3732
|
+
const msg = String(err.message ?? err);
|
|
3733
|
+
if (msg.includes("Cannot find module")) {
|
|
3734
|
+
add2(findings, {
|
|
3735
|
+
severity: "warn",
|
|
3736
|
+
area: "uws",
|
|
3737
|
+
message: "uWebSockets.js is not installed in this project",
|
|
3738
|
+
hint: "It is a peer dependency of `@axiomify/native`. Install via `npm install --save-optional uWebSockets.js` (the package handles platform selection)."
|
|
3739
|
+
});
|
|
3740
|
+
} else {
|
|
3741
|
+
add2(findings, {
|
|
3742
|
+
severity: "fail",
|
|
3743
|
+
area: "uws",
|
|
3744
|
+
message: "uWebSockets.js native binding failed to load",
|
|
3745
|
+
hint: msg.length > 200 ? msg.slice(0, 200) + "\u2026" : msg
|
|
3746
|
+
});
|
|
3747
|
+
}
|
|
3748
|
+
}
|
|
3749
|
+
}
|
|
3750
|
+
async function checkPortAvailability(findings) {
|
|
3751
|
+
const port = parseInt(process.env.PORT ?? "3000", 10);
|
|
3752
|
+
const state = await probePort(port);
|
|
3753
|
+
if (state === "free") {
|
|
3754
|
+
add2(findings, {
|
|
3755
|
+
severity: "ok",
|
|
3756
|
+
area: "port",
|
|
3757
|
+
message: `Port ${port} is available on 127.0.0.1`
|
|
3758
|
+
});
|
|
3759
|
+
} else if (state === "busy") {
|
|
3760
|
+
add2(findings, {
|
|
3761
|
+
severity: "warn",
|
|
3762
|
+
area: "port",
|
|
3763
|
+
message: `Port ${port} is already in use`,
|
|
3764
|
+
hint: "Stop the conflicting process or set `PORT` to a different value."
|
|
3765
|
+
});
|
|
3766
|
+
} else {
|
|
3767
|
+
add2(findings, {
|
|
3768
|
+
severity: "warn",
|
|
3769
|
+
area: "port",
|
|
3770
|
+
message: `Port ${port}: bind denied (permission)`,
|
|
3771
|
+
hint: "Ports below 1024 typically require root. Use a port \u2265 1024 in development."
|
|
3772
|
+
});
|
|
3773
|
+
}
|
|
3774
|
+
}
|
|
3775
|
+
function checkBuildArtifacts(findings) {
|
|
3776
|
+
const dist = path7.join(process.cwd(), "dist");
|
|
3777
|
+
if (fs.existsSync(dist)) {
|
|
3778
|
+
add2(findings, {
|
|
3779
|
+
severity: "ok",
|
|
3780
|
+
area: "build",
|
|
3781
|
+
message: "dist/ exists (recent `axiomify build`)"
|
|
3782
|
+
});
|
|
3783
|
+
} else {
|
|
3784
|
+
add2(findings, {
|
|
3785
|
+
severity: "warn",
|
|
3786
|
+
area: "build",
|
|
3787
|
+
message: "No dist/ directory \u2014 production build has not been run",
|
|
3788
|
+
hint: "Run `axiomify build` before deploying."
|
|
3789
|
+
});
|
|
3790
|
+
}
|
|
3791
|
+
}
|
|
3792
|
+
async function runDoctor() {
|
|
3793
|
+
const findings = [];
|
|
3794
|
+
checkNodeVersion(findings);
|
|
3795
|
+
checkPlatform(findings);
|
|
3796
|
+
checkDependencyDrift(findings);
|
|
3797
|
+
checkUwsLoads(findings);
|
|
3798
|
+
checkBuildArtifacts(findings);
|
|
3799
|
+
await checkPortAvailability(findings);
|
|
3800
|
+
console.log();
|
|
3801
|
+
console.log(pc.bold(" \u{1FA7A} Axiomify doctor"));
|
|
3802
|
+
console.log();
|
|
3803
|
+
const sevOrder = { fail: 0, warn: 1, ok: 2 };
|
|
3804
|
+
findings.sort(
|
|
3805
|
+
(a, b) => sevOrder[a.severity] - sevOrder[b.severity] || a.area.localeCompare(b.area)
|
|
3806
|
+
);
|
|
3807
|
+
const sym = {
|
|
3808
|
+
ok: symbols.ok,
|
|
3809
|
+
warn: symbols.warn,
|
|
3810
|
+
fail: symbols.fail
|
|
3811
|
+
};
|
|
3812
|
+
for (const f of findings) {
|
|
3813
|
+
const tag = pc.dim(`[${f.area}]`);
|
|
3814
|
+
console.log(` ${sym[f.severity]} ${tag} ${f.message}`);
|
|
3815
|
+
if (f.hint && f.severity !== "ok") {
|
|
3816
|
+
const wrapped = f.hint.replace(/(.{1,80})(\s+|$)/g, "\n " + pc.dim("$1"));
|
|
3817
|
+
console.log(wrapped);
|
|
3818
|
+
}
|
|
3819
|
+
}
|
|
3820
|
+
const fails = findings.filter((f) => f.severity === "fail").length;
|
|
3821
|
+
const warns = findings.filter((f) => f.severity === "warn").length;
|
|
3822
|
+
const oks = findings.filter((f) => f.severity === "ok").length;
|
|
3823
|
+
console.log();
|
|
3824
|
+
console.log(
|
|
3825
|
+
` ${symbols.ok} ${pluralise(oks, "pass", "passes")}` + pc.dim(" \xB7 ") + (warns > 0 ? `${symbols.warn} ${pluralise(warns, "warning")}` : pc.dim("0 warnings")) + pc.dim(" \xB7 ") + (fails > 0 ? `${symbols.fail} ${pluralise(fails, "failure")}` : pc.dim("0 failures"))
|
|
3826
|
+
);
|
|
3827
|
+
console.log();
|
|
3828
|
+
if (fails > 0) process.exit(1);
|
|
3829
|
+
}
|
|
3830
|
+
var DEV_COMMAND_BY_PM = {
|
|
3831
|
+
npm: "npm run dev",
|
|
3832
|
+
pnpm: "pnpm dev",
|
|
3833
|
+
yarn: "yarn dev"
|
|
3834
|
+
};
|
|
115
3835
|
async function initProject(targetDir, options = {}) {
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
3836
|
+
console.log(pc.cyan(pc.bold("\n\u{1F680} Axiomify Project Initializer\n")));
|
|
3837
|
+
const questions = [];
|
|
3838
|
+
if (!targetDir) {
|
|
3839
|
+
questions.push({
|
|
3840
|
+
type: "input",
|
|
3841
|
+
name: "projectName",
|
|
3842
|
+
message: "What is your project name?",
|
|
3843
|
+
initial: "my-axiomify-app"
|
|
3844
|
+
});
|
|
3845
|
+
}
|
|
3846
|
+
questions.push(
|
|
3847
|
+
{
|
|
3848
|
+
type: "input",
|
|
3849
|
+
name: "description",
|
|
3850
|
+
message: "Project description",
|
|
3851
|
+
initial: "A production-ready Axiomify service"
|
|
3852
|
+
},
|
|
3853
|
+
{
|
|
3854
|
+
type: "confirm",
|
|
3855
|
+
name: "useEslint",
|
|
3856
|
+
message: "Add ESLint + Prettier + EditorConfig?",
|
|
3857
|
+
initial: true
|
|
3858
|
+
},
|
|
3859
|
+
{
|
|
3860
|
+
type: "select",
|
|
3861
|
+
name: "packageManager",
|
|
3862
|
+
message: "Preferred package manager?",
|
|
3863
|
+
choices: ["npm", "pnpm", "yarn"],
|
|
3864
|
+
initial: 0
|
|
3865
|
+
},
|
|
3866
|
+
{
|
|
3867
|
+
type: "confirm",
|
|
3868
|
+
name: "useGit",
|
|
3869
|
+
message: "Initialize a git repository?",
|
|
3870
|
+
initial: true
|
|
3871
|
+
},
|
|
3872
|
+
{
|
|
3873
|
+
type: "confirm",
|
|
3874
|
+
name: "installDeps",
|
|
3875
|
+
message: "Install dependencies automatically?",
|
|
3876
|
+
initial: true
|
|
3877
|
+
}
|
|
3878
|
+
);
|
|
3879
|
+
const answers = await prompt(questions);
|
|
3880
|
+
const projectName = targetDir || answers.projectName;
|
|
3881
|
+
if (!projectName || projectName.trim().length === 0) {
|
|
3882
|
+
console.error(
|
|
3883
|
+
pc.red(
|
|
3884
|
+
"\u274C A project name is required. Aborting to avoid writing into the current directory."
|
|
3885
|
+
)
|
|
3886
|
+
);
|
|
3887
|
+
process.exit(1);
|
|
3888
|
+
}
|
|
3889
|
+
if (
|
|
3890
|
+
// eslint-disable-next-line no-control-regex
|
|
3891
|
+
/[<>:"|?*\u0000-\u001f]/.test(projectName) || projectName.includes("..")
|
|
3892
|
+
) {
|
|
125
3893
|
console.error(
|
|
126
|
-
|
|
3894
|
+
pc.red(
|
|
3895
|
+
`\u274C Invalid project name: "${projectName}". Names cannot contain path traversal or control characters.`
|
|
3896
|
+
)
|
|
127
3897
|
);
|
|
128
3898
|
process.exit(1);
|
|
129
3899
|
}
|
|
3900
|
+
const dir = path7.resolve(process.cwd(), projectName);
|
|
3901
|
+
if (existsSync(dir) && !options.force && targetDir) {
|
|
3902
|
+
const targets = [
|
|
3903
|
+
path7.join(dir, "package.json"),
|
|
3904
|
+
path7.join(dir, "tsconfig.json"),
|
|
3905
|
+
path7.join(dir, "src", "index.ts")
|
|
3906
|
+
];
|
|
3907
|
+
const collisions = targets.filter((p) => existsSync(p));
|
|
3908
|
+
if (collisions.length > 0) {
|
|
3909
|
+
console.error(
|
|
3910
|
+
pc.red("\u274C Refusing to overwrite existing files:\n") + collisions.map((p) => ` - ${p}`).join("\n") + pc.yellow(
|
|
3911
|
+
"\n\nRe-run with '--force' if you really want to replace them."
|
|
3912
|
+
)
|
|
3913
|
+
);
|
|
3914
|
+
process.exit(1);
|
|
3915
|
+
}
|
|
3916
|
+
}
|
|
3917
|
+
await fs5.mkdir(path7.join(dir, "src"), { recursive: true });
|
|
3918
|
+
const AXIOMIFY_VERSION = `^${package_default.version}`;
|
|
3919
|
+
const adapterPackage = "@axiomify/native";
|
|
3920
|
+
const adapterImport = "import { NativeAdapter } from '@axiomify/native';";
|
|
3921
|
+
const adapterInit = "const server = new NativeAdapter(app, { port: 3000 });\n server.listen(() => console.log(' Axiomify Native on :3000'));";
|
|
130
3922
|
const pkgJson = {
|
|
131
|
-
name:
|
|
3923
|
+
name: projectName,
|
|
132
3924
|
version: "1.0.0",
|
|
133
3925
|
private: true,
|
|
3926
|
+
description: answers.description,
|
|
134
3927
|
scripts: {
|
|
135
3928
|
dev: "axiomify dev src/index.ts",
|
|
136
3929
|
build: "axiomify build src/index.ts",
|
|
137
3930
|
start: "node dist/index.js",
|
|
138
|
-
routes: "axiomify routes src/index.ts"
|
|
3931
|
+
routes: "axiomify routes src/index.ts",
|
|
3932
|
+
typecheck: "tsc --noEmit"
|
|
139
3933
|
},
|
|
140
3934
|
dependencies: {
|
|
141
|
-
"@axiomify/core":
|
|
142
|
-
|
|
3935
|
+
"@axiomify/core": AXIOMIFY_VERSION,
|
|
3936
|
+
[adapterPackage]: AXIOMIFY_VERSION,
|
|
3937
|
+
// Inject selected adapter
|
|
3938
|
+
"@axiomify/helmet": AXIOMIFY_VERSION,
|
|
3939
|
+
"@axiomify/cors": AXIOMIFY_VERSION,
|
|
3940
|
+
"@axiomify/logger": AXIOMIFY_VERSION,
|
|
3941
|
+
"@axiomify/security": AXIOMIFY_VERSION,
|
|
3942
|
+
"@axiomify/rate-limit": AXIOMIFY_VERSION,
|
|
3943
|
+
"@axiomify/fingerprint": AXIOMIFY_VERSION
|
|
143
3944
|
},
|
|
144
3945
|
devDependencies: {
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
typescript: "^6.0.0",
|
|
149
|
-
"@types/node": "^22.0.0"
|
|
3946
|
+
typescript: "^5.4.0",
|
|
3947
|
+
"@types/node": "^22.0.0",
|
|
3948
|
+
"@axiomify/cli": AXIOMIFY_VERSION
|
|
150
3949
|
}
|
|
151
3950
|
};
|
|
3951
|
+
if (answers.useEslint) {
|
|
3952
|
+
pkgJson.devDependencies = {
|
|
3953
|
+
...pkgJson.devDependencies,
|
|
3954
|
+
eslint: "^8.57.0",
|
|
3955
|
+
prettier: "^3.0.0",
|
|
3956
|
+
"eslint-config-prettier": "^9.0.0",
|
|
3957
|
+
"eslint-plugin-prettier": "^5.0.0",
|
|
3958
|
+
"@typescript-eslint/eslint-plugin": "^7.0.0",
|
|
3959
|
+
"@typescript-eslint/parser": "^7.0.0"
|
|
3960
|
+
};
|
|
3961
|
+
pkgJson.scripts.lint = "eslint . --ext .ts";
|
|
3962
|
+
pkgJson.scripts["lint:fix"] = "eslint . --ext .ts --fix";
|
|
3963
|
+
pkgJson.scripts.format = "prettier --write .";
|
|
3964
|
+
const eslintConfig = `module.exports = {
|
|
3965
|
+
root: true,
|
|
3966
|
+
parser: '@typescript-eslint/parser',
|
|
3967
|
+
plugins: ['@typescript-eslint', 'prettier'],
|
|
3968
|
+
extends: [
|
|
3969
|
+
'eslint:recommended',
|
|
3970
|
+
'plugin:@typescript-eslint/recommended',
|
|
3971
|
+
'plugin:prettier/recommended',
|
|
3972
|
+
],
|
|
3973
|
+
parserOptions: {
|
|
3974
|
+
ecmaVersion: 2022,
|
|
3975
|
+
sourceType: 'module',
|
|
3976
|
+
},
|
|
3977
|
+
env: {
|
|
3978
|
+
node: true,
|
|
3979
|
+
es2022: true,
|
|
3980
|
+
},
|
|
3981
|
+
};`;
|
|
3982
|
+
const prettierConfig = `{
|
|
3983
|
+
"semi": true,
|
|
3984
|
+
"trailingComma": "all",
|
|
3985
|
+
"singleQuote": true,
|
|
3986
|
+
"printWidth": 100,
|
|
3987
|
+
"tabWidth": 2
|
|
3988
|
+
}`;
|
|
3989
|
+
await fs5.writeFile(path7.join(dir, ".eslintrc.cjs"), eslintConfig);
|
|
3990
|
+
await fs5.writeFile(path7.join(dir, ".prettierrc"), prettierConfig);
|
|
3991
|
+
await fs5.writeFile(
|
|
3992
|
+
path7.join(dir, ".prettierignore"),
|
|
3993
|
+
"dist\nnode_modules\ncoverage\n"
|
|
3994
|
+
);
|
|
3995
|
+
await fs5.writeFile(
|
|
3996
|
+
path7.join(dir, ".editorconfig"),
|
|
3997
|
+
"root = true\n\n[*]\ncharset = utf-8\nend_of_line = lf\nindent_style = space\nindent_size = 2\ninsert_final_newline = true\ntrim_trailing_whitespace = true\n"
|
|
3998
|
+
);
|
|
3999
|
+
}
|
|
152
4000
|
const tsConfig = {
|
|
153
4001
|
compilerOptions: {
|
|
154
4002
|
target: "ES2022",
|
|
@@ -158,100 +4006,775 @@ async function initProject(targetDir, options = {}) {
|
|
|
158
4006
|
esModuleInterop: true,
|
|
159
4007
|
skipLibCheck: true,
|
|
160
4008
|
forceConsistentCasingInFileNames: true,
|
|
161
|
-
outDir: "./dist"
|
|
4009
|
+
outDir: "./dist",
|
|
4010
|
+
rootDir: "./src",
|
|
4011
|
+
types: ["node"]
|
|
162
4012
|
},
|
|
163
4013
|
include: ["src/**/*"]
|
|
164
4014
|
};
|
|
165
|
-
const indexTs = `import { Axiomify
|
|
166
|
-
|
|
4015
|
+
const indexTs = `import { Axiomify } from '@axiomify/core';
|
|
4016
|
+
${adapterImport}
|
|
4017
|
+
import { useHelmet } from '@axiomify/helmet';
|
|
4018
|
+
import { useCors } from '@axiomify/cors';
|
|
4019
|
+
import { useLogger } from '@axiomify/logger';
|
|
4020
|
+
import { useSecurity } from '@axiomify/security';
|
|
4021
|
+
import { useRateLimit, MemoryStore } from '@axiomify/rate-limit';
|
|
4022
|
+
import { useFingerprint } from '@axiomify/fingerprint';
|
|
167
4023
|
|
|
168
|
-
|
|
169
|
-
export const app = new Axiomify();
|
|
4024
|
+
export const app = new Axiomify();
|
|
170
4025
|
|
|
171
|
-
app
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
handler: async (req, res) => {
|
|
175
|
-
res.status(200).send({ status: 'healthy', timestamp: Date.now() }, 'System Operational');
|
|
176
|
-
}
|
|
177
|
-
});
|
|
4026
|
+
useHelmet(app);
|
|
4027
|
+
useCors(app, { credentials: false });
|
|
4028
|
+
useSecurity(app);
|
|
178
4029
|
|
|
179
|
-
//
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
4030
|
+
// PRODUCTION NOTE
|
|
4031
|
+
// MemoryStore is per-process. For production, swap this for a RedisStore.
|
|
4032
|
+
useRateLimit(app, { max: 100, windowMs: 60_000, store: new MemoryStore() });
|
|
4033
|
+
useFingerprint(app);
|
|
4034
|
+
useLogger(app);
|
|
4035
|
+
|
|
4036
|
+
app.route({
|
|
4037
|
+
method: 'GET',
|
|
4038
|
+
path: '/health',
|
|
4039
|
+
handler: async (_req, res) => {
|
|
4040
|
+
res.status(200).send({ status: 'healthy' }, 'System Operational');
|
|
4041
|
+
},
|
|
4042
|
+
});
|
|
4043
|
+
|
|
4044
|
+
if (require.main === module) {
|
|
4045
|
+
${adapterInit}
|
|
4046
|
+
}
|
|
4047
|
+
`;
|
|
4048
|
+
const gitignore = [
|
|
4049
|
+
"node_modules",
|
|
4050
|
+
"dist",
|
|
4051
|
+
".axiomify",
|
|
4052
|
+
".env",
|
|
4053
|
+
".env.local",
|
|
4054
|
+
"coverage",
|
|
4055
|
+
"*.log"
|
|
4056
|
+
].join("\n") + "\n";
|
|
4057
|
+
await fs5.writeFile(
|
|
4058
|
+
path7.join(dir, "package.json"),
|
|
187
4059
|
JSON.stringify(pkgJson, null, 2)
|
|
188
4060
|
);
|
|
189
|
-
await
|
|
190
|
-
|
|
4061
|
+
await fs5.writeFile(
|
|
4062
|
+
path7.join(dir, "tsconfig.json"),
|
|
191
4063
|
JSON.stringify(tsConfig, null, 2)
|
|
192
4064
|
);
|
|
193
|
-
await
|
|
194
|
-
|
|
195
|
-
console.log(
|
|
4065
|
+
await fs5.writeFile(path7.join(dir, "src", "index.ts"), indexTs);
|
|
4066
|
+
await fs5.writeFile(path7.join(dir, ".gitignore"), gitignore);
|
|
4067
|
+
console.log(pc.green(`
|
|
4068
|
+
\u2705 Axiomify project initialized in ${pc.bold(dir)}`));
|
|
4069
|
+
if (answers.useGit && !existsSync(path7.join(dir, ".git"))) {
|
|
4070
|
+
try {
|
|
4071
|
+
await execa("git", ["init"], { cwd: dir });
|
|
4072
|
+
console.log(pc.green("\u2705 Git repository initialized"));
|
|
4073
|
+
} catch {
|
|
4074
|
+
console.log(pc.yellow("\u26A0\uFE0F Could not initialize git repository."));
|
|
4075
|
+
}
|
|
4076
|
+
}
|
|
4077
|
+
if (answers.installDeps) {
|
|
4078
|
+
const pkgManager = answers.packageManager || "npm";
|
|
4079
|
+
const installArgs = ["install"];
|
|
4080
|
+
console.log(pc.cyan(`\u{1F4E6} Installing dependencies using ${pkgManager}...`));
|
|
4081
|
+
try {
|
|
4082
|
+
await execa(pkgManager, installArgs, { cwd: dir, stdio: "inherit" });
|
|
4083
|
+
console.log(pc.green("\u2705 Dependencies installed successfully!"));
|
|
4084
|
+
} catch {
|
|
4085
|
+
console.error(
|
|
4086
|
+
pc.red("\u274C Failed to install dependencies. Please install manually.")
|
|
4087
|
+
);
|
|
4088
|
+
}
|
|
4089
|
+
} else {
|
|
4090
|
+
console.log(
|
|
4091
|
+
pc.yellow(
|
|
4092
|
+
`
|
|
4093
|
+
\u{1F4E6} Run "cd ${projectName} && ${answers.packageManager || "npm"} install" to get started.`
|
|
4094
|
+
)
|
|
4095
|
+
);
|
|
4096
|
+
}
|
|
4097
|
+
const devCommand = DEV_COMMAND_BY_PM[answers.packageManager || "npm"];
|
|
4098
|
+
console.log(
|
|
4099
|
+
pc.cyan(`
|
|
4100
|
+
\u{1F525} Run "${devCommand}" to start your development server!`)
|
|
4101
|
+
);
|
|
196
4102
|
}
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
4103
|
+
var RULES = [
|
|
4104
|
+
{
|
|
4105
|
+
id: "meta-to-openapi",
|
|
4106
|
+
description: "`meta:` route field renamed to `openapi:` (OpenAPI 3.0.3 Operation Object terminology)",
|
|
4107
|
+
// Match `meta: {` or `meta:{` after whitespace/comma — avoid matching
|
|
4108
|
+
// unrelated `meta:` fields in other object literals by requiring an
|
|
4109
|
+
// adjacent route-definition cue (method, path, schema, handler nearby).
|
|
4110
|
+
// To stay simple and conservative, only rewrite when the line starts
|
|
4111
|
+
// with optional whitespace + `meta:` (the common formatting).
|
|
4112
|
+
match: /^(\s*)meta:(\s*\{)/gm,
|
|
4113
|
+
replace: "$1openapi:$2"
|
|
4114
|
+
},
|
|
4115
|
+
{
|
|
4116
|
+
id: "useSwagger-import",
|
|
4117
|
+
description: "`useSwagger` import \u2192 `useOpenAPI` (the function was never named `useSwagger` in shipped code \u2014 docs were wrong)",
|
|
4118
|
+
match: /\buseSwagger\b/g,
|
|
4119
|
+
replace: "useOpenAPI"
|
|
4120
|
+
},
|
|
4121
|
+
{
|
|
4122
|
+
id: "routePrefix-option",
|
|
4123
|
+
description: "`routePrefix:` \u2192 `prefix:` on `useOpenAPI()` options",
|
|
4124
|
+
match: /(\buseOpenAPI\s*\([\s\S]*?)\brouteprefix(\s*:)/gi,
|
|
4125
|
+
// Naive: just rename the property when it appears inside a useOpenAPI() call.
|
|
4126
|
+
// The capture-group lookbehind avoids touching unrelated `routePrefix`
|
|
4127
|
+
// properties in other contexts.
|
|
4128
|
+
replace: (_match, before, suffix) => `${before}prefix${suffix}`
|
|
4129
|
+
},
|
|
4130
|
+
{
|
|
4131
|
+
id: "RouteMeta-type",
|
|
4132
|
+
description: "`RouteMeta` type \u2192 `OpenApiOperation` (alias kept through 5.x, removed in 6.0)",
|
|
4133
|
+
// Match `RouteMeta` only as a type position (after `:` or `<` or
|
|
4134
|
+
// `as`) — avoids hitting an unrelated variable named `RouteMeta`.
|
|
4135
|
+
match: /(:\s*|<\s*|\bas\s+)RouteMeta\b/g,
|
|
4136
|
+
replace: "$1OpenApiOperation"
|
|
4137
|
+
},
|
|
4138
|
+
{
|
|
4139
|
+
id: "AppPlugin-type",
|
|
4140
|
+
description: "`AppPlugin` type alias \u2192 `AppConfigurator` (removed in 5.0; runtime accepts 1-arg fns identically)",
|
|
4141
|
+
match: /(:\s*|<\s*|\bas\s+)AppPlugin\b/g,
|
|
4142
|
+
replace: "$1AppConfigurator"
|
|
4143
|
+
}
|
|
4144
|
+
];
|
|
4145
|
+
async function listSourceFiles(rootAbs) {
|
|
4146
|
+
const out = [];
|
|
4147
|
+
const skip = /* @__PURE__ */ new Set(["node_modules", ".git", "dist", "build", ".axiomify", "coverage"]);
|
|
4148
|
+
const walk = async (dir) => {
|
|
4149
|
+
let entries;
|
|
210
4150
|
try {
|
|
211
|
-
|
|
212
|
-
} catch
|
|
4151
|
+
entries = await fs5.readdir(dir, { withFileTypes: true });
|
|
4152
|
+
} catch {
|
|
4153
|
+
return;
|
|
4154
|
+
}
|
|
4155
|
+
for (const e of entries) {
|
|
4156
|
+
if (e.isDirectory()) {
|
|
4157
|
+
if (skip.has(e.name) || e.name.startsWith(".")) continue;
|
|
4158
|
+
await walk(path7.join(dir, e.name));
|
|
4159
|
+
} else if (e.isFile()) {
|
|
4160
|
+
const ext = path7.extname(e.name);
|
|
4161
|
+
if ([".ts", ".tsx", ".js", ".mjs", ".cjs"].includes(ext)) {
|
|
4162
|
+
out.push(path7.join(dir, e.name));
|
|
4163
|
+
}
|
|
4164
|
+
}
|
|
4165
|
+
}
|
|
4166
|
+
};
|
|
4167
|
+
await walk(rootAbs);
|
|
4168
|
+
return out;
|
|
4169
|
+
}
|
|
4170
|
+
function applyRules(src) {
|
|
4171
|
+
let updated = src;
|
|
4172
|
+
const counts = {};
|
|
4173
|
+
for (const rule of RULES) {
|
|
4174
|
+
const before = updated;
|
|
4175
|
+
if (typeof rule.replace === "string") {
|
|
4176
|
+
updated = updated.replace(rule.match, rule.replace);
|
|
4177
|
+
} else {
|
|
4178
|
+
updated = updated.replace(rule.match, rule.replace);
|
|
4179
|
+
}
|
|
4180
|
+
if (updated !== before) {
|
|
4181
|
+
const matches = before.match(rule.match);
|
|
4182
|
+
counts[rule.id] = matches ? matches.length : 1;
|
|
4183
|
+
}
|
|
4184
|
+
}
|
|
4185
|
+
return { updated, counts };
|
|
4186
|
+
}
|
|
4187
|
+
function renderUnifiedDiff(file, original, updated) {
|
|
4188
|
+
if (original === updated) return "";
|
|
4189
|
+
const origLines = original.split("\n");
|
|
4190
|
+
const updatedLines = updated.split("\n");
|
|
4191
|
+
const out = [];
|
|
4192
|
+
out.push(pc.bold(`--- ${file}`));
|
|
4193
|
+
out.push(pc.bold(`+++ ${file}`));
|
|
4194
|
+
const max = Math.max(origLines.length, updatedLines.length);
|
|
4195
|
+
for (let i = 0; i < max; i++) {
|
|
4196
|
+
const a = origLines[i];
|
|
4197
|
+
const b = updatedLines[i];
|
|
4198
|
+
if (a === b) continue;
|
|
4199
|
+
if (a !== void 0) out.push(pc.red("- " + a));
|
|
4200
|
+
if (b !== void 0) out.push(pc.green("+ " + b));
|
|
4201
|
+
}
|
|
4202
|
+
return out.join("\n");
|
|
4203
|
+
}
|
|
4204
|
+
async function runMigrate(opts = {}) {
|
|
4205
|
+
const dir = opts.dir ?? "src";
|
|
4206
|
+
const rootAbs = path7.resolve(process.cwd(), dir);
|
|
4207
|
+
try {
|
|
4208
|
+
const stat = await fs5.stat(rootAbs);
|
|
4209
|
+
if (!stat.isDirectory()) throw new Error("not a directory");
|
|
4210
|
+
} catch {
|
|
4211
|
+
console.error(
|
|
4212
|
+
pc.red(`\u2717 ${dir} does not exist or is not a directory.`),
|
|
4213
|
+
`
|
|
4214
|
+
Run from a project root that contains the directory you want to migrate.`
|
|
4215
|
+
);
|
|
4216
|
+
process.exit(1);
|
|
4217
|
+
}
|
|
4218
|
+
const files = await listSourceFiles(rootAbs);
|
|
4219
|
+
if (files.length === 0) {
|
|
4220
|
+
console.log(`${symbols.info} No source files found under ${pc.cyan(dir)}.`);
|
|
4221
|
+
return;
|
|
4222
|
+
}
|
|
4223
|
+
const results = [];
|
|
4224
|
+
for (const f of files) {
|
|
4225
|
+
const original = await fs5.readFile(f, "utf8");
|
|
4226
|
+
const { updated, counts } = applyRules(original);
|
|
4227
|
+
if (Object.keys(counts).length > 0) {
|
|
4228
|
+
results.push({ file: f, counts, original, updated });
|
|
4229
|
+
}
|
|
4230
|
+
}
|
|
4231
|
+
console.log();
|
|
4232
|
+
console.log(pc.bold(" \u{1F504} Axiomify v4 \u2192 v5 migration"));
|
|
4233
|
+
console.log(
|
|
4234
|
+
pc.dim(
|
|
4235
|
+
` Scanned ${pluralise(files.length, "file")} under ${path7.relative(process.cwd(), rootAbs) || "."}/.
|
|
4236
|
+
`
|
|
4237
|
+
)
|
|
4238
|
+
);
|
|
4239
|
+
if (results.length === 0) {
|
|
4240
|
+
console.log(` ${symbols.ok} Nothing to migrate \u2014 looks like you're already on the v5 shape.`);
|
|
4241
|
+
console.log();
|
|
4242
|
+
return;
|
|
4243
|
+
}
|
|
4244
|
+
const totalsByRule = {};
|
|
4245
|
+
for (const r of results) {
|
|
4246
|
+
for (const [rule, n] of Object.entries(r.counts)) {
|
|
4247
|
+
totalsByRule[rule] = (totalsByRule[rule] ?? 0) + n;
|
|
4248
|
+
}
|
|
4249
|
+
}
|
|
4250
|
+
for (const rule of RULES) {
|
|
4251
|
+
const count = totalsByRule[rule.id];
|
|
4252
|
+
if (!count) continue;
|
|
4253
|
+
console.log(
|
|
4254
|
+
` ${pc.cyan(rule.id)} ${pc.dim("\u2014")} ${rule.description}`
|
|
4255
|
+
);
|
|
4256
|
+
console.log(
|
|
4257
|
+
` ${symbols.bullet} ${pluralise(count, "change")} across ${pluralise(
|
|
4258
|
+
results.filter((r) => r.counts[rule.id]).length,
|
|
4259
|
+
"file"
|
|
4260
|
+
)}`
|
|
4261
|
+
);
|
|
4262
|
+
}
|
|
4263
|
+
console.log();
|
|
4264
|
+
if (opts.reportOnly) {
|
|
4265
|
+
console.log(pc.dim(" --report-only: no files were modified."));
|
|
4266
|
+
console.log();
|
|
4267
|
+
return;
|
|
4268
|
+
}
|
|
4269
|
+
if (opts.dryRun) {
|
|
4270
|
+
for (const r of results) {
|
|
4271
|
+
const rel = path7.relative(process.cwd(), r.file);
|
|
4272
|
+
console.log(renderUnifiedDiff(rel, r.original, r.updated));
|
|
4273
|
+
console.log();
|
|
4274
|
+
}
|
|
4275
|
+
console.log(
|
|
4276
|
+
`${symbols.info} ${pluralise(results.length, "file")} would be modified. Re-run without ${pc.cyan("--dry-run")} to apply.`
|
|
4277
|
+
);
|
|
4278
|
+
console.log();
|
|
4279
|
+
return;
|
|
4280
|
+
}
|
|
4281
|
+
for (const r of results) {
|
|
4282
|
+
await fs5.writeFile(r.file, r.updated, "utf8");
|
|
4283
|
+
console.log(` ${symbols.ok} ${pc.green("Updated")} ${path7.relative(process.cwd(), r.file)}`);
|
|
4284
|
+
}
|
|
4285
|
+
console.log();
|
|
4286
|
+
console.log(
|
|
4287
|
+
` ${symbols.ok} ${pluralise(results.length, "file")} migrated, ${pluralise(
|
|
4288
|
+
Object.values(totalsByRule).reduce((a, b) => a + b, 0),
|
|
4289
|
+
"total change"
|
|
4290
|
+
)} applied.`
|
|
4291
|
+
);
|
|
4292
|
+
console.log();
|
|
4293
|
+
console.log(pc.dim(" Manual review needed for:"));
|
|
4294
|
+
console.log(
|
|
4295
|
+
pc.dim(
|
|
4296
|
+
` ${symbols.bullet} Dangling \`AppPlugin\` / \`RouteMeta\` in import statements \u2014 the codemod renames`
|
|
4297
|
+
)
|
|
4298
|
+
);
|
|
4299
|
+
console.log(
|
|
4300
|
+
pc.dim(
|
|
4301
|
+
` type USAGES but not the import bindings themselves. TypeScript flags the unused`
|
|
4302
|
+
)
|
|
4303
|
+
);
|
|
4304
|
+
console.log(
|
|
4305
|
+
pc.dim(
|
|
4306
|
+
` import; remove it (or run \`tsc --noUnusedLocals\` once and let your editor clean up).`
|
|
4307
|
+
)
|
|
4308
|
+
);
|
|
4309
|
+
console.log(
|
|
4310
|
+
pc.dim(
|
|
4311
|
+
` ${symbols.bullet} 5-arg positional \`SerializerFn\` signatures \u2014 the function body needs by-hand updates`
|
|
4312
|
+
)
|
|
4313
|
+
);
|
|
4314
|
+
console.log(
|
|
4315
|
+
pc.dim(
|
|
4316
|
+
` ${symbols.bullet} \`new Axiomify()\` callers that relied on automatic \`X-Request-Id\` injection`
|
|
4317
|
+
)
|
|
4318
|
+
);
|
|
4319
|
+
console.log(
|
|
4320
|
+
pc.dim(
|
|
4321
|
+
` ${symbols.bullet} JWT secrets \u2014 verify they are \u2265 32 BYTES (not chars) per RFC 7518 \xA73.2`
|
|
4322
|
+
)
|
|
4323
|
+
);
|
|
4324
|
+
console.log();
|
|
4325
|
+
console.log(
|
|
4326
|
+
` See ${pc.cyan("docs/migration-v4-to-v5.md")} for the full guide and ` + pc.cyan("axiomify check") + " to verify the migrated app."
|
|
4327
|
+
);
|
|
4328
|
+
console.log();
|
|
4329
|
+
}
|
|
4330
|
+
async function jsonToYaml(obj) {
|
|
4331
|
+
const emit = (v, indent) => {
|
|
4332
|
+
const pad2 = " ".repeat(indent);
|
|
4333
|
+
if (v === null) return "null";
|
|
4334
|
+
if (typeof v === "boolean" || typeof v === "number") return String(v);
|
|
4335
|
+
if (typeof v === "string") {
|
|
4336
|
+
if (/[:#\n\r\t"'{}[\]&*!|>%@`]|^\s|\s$/.test(v) || v === "") {
|
|
4337
|
+
return JSON.stringify(v);
|
|
4338
|
+
}
|
|
4339
|
+
return v;
|
|
4340
|
+
}
|
|
4341
|
+
if (Array.isArray(v)) {
|
|
4342
|
+
if (v.length === 0) return "[]";
|
|
4343
|
+
return v.map((item) => `
|
|
4344
|
+
${pad2}- ${emit(item, indent + 1).replace(/^/gm, " ").trimStart()}`).join("");
|
|
213
4345
|
}
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
4346
|
+
if (typeof v === "object") {
|
|
4347
|
+
const keys = Object.keys(v);
|
|
4348
|
+
if (keys.length === 0) return "{}";
|
|
4349
|
+
return keys.map((k) => {
|
|
4350
|
+
const val = v[k];
|
|
4351
|
+
const rendered = emit(val, indent + 1);
|
|
4352
|
+
if (rendered.startsWith("\n")) return `
|
|
4353
|
+
${pad2}${k}:${rendered}`;
|
|
4354
|
+
return `
|
|
4355
|
+
${pad2}${k}: ${rendered}`;
|
|
4356
|
+
}).join("");
|
|
4357
|
+
}
|
|
4358
|
+
return JSON.stringify(v);
|
|
4359
|
+
};
|
|
4360
|
+
return emit(obj, 0).trimStart();
|
|
4361
|
+
}
|
|
4362
|
+
async function emitOpenApi(entry, opts = {}) {
|
|
4363
|
+
let app;
|
|
4364
|
+
let cleanup = async () => {
|
|
4365
|
+
};
|
|
4366
|
+
try {
|
|
4367
|
+
const loaded = await loadApp(entry);
|
|
4368
|
+
app = loaded.app;
|
|
4369
|
+
cleanup = loaded.cleanup;
|
|
4370
|
+
} catch (err) {
|
|
4371
|
+
console.error(pc.red("\u2717 Failed to load app:"));
|
|
4372
|
+
console.error(err.message);
|
|
4373
|
+
process.exit(1);
|
|
4374
|
+
}
|
|
4375
|
+
try {
|
|
4376
|
+
let OpenApiGenerator;
|
|
4377
|
+
try {
|
|
4378
|
+
({ OpenApiGenerator } = await import('./dist-PKSGYMK7.mjs'));
|
|
4379
|
+
} catch {
|
|
218
4380
|
console.error(
|
|
219
|
-
"
|
|
4381
|
+
pc.red("\u2717 @axiomify/openapi is not installed."),
|
|
4382
|
+
"\n Install it:",
|
|
4383
|
+
pc.cyan("npm install @axiomify/openapi")
|
|
220
4384
|
);
|
|
221
4385
|
process.exit(1);
|
|
222
4386
|
}
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
app
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
const
|
|
4387
|
+
const info = {
|
|
4388
|
+
title: opts.title ?? "API",
|
|
4389
|
+
version: opts.version ?? "1.0.0"
|
|
4390
|
+
};
|
|
4391
|
+
const generator = new OpenApiGenerator(app, { info });
|
|
4392
|
+
const spec = generator.generate();
|
|
4393
|
+
if (opts.title) spec.info.title = opts.title;
|
|
4394
|
+
if (opts.version) spec.info.version = opts.version;
|
|
4395
|
+
const format = opts.format ?? "json";
|
|
4396
|
+
const serialised = format === "yaml" ? await jsonToYaml(spec) : opts.minify ? JSON.stringify(spec) : JSON.stringify(spec, null, 2);
|
|
4397
|
+
if (opts.output) {
|
|
4398
|
+
const outPath = path7.resolve(process.cwd(), opts.output);
|
|
4399
|
+
await fs5.mkdir(path7.dirname(outPath), { recursive: true });
|
|
4400
|
+
await fs5.writeFile(outPath, serialised + "\n", "utf8");
|
|
4401
|
+
const routeCount = (app.registeredRoutes ?? []).length;
|
|
235
4402
|
console.log(
|
|
236
|
-
`${
|
|
237
|
-
30
|
|
238
|
-
)} | ${validationStr}`
|
|
4403
|
+
`${pc.green("\u2713")} OpenAPI spec written to ${pc.cyan(opts.output)} ` + pc.dim(`(${routeCount} route${routeCount === 1 ? "" : "s"}, ${format})`)
|
|
239
4404
|
);
|
|
240
|
-
}
|
|
241
|
-
|
|
4405
|
+
} else {
|
|
4406
|
+
process.stdout.write(serialised + "\n");
|
|
4407
|
+
}
|
|
242
4408
|
} catch (error) {
|
|
243
|
-
console.error("\
|
|
4409
|
+
console.error(pc.red("\u2717 Failed to generate spec:"), error);
|
|
4410
|
+
process.exit(1);
|
|
244
4411
|
} finally {
|
|
245
|
-
await
|
|
4412
|
+
await cleanup();
|
|
4413
|
+
}
|
|
4414
|
+
}
|
|
4415
|
+
function normalise(raw, isWs) {
|
|
4416
|
+
const validation = [];
|
|
4417
|
+
if (raw.schema?.body) validation.push("Body");
|
|
4418
|
+
if (raw.schema?.query) validation.push("Query");
|
|
4419
|
+
if (raw.schema?.params) validation.push("Params");
|
|
4420
|
+
if (raw.schema?.response) validation.push("Response");
|
|
4421
|
+
if (raw.schema?.files) validation.push("Files");
|
|
4422
|
+
if (raw.schema?.message) validation.push("Message");
|
|
4423
|
+
const op = raw.openapi ?? {};
|
|
4424
|
+
return {
|
|
4425
|
+
method: isWs ? "WS" : raw.method,
|
|
4426
|
+
path: raw.path,
|
|
4427
|
+
validation,
|
|
4428
|
+
tags: Array.isArray(op.tags) ? op.tags : [],
|
|
4429
|
+
operationId: typeof op.operationId === "string" ? op.operationId : void 0,
|
|
4430
|
+
deprecated: op.deprecated === true,
|
|
4431
|
+
timeout: typeof raw.timeout === "number" && raw.timeout > 0 ? raw.timeout : void 0,
|
|
4432
|
+
plugins: Array.isArray(raw.plugins) ? raw.plugins.length : 0,
|
|
4433
|
+
isWs
|
|
4434
|
+
};
|
|
4435
|
+
}
|
|
4436
|
+
function matchesFilter(route, opts) {
|
|
4437
|
+
if (opts.method) {
|
|
4438
|
+
const wanted = opts.method.split(",").map((m) => m.trim().toUpperCase()).filter(Boolean);
|
|
4439
|
+
if (wanted.length && !wanted.includes(route.method)) return false;
|
|
4440
|
+
}
|
|
4441
|
+
if (opts.filter) {
|
|
4442
|
+
const pat = opts.filter;
|
|
4443
|
+
if (pat.includes("*")) {
|
|
4444
|
+
const re = new RegExp(
|
|
4445
|
+
"^" + pat.split("*").map((s) => s.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*") + "$"
|
|
4446
|
+
);
|
|
4447
|
+
if (!re.test(route.path)) return false;
|
|
4448
|
+
} else if (!route.path.includes(pat)) {
|
|
4449
|
+
return false;
|
|
4450
|
+
}
|
|
4451
|
+
}
|
|
4452
|
+
return true;
|
|
4453
|
+
}
|
|
4454
|
+
function sortRoutes(routes, by) {
|
|
4455
|
+
const methodOrder = {
|
|
4456
|
+
GET: 0,
|
|
4457
|
+
POST: 1,
|
|
4458
|
+
PUT: 2,
|
|
4459
|
+
PATCH: 3,
|
|
4460
|
+
DELETE: 4,
|
|
4461
|
+
HEAD: 5,
|
|
4462
|
+
OPTIONS: 6,
|
|
4463
|
+
WS: 7
|
|
4464
|
+
};
|
|
4465
|
+
return [...routes].sort((a, b) => {
|
|
4466
|
+
if (by === "method") {
|
|
4467
|
+
const am = methodOrder[a.method] ?? 99;
|
|
4468
|
+
const bm = methodOrder[b.method] ?? 99;
|
|
4469
|
+
if (am !== bm) return am - bm;
|
|
4470
|
+
return a.path.localeCompare(b.path);
|
|
4471
|
+
}
|
|
4472
|
+
if (a.path !== b.path) return a.path.localeCompare(b.path);
|
|
4473
|
+
return (methodOrder[a.method] ?? 99) - (methodOrder[b.method] ?? 99);
|
|
4474
|
+
});
|
|
4475
|
+
}
|
|
4476
|
+
async function inspectRoutes(entry, opts = {}) {
|
|
4477
|
+
let app;
|
|
4478
|
+
let cleanup = async () => {
|
|
4479
|
+
};
|
|
4480
|
+
try {
|
|
4481
|
+
const loaded = await loadApp(entry);
|
|
4482
|
+
app = loaded.app;
|
|
4483
|
+
cleanup = loaded.cleanup;
|
|
4484
|
+
} catch (err) {
|
|
4485
|
+
console.error(pc.red("\u2717 Failed to load app:"));
|
|
4486
|
+
console.error(err.message);
|
|
4487
|
+
process.exit(1);
|
|
4488
|
+
}
|
|
4489
|
+
try {
|
|
4490
|
+
const httpRoutes = (app.registeredRoutes ?? []).map(
|
|
4491
|
+
(r) => normalise(r, false)
|
|
4492
|
+
);
|
|
4493
|
+
const wsRoutes = (app.registeredWsRoutes ?? []).map(
|
|
4494
|
+
(r) => normalise(r, true)
|
|
4495
|
+
);
|
|
4496
|
+
const all = sortRoutes([...httpRoutes, ...wsRoutes], opts.sort ?? "path");
|
|
4497
|
+
const filtered = all.filter((r) => matchesFilter(r, opts));
|
|
4498
|
+
if (opts.json) {
|
|
4499
|
+
process.stdout.write(JSON.stringify(filtered, null, 2) + "\n");
|
|
4500
|
+
return;
|
|
4501
|
+
}
|
|
4502
|
+
if (filtered.length === 0) {
|
|
4503
|
+
console.log(
|
|
4504
|
+
"\n" + symbols.info + pc.dim(
|
|
4505
|
+
` No routes match the current filter (${all.length} total registered).
|
|
4506
|
+
`
|
|
4507
|
+
)
|
|
4508
|
+
);
|
|
4509
|
+
return;
|
|
4510
|
+
}
|
|
4511
|
+
console.log();
|
|
4512
|
+
console.log(pc.bold(" \u{1F9ED} Axiomify routes"));
|
|
4513
|
+
console.log();
|
|
4514
|
+
const columns = [
|
|
4515
|
+
{ header: "METHOD", minWidth: 7 },
|
|
4516
|
+
{ header: "PATH", minWidth: 20, maxWidth: 60 },
|
|
4517
|
+
{ header: "VALIDATION", minWidth: 10, maxWidth: 32 },
|
|
4518
|
+
{ header: "META", maxWidth: 40 }
|
|
4519
|
+
];
|
|
4520
|
+
const rows = filtered.map((r) => {
|
|
4521
|
+
const method = colourMethod(r.method);
|
|
4522
|
+
const path11 = r.deprecated ? pc.strikethrough(r.path) + " " + badge.deprecated() : r.path;
|
|
4523
|
+
const validation = r.validation.length > 0 ? r.validation.map(badge.validation).join(pc.dim(",")) : pc.dim("\u2014");
|
|
4524
|
+
const metaBits = [];
|
|
4525
|
+
if (r.operationId) metaBits.push(pc.dim(`op:`) + r.operationId);
|
|
4526
|
+
if (r.tags.length) metaBits.push(badge.tags(r.tags));
|
|
4527
|
+
if (r.timeout !== void 0) metaBits.push(badge.timeout(r.timeout));
|
|
4528
|
+
if (r.plugins > 0) metaBits.push(pc.dim(`+${r.plugins} plugin${r.plugins === 1 ? "" : "s"}`));
|
|
4529
|
+
const meta = metaBits.length ? metaBits.join(" ") : pc.dim("\u2014");
|
|
4530
|
+
return [method, path11, validation, meta];
|
|
246
4531
|
});
|
|
4532
|
+
console.log(renderTable(columns, rows));
|
|
4533
|
+
const byMethod = filtered.reduce((acc, r) => {
|
|
4534
|
+
acc[r.method] = (acc[r.method] ?? 0) + 1;
|
|
4535
|
+
return acc;
|
|
4536
|
+
}, {});
|
|
4537
|
+
const summaryParts = Object.entries(byMethod).sort(([a], [b]) => a.localeCompare(b)).map(([m, n]) => `${colourMethod(m).trimEnd()} ${pc.bold(String(n))}`);
|
|
4538
|
+
console.log();
|
|
4539
|
+
console.log(
|
|
4540
|
+
` ${symbols.ok} ${pluralise(filtered.length, "route")}` + (filtered.length < all.length ? pc.dim(` (filtered from ${all.length})`) : "") + " " + summaryParts.join(pc.dim(" \xB7 "))
|
|
4541
|
+
);
|
|
4542
|
+
const filteredWs = filtered.filter((r) => r.isWs).length;
|
|
4543
|
+
if (filteredWs > 0) {
|
|
4544
|
+
console.log(
|
|
4545
|
+
pc.dim(` \u2514 ${pluralise(filteredWs, "WebSocket route")} included`)
|
|
4546
|
+
);
|
|
4547
|
+
}
|
|
4548
|
+
console.log();
|
|
4549
|
+
} catch (error) {
|
|
4550
|
+
console.error(pc.red("\u2717 Failed to inspect routes:"), error);
|
|
4551
|
+
process.exit(1);
|
|
4552
|
+
} finally {
|
|
4553
|
+
await cleanup();
|
|
4554
|
+
}
|
|
4555
|
+
}
|
|
4556
|
+
var VALID_METHODS = /* @__PURE__ */ new Set([
|
|
4557
|
+
"GET",
|
|
4558
|
+
"POST",
|
|
4559
|
+
"PUT",
|
|
4560
|
+
"PATCH",
|
|
4561
|
+
"DELETE",
|
|
4562
|
+
"OPTIONS",
|
|
4563
|
+
"HEAD",
|
|
4564
|
+
"WS"
|
|
4565
|
+
]);
|
|
4566
|
+
function pathToFilename(routePath) {
|
|
4567
|
+
const cleaned = routePath.split("/").filter(Boolean).map((seg) => seg.startsWith(":") ? `by-${seg.slice(1)}` : seg).join("-");
|
|
4568
|
+
return cleaned || "root";
|
|
4569
|
+
}
|
|
4570
|
+
function generateRouteSource(method, routePath, opts) {
|
|
4571
|
+
const isWs = method === "WS";
|
|
4572
|
+
const params = routePath.match(/:[a-zA-Z_][a-zA-Z0-9_]*/g) ?? [];
|
|
4573
|
+
const paramKeys = params.map((p) => p.slice(1));
|
|
4574
|
+
const plugins = [];
|
|
4575
|
+
const extraImports = [];
|
|
4576
|
+
if (opts.auth) {
|
|
4577
|
+
plugins.push("requireAuth");
|
|
4578
|
+
extraImports.push(
|
|
4579
|
+
`import { createAuthPlugin } from '@axiomify/auth';
|
|
4580
|
+
|
|
4581
|
+
const requireAuth = createAuthPlugin({
|
|
4582
|
+
secret: process.env.JWT_SECRET!,
|
|
4583
|
+
});`
|
|
4584
|
+
);
|
|
4585
|
+
}
|
|
4586
|
+
if (opts.rateLimit) {
|
|
4587
|
+
plugins.push("limiter");
|
|
4588
|
+
extraImports.push(
|
|
4589
|
+
`import { createRateLimitPlugin, MemoryStore } from '@axiomify/rate-limit';
|
|
4590
|
+
|
|
4591
|
+
// Replace MemoryStore with RedisStore for multi-process / multi-host.
|
|
4592
|
+
const limiter = createRateLimitPlugin({
|
|
4593
|
+
windowMs: 60_000,
|
|
4594
|
+
max: 100,
|
|
4595
|
+
store: new MemoryStore(),
|
|
4596
|
+
});`
|
|
4597
|
+
);
|
|
4598
|
+
}
|
|
4599
|
+
if (isWs) {
|
|
4600
|
+
return [
|
|
4601
|
+
`import type { Axiomify } from '@axiomify/core';`,
|
|
4602
|
+
`import { z } from 'zod';`,
|
|
4603
|
+
extraImports.length ? extraImports.join("\n\n") + "\n" : "",
|
|
4604
|
+
`/**`,
|
|
4605
|
+
` * Registers WebSocket route ${routePath}.`,
|
|
4606
|
+
` * Wire this into your entry file:`,
|
|
4607
|
+
` * import { registerRoute } from './routes/${pathToFilename(routePath)}';`,
|
|
4608
|
+
` * registerRoute(app);`,
|
|
4609
|
+
` */`,
|
|
4610
|
+
`export function registerRoute(app: Axiomify): void {`,
|
|
4611
|
+
` app.ws({`,
|
|
4612
|
+
` path: '${routePath}',`,
|
|
4613
|
+
paramKeys.length > 0 ? ` schema: {
|
|
4614
|
+
params: z.object({ ${paramKeys.map((k) => `${k}: z.string()`).join(", ")} }),
|
|
4615
|
+
// Define your message shape here \u2014 runtime-validated on every incoming frame.
|
|
4616
|
+
message: z.object({
|
|
4617
|
+
text: z.string(),
|
|
4618
|
+
}),
|
|
4619
|
+
},` : ` schema: {
|
|
4620
|
+
// Define your message shape here \u2014 runtime-validated on every incoming frame.
|
|
4621
|
+
message: z.object({
|
|
4622
|
+
text: z.string(),
|
|
4623
|
+
}),
|
|
4624
|
+
},`,
|
|
4625
|
+
plugins.length > 0 ? ` plugins: [${plugins.join(", ")}],` : "",
|
|
4626
|
+
` open: (client, _req) => {`,
|
|
4627
|
+
` client.send({ type: 'welcome' });`,
|
|
4628
|
+
` },`,
|
|
4629
|
+
` message: (client, data) => {`,
|
|
4630
|
+
` // \`data\` is typed and validated from the schema above.`,
|
|
4631
|
+
` client.send({ echo: data.text });`,
|
|
4632
|
+
` },`,
|
|
4633
|
+
` close: (_client, code, reason) => {`,
|
|
4634
|
+
` console.log('connection closed', code, reason);`,
|
|
4635
|
+
` },`,
|
|
4636
|
+
` });`,
|
|
4637
|
+
`}`,
|
|
4638
|
+
``
|
|
4639
|
+
].filter(Boolean).join("\n");
|
|
4640
|
+
}
|
|
4641
|
+
return [
|
|
4642
|
+
`import type { Axiomify } from '@axiomify/core';`,
|
|
4643
|
+
`import { z } from 'zod';`,
|
|
4644
|
+
extraImports.length ? extraImports.join("\n\n") + "\n" : "",
|
|
4645
|
+
`/**`,
|
|
4646
|
+
` * Registers ${method} ${routePath}.`,
|
|
4647
|
+
` * Wire this into your entry file:`,
|
|
4648
|
+
` * import { registerRoute } from './routes/${pathToFilename(routePath)}';`,
|
|
4649
|
+
` * registerRoute(app);`,
|
|
4650
|
+
` */`,
|
|
4651
|
+
`export function registerRoute(app: Axiomify): void {`,
|
|
4652
|
+
` app.route({`,
|
|
4653
|
+
` method: '${method}',`,
|
|
4654
|
+
` path: '${routePath}',`,
|
|
4655
|
+
` schema: {`,
|
|
4656
|
+
paramKeys.length > 0 ? ` params: z.object({ ${paramKeys.map((k) => `${k}: z.string()`).join(", ")} }),` : "",
|
|
4657
|
+
method === "POST" || method === "PUT" || method === "PATCH" ? ` body: z.object({
|
|
4658
|
+
// TODO \u2014 define request body shape
|
|
4659
|
+
}),` : "",
|
|
4660
|
+
` // response: z.object({ /* response shape */ }),`,
|
|
4661
|
+
` },`,
|
|
4662
|
+
` openapi: {`,
|
|
4663
|
+
` tags: ['${pathToFilename(routePath).split("-")[0] || "general"}'],`,
|
|
4664
|
+
` summary: '${method} ${routePath}',`,
|
|
4665
|
+
` },`,
|
|
4666
|
+
plugins.length > 0 ? ` plugins: [${plugins.join(", ")}],` : "",
|
|
4667
|
+
` handler: async (${paramKeys.length > 0 || method !== "GET" ? "req" : "_req"}, res) => {`,
|
|
4668
|
+
method === "POST" ? ` // TODO \u2014 handler logic
|
|
4669
|
+
res.status(201).send({ ok: true });` : method === "DELETE" ? ` // TODO \u2014 handler logic
|
|
4670
|
+
res.status(204).send(null);` : ` // TODO \u2014 handler logic
|
|
4671
|
+
res.send({ ok: true });`,
|
|
4672
|
+
` },`,
|
|
4673
|
+
` });`,
|
|
4674
|
+
`}`,
|
|
4675
|
+
``
|
|
4676
|
+
].filter(Boolean).join("\n");
|
|
4677
|
+
}
|
|
4678
|
+
async function scaffoldRoute(method, routePath, opts = {}) {
|
|
4679
|
+
const upperMethod = method.toUpperCase();
|
|
4680
|
+
if (!VALID_METHODS.has(upperMethod)) {
|
|
4681
|
+
console.error(
|
|
4682
|
+
pc.red(`\u2717 Invalid method "${method}".`),
|
|
4683
|
+
`Expected one of: ${[...VALID_METHODS].join(", ")}.`
|
|
4684
|
+
);
|
|
4685
|
+
process.exit(1);
|
|
4686
|
+
}
|
|
4687
|
+
if (!routePath.startsWith("/")) {
|
|
4688
|
+
console.error(
|
|
4689
|
+
pc.red('\u2717 Path must start with "/".'),
|
|
4690
|
+
`Got: ${routePath}`
|
|
4691
|
+
);
|
|
4692
|
+
process.exit(1);
|
|
4693
|
+
}
|
|
4694
|
+
const dir = opts.dir ?? "src/routes";
|
|
4695
|
+
const filename = pathToFilename(routePath) + ".ts";
|
|
4696
|
+
const fileAbs = path7.resolve(process.cwd(), dir, filename);
|
|
4697
|
+
const source = generateRouteSource(upperMethod, routePath, opts);
|
|
4698
|
+
if (opts.dryRun) {
|
|
4699
|
+
console.log(pc.dim(`# would write ${path7.relative(process.cwd(), fileAbs)}
|
|
4700
|
+
`));
|
|
4701
|
+
console.log(source);
|
|
4702
|
+
return;
|
|
247
4703
|
}
|
|
4704
|
+
let exists = false;
|
|
4705
|
+
try {
|
|
4706
|
+
await fs5.access(fileAbs);
|
|
4707
|
+
exists = true;
|
|
4708
|
+
} catch {
|
|
4709
|
+
}
|
|
4710
|
+
if (exists && !opts.force) {
|
|
4711
|
+
console.log(
|
|
4712
|
+
`${symbols.warn} ${pc.yellow("Already exists:")} ${path7.relative(process.cwd(), fileAbs)}
|
|
4713
|
+
Pass ${pc.cyan("--force")} to overwrite, or pick a different path.`
|
|
4714
|
+
);
|
|
4715
|
+
return;
|
|
4716
|
+
}
|
|
4717
|
+
await fs5.mkdir(path7.dirname(fileAbs), { recursive: true });
|
|
4718
|
+
await fs5.writeFile(fileAbs, source, "utf8");
|
|
4719
|
+
console.log();
|
|
4720
|
+
console.log(
|
|
4721
|
+
`${symbols.ok} ${pc.green("Created")} ${pc.cyan(path7.relative(process.cwd(), fileAbs))}`
|
|
4722
|
+
);
|
|
4723
|
+
console.log();
|
|
4724
|
+
console.log(pc.dim(" Next steps:"));
|
|
4725
|
+
console.log(
|
|
4726
|
+
` 1. Wire it into your entry file:
|
|
4727
|
+
` + pc.dim(` import { registerRoute } from './routes/${pathToFilename(routePath)}';
|
|
4728
|
+
`) + pc.dim(` registerRoute(app);`)
|
|
4729
|
+
);
|
|
4730
|
+
console.log(
|
|
4731
|
+
` 2. Fill in the TODOs in ${pc.cyan(path7.relative(process.cwd(), fileAbs))}.`
|
|
4732
|
+
);
|
|
4733
|
+
console.log(
|
|
4734
|
+
` 3. Verify with ${pc.cyan("npx axiomify routes")} and ${pc.cyan("npx axiomify check")}.`
|
|
4735
|
+
);
|
|
4736
|
+
console.log();
|
|
248
4737
|
}
|
|
249
4738
|
|
|
250
4739
|
// src/index.ts
|
|
251
|
-
var
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
4740
|
+
var program2 = new Command();
|
|
4741
|
+
program2.name("axiomify").description("The official CLI for the Axiomify framework").version(package_default.version);
|
|
4742
|
+
program2.command("init").description("Bootstrap a new Axiomify project").argument("[directory]", "Target directory").option("-f, --force", "Overwrite existing project files", false).action(
|
|
4743
|
+
(directory, options) => initProject(directory, options)
|
|
4744
|
+
);
|
|
4745
|
+
program2.command("dev").description("Start the development server with hot-reload").argument("[entry]", "Entry file", "src/index.ts").action(devServer);
|
|
4746
|
+
program2.command("build").description("Compile the application for production").argument("[entry]", "Entry file", "src/index.ts").action(buildProject);
|
|
4747
|
+
program2.command("routes").description("Inspect and list all registered HTTP + WebSocket routes").argument("[entry]", "Entry file", "src/index.ts").option("--json", "Emit machine-readable JSON instead of the formatted table", false).option(
|
|
4748
|
+
"-m, --method <list>",
|
|
4749
|
+
"Comma-separated list of methods to include (e.g. GET,POST,WS)"
|
|
4750
|
+
).option(
|
|
4751
|
+
"-f, --filter <pattern>",
|
|
4752
|
+
'Path filter \u2014 substring match, or glob with "*" (e.g. /api/v1/*)'
|
|
4753
|
+
).option(
|
|
4754
|
+
"-s, --sort <by>",
|
|
4755
|
+
'Sort routes by "method" or "path"',
|
|
4756
|
+
"path"
|
|
4757
|
+
).action(
|
|
4758
|
+
(entry, options) => inspectRoutes(entry, options)
|
|
4759
|
+
);
|
|
4760
|
+
program2.command("openapi").description("Generate the OpenAPI spec from the app and emit it").argument("[entry]", "Entry file", "src/index.ts").option(
|
|
4761
|
+
"-o, --output <file>",
|
|
4762
|
+
"Write the spec to this file path instead of stdout"
|
|
4763
|
+
).option("--format <fmt>", 'Output format: "json" (default) or "yaml"', "json").option("--minify", "Minified JSON (single line). Ignored for yaml.", false).option("--title <title>", "Override info.title in the generated spec").option("--spec-version <version>", "Override info.version in the generated spec").action(
|
|
4764
|
+
(entry, options) => emitOpenApi(entry, {
|
|
4765
|
+
...options,
|
|
4766
|
+
// Map the CLI flag name (`spec-version` → camel `specVersion`) onto
|
|
4767
|
+
// the internal `version` field that emitOpenApi() expects.
|
|
4768
|
+
version: options.specVersion
|
|
4769
|
+
})
|
|
4770
|
+
);
|
|
4771
|
+
program2.command("check").description("Run a static production-readiness audit against the app").argument("[entry]", "Entry file", "src/index.ts").action(runCheck);
|
|
4772
|
+
program2.command("doctor").description("Diagnose the host environment (Node, uWS, ports, dep drift)").action(runDoctor);
|
|
4773
|
+
var scaffold = program2.command("scaffold").description("Generate boilerplate (routes, modules, plugins)");
|
|
4774
|
+
scaffold.command("route <method> <path>").description("Create a new route file under src/routes/").option("--auth", "Include `requireAuth` plugin and import", false).option("--rate-limit", "Include a default rate-limit plugin", false).option("--dry-run", "Print the generated source without writing", false).option("--force", "Overwrite the file if it already exists", false).option("--dir <dir>", "Directory under cwd to create the file in", "src/routes").action(
|
|
4775
|
+
(method, routePath, options) => scaffoldRoute(method, routePath, options)
|
|
4776
|
+
);
|
|
4777
|
+
program2.command("migrate").description("v4 \u2192 v5 codemod: rename meta\u2192openapi, useSwagger\u2192useOpenAPI, etc").option("--dry-run", "Show the unified diff without writing", false).option("--report-only", "Print a migration report and exit; do not write", false).option("--dir <dir>", "Directory to scan recursively", "src").action(
|
|
4778
|
+
(options) => runMigrate(options)
|
|
4779
|
+
);
|
|
4780
|
+
program2.parse(process.argv);
|