@agentcomms/whatsapp 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +258 -0
- package/THIRD_PARTY_LICENSES +924 -0
- package/dist/cli.d.mts +1 -0
- package/dist/cli.mjs +3584 -0
- package/dist/coerce-BscjcmYU.mjs +34 -0
- package/dist/dist-COPefvtq-D67MoOnB.mjs +9880 -0
- package/dist/index.d.mts +11605 -0
- package/dist/index.mjs +12 -0
- package/dist/mcp-DXXb3Vv3-Co5BzjYe.mjs +16220 -0
- package/dist/schemas-DiGKNDNq.mjs +5885 -0
- package/dist/server-DJZWYUNK.mjs +215 -0
- package/dist/src-D_zzAWoS-BhK0GFdq-XAvBzdGB.mjs +7806 -0
- package/dist/stdio-BR8R87El.mjs +102 -0
- package/dist/stdio-CHZ2WRcx-5iYMXTdw.mjs +607 -0
- package/dist/stdio-entry-m_AQ55DZ.mjs +21 -0
- package/dist/sync-BUT0jSeG.mjs +9360 -0
- package/package.json +91 -0
package/dist/cli.mjs
ADDED
|
@@ -0,0 +1,3584 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { $ as withFileLock, A as CommsError, B as installExitStatus, C as checkStorePath, F as canPrompt, G as paint, H as lookupName, I as channelManifest, J as runCommand, K as renderInstall, L as colorEnabled, M as agentMarker, N as approvalKind, O as CHANNELS, P as approveChangeAtTerminal, Q as truncateDisplay, R as escapeForDisplay, S as storeIdentity, T as expandSource, U as nameAvailable, V as isCommsError, W as nameShapeProblem, X as serverPruneChange, Y as serverInstallChange, _ as chatRefOf, a as listChats, b as requireAccount, c as Presenter, d as draftMessage, et as writeResult, f as Visibility, g as requireSupportedNode, h as WhatsAppIndex, i as CHAT_KINDS, j as EXIT_CODES, k as CHANNEL_SERVERS, l as innerText, m as WhatsAppContext, n as whatsappStatus, o as readChat, p as listKey, q as renderPrune, r as probeStore, s as searchMessages, t as syncAccount, tt as VERSION, v as PLATFORM, w as defaultStorePath, x as requireNamedConfig, y as newWhatsAppAccount, z as gatedChangeAtTerminal } from "./sync-BUT0jSeG.mjs";
|
|
3
|
+
import { rm } from "node:fs/promises";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { stripVTControlCharacters } from "node:util";
|
|
6
|
+
import childProcess, { spawn } from "node:child_process";
|
|
7
|
+
import fs from "node:fs";
|
|
8
|
+
import process$1 from "node:process";
|
|
9
|
+
import { EventEmitter } from "node:events";
|
|
10
|
+
//#region ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/error.js
|
|
11
|
+
/**
|
|
12
|
+
* CommanderError class
|
|
13
|
+
*/
|
|
14
|
+
var CommanderError = class extends Error {
|
|
15
|
+
/**
|
|
16
|
+
* Constructs the CommanderError class
|
|
17
|
+
* @param {number} exitCode suggested exit code which could be used with process.exit
|
|
18
|
+
* @param {string} code an id string representing the error
|
|
19
|
+
* @param {string} message human-readable description of the error
|
|
20
|
+
*/
|
|
21
|
+
constructor(exitCode, code, message) {
|
|
22
|
+
super(message);
|
|
23
|
+
Error.captureStackTrace(this, this.constructor);
|
|
24
|
+
this.name = this.constructor.name;
|
|
25
|
+
this.code = code;
|
|
26
|
+
this.exitCode = exitCode;
|
|
27
|
+
this.nestedError = void 0;
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* InvalidArgumentError class
|
|
32
|
+
*/
|
|
33
|
+
var InvalidArgumentError = class extends CommanderError {
|
|
34
|
+
/**
|
|
35
|
+
* Constructs the InvalidArgumentError class
|
|
36
|
+
* @param {string} [message] explanation of why argument is invalid
|
|
37
|
+
*/
|
|
38
|
+
constructor(message) {
|
|
39
|
+
super(1, "commander.invalidArgument", message);
|
|
40
|
+
Error.captureStackTrace(this, this.constructor);
|
|
41
|
+
this.name = this.constructor.name;
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
//#endregion
|
|
45
|
+
//#region ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/argument.js
|
|
46
|
+
var Argument = class {
|
|
47
|
+
/**
|
|
48
|
+
* Initialize a new command argument with the given name and description.
|
|
49
|
+
* The default is that the argument is required, and you can explicitly
|
|
50
|
+
* indicate this with <> around the name. Put [] around the name for an optional argument.
|
|
51
|
+
*
|
|
52
|
+
* @param {string} name
|
|
53
|
+
* @param {string} [description]
|
|
54
|
+
*/
|
|
55
|
+
constructor(name, description) {
|
|
56
|
+
this.description = description || "";
|
|
57
|
+
this.variadic = false;
|
|
58
|
+
this.parseArg = void 0;
|
|
59
|
+
this.defaultValue = void 0;
|
|
60
|
+
this.defaultValueDescription = void 0;
|
|
61
|
+
this.argChoices = void 0;
|
|
62
|
+
switch (name[0]) {
|
|
63
|
+
case "<":
|
|
64
|
+
this.required = true;
|
|
65
|
+
this._name = name.slice(1, -1);
|
|
66
|
+
break;
|
|
67
|
+
case "[":
|
|
68
|
+
this.required = false;
|
|
69
|
+
this._name = name.slice(1, -1);
|
|
70
|
+
break;
|
|
71
|
+
default:
|
|
72
|
+
this.required = true;
|
|
73
|
+
this._name = name;
|
|
74
|
+
}
|
|
75
|
+
if (this._name.endsWith("...")) {
|
|
76
|
+
this.variadic = true;
|
|
77
|
+
this._name = this._name.slice(0, -3);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Return argument name.
|
|
82
|
+
*
|
|
83
|
+
* @return {string}
|
|
84
|
+
*/
|
|
85
|
+
name() {
|
|
86
|
+
return this._name;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* @package
|
|
90
|
+
*/
|
|
91
|
+
_collectValue(value, previous) {
|
|
92
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) return [value];
|
|
93
|
+
previous.push(value);
|
|
94
|
+
return previous;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Set the default value, and optionally supply the description to be displayed in the help.
|
|
98
|
+
*
|
|
99
|
+
* @param {*} value
|
|
100
|
+
* @param {string} [description]
|
|
101
|
+
* @return {Argument}
|
|
102
|
+
*/
|
|
103
|
+
default(value, description) {
|
|
104
|
+
this.defaultValue = value;
|
|
105
|
+
this.defaultValueDescription = description;
|
|
106
|
+
return this;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Set the custom handler for processing CLI command arguments into argument values.
|
|
110
|
+
*
|
|
111
|
+
* @param {Function} [fn]
|
|
112
|
+
* @return {Argument}
|
|
113
|
+
*/
|
|
114
|
+
argParser(fn) {
|
|
115
|
+
this.parseArg = fn;
|
|
116
|
+
return this;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Only allow argument value to be one of choices.
|
|
120
|
+
*
|
|
121
|
+
* @param {string[]} values
|
|
122
|
+
* @return {Argument}
|
|
123
|
+
*/
|
|
124
|
+
choices(values) {
|
|
125
|
+
this.argChoices = values.slice();
|
|
126
|
+
this.parseArg = (arg, previous) => {
|
|
127
|
+
if (!this.argChoices.includes(arg)) throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
|
|
128
|
+
if (this.variadic) return this._collectValue(arg, previous);
|
|
129
|
+
return arg;
|
|
130
|
+
};
|
|
131
|
+
return this;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Make argument required.
|
|
135
|
+
*
|
|
136
|
+
* @returns {Argument}
|
|
137
|
+
*/
|
|
138
|
+
argRequired() {
|
|
139
|
+
this.required = true;
|
|
140
|
+
return this;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Make argument optional.
|
|
144
|
+
*
|
|
145
|
+
* @returns {Argument}
|
|
146
|
+
*/
|
|
147
|
+
argOptional() {
|
|
148
|
+
this.required = false;
|
|
149
|
+
return this;
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
/**
|
|
153
|
+
* Takes an argument and returns its human readable equivalent for help usage.
|
|
154
|
+
*
|
|
155
|
+
* @param {Argument} arg
|
|
156
|
+
* @return {string}
|
|
157
|
+
* @private
|
|
158
|
+
*/
|
|
159
|
+
function humanReadableArgName(arg) {
|
|
160
|
+
const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
|
|
161
|
+
return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
|
|
162
|
+
}
|
|
163
|
+
//#endregion
|
|
164
|
+
//#region ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/help.js
|
|
165
|
+
/**
|
|
166
|
+
* TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`
|
|
167
|
+
* https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types
|
|
168
|
+
* @typedef { import("./argument.js").Argument } Argument
|
|
169
|
+
* @typedef { import("./command.js").Command } Command
|
|
170
|
+
* @typedef { import("./option.js").Option } Option
|
|
171
|
+
*/
|
|
172
|
+
var Help = class {
|
|
173
|
+
constructor() {
|
|
174
|
+
this.helpWidth = void 0;
|
|
175
|
+
this.minWidthToWrap = 40;
|
|
176
|
+
this.sortSubcommands = false;
|
|
177
|
+
this.sortOptions = false;
|
|
178
|
+
this.showGlobalOptions = false;
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
|
|
182
|
+
* and just before calling `formatHelp()`.
|
|
183
|
+
*
|
|
184
|
+
* Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
|
|
185
|
+
*
|
|
186
|
+
* @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
|
|
187
|
+
*/
|
|
188
|
+
prepareContext(contextOptions) {
|
|
189
|
+
this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
|
|
193
|
+
*
|
|
194
|
+
* @param {Command} cmd
|
|
195
|
+
* @returns {Command[]}
|
|
196
|
+
*/
|
|
197
|
+
visibleCommands(cmd) {
|
|
198
|
+
const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);
|
|
199
|
+
const helpCommand = cmd._getHelpCommand();
|
|
200
|
+
if (helpCommand && !helpCommand._hidden) visibleCommands.push(helpCommand);
|
|
201
|
+
if (this.sortSubcommands) visibleCommands.sort((a, b) => {
|
|
202
|
+
return a.name().localeCompare(b.name());
|
|
203
|
+
});
|
|
204
|
+
return visibleCommands;
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Compare options for sort.
|
|
208
|
+
*
|
|
209
|
+
* @param {Option} a
|
|
210
|
+
* @param {Option} b
|
|
211
|
+
* @returns {number}
|
|
212
|
+
*/
|
|
213
|
+
compareOptions(a, b) {
|
|
214
|
+
const getSortKey = (option) => {
|
|
215
|
+
return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
|
|
216
|
+
};
|
|
217
|
+
return getSortKey(a).localeCompare(getSortKey(b));
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
|
|
221
|
+
*
|
|
222
|
+
* @param {Command} cmd
|
|
223
|
+
* @returns {Option[]}
|
|
224
|
+
*/
|
|
225
|
+
visibleOptions(cmd) {
|
|
226
|
+
const visibleOptions = cmd.options.filter((option) => !option.hidden);
|
|
227
|
+
const helpOption = cmd._getHelpOption();
|
|
228
|
+
if (helpOption && !helpOption.hidden) {
|
|
229
|
+
const removeShort = helpOption.short && cmd._findOption(helpOption.short);
|
|
230
|
+
const removeLong = helpOption.long && cmd._findOption(helpOption.long);
|
|
231
|
+
if (!removeShort && !removeLong) visibleOptions.push(helpOption);
|
|
232
|
+
else if (helpOption.long && !removeLong) visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
|
|
233
|
+
else if (helpOption.short && !removeShort) visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
|
|
234
|
+
}
|
|
235
|
+
if (this.sortOptions) visibleOptions.sort(this.compareOptions);
|
|
236
|
+
return visibleOptions;
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Get an array of the visible global options. (Not including help.)
|
|
240
|
+
*
|
|
241
|
+
* @param {Command} cmd
|
|
242
|
+
* @returns {Option[]}
|
|
243
|
+
*/
|
|
244
|
+
visibleGlobalOptions(cmd) {
|
|
245
|
+
if (!this.showGlobalOptions) return [];
|
|
246
|
+
const globalOptions = [];
|
|
247
|
+
for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
|
|
248
|
+
const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
|
|
249
|
+
globalOptions.push(...visibleOptions);
|
|
250
|
+
}
|
|
251
|
+
if (this.sortOptions) globalOptions.sort(this.compareOptions);
|
|
252
|
+
return globalOptions;
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Get an array of the arguments if any have a description.
|
|
256
|
+
*
|
|
257
|
+
* @param {Command} cmd
|
|
258
|
+
* @returns {Argument[]}
|
|
259
|
+
*/
|
|
260
|
+
visibleArguments(cmd) {
|
|
261
|
+
if (cmd._argsDescription) cmd.registeredArguments.forEach((argument) => {
|
|
262
|
+
argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
|
|
263
|
+
});
|
|
264
|
+
if (cmd.registeredArguments.find((argument) => argument.description)) return cmd.registeredArguments;
|
|
265
|
+
return [];
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Get the command term to show in the list of subcommands.
|
|
269
|
+
*
|
|
270
|
+
* @param {Command} cmd
|
|
271
|
+
* @returns {string}
|
|
272
|
+
*/
|
|
273
|
+
subcommandTerm(cmd) {
|
|
274
|
+
const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
|
|
275
|
+
return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Get the option term to show in the list of options.
|
|
279
|
+
*
|
|
280
|
+
* @param {Option} option
|
|
281
|
+
* @returns {string}
|
|
282
|
+
*/
|
|
283
|
+
optionTerm(option) {
|
|
284
|
+
return option.flags;
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* Get the argument term to show in the list of arguments.
|
|
288
|
+
*
|
|
289
|
+
* @param {Argument} argument
|
|
290
|
+
* @returns {string}
|
|
291
|
+
*/
|
|
292
|
+
argumentTerm(argument) {
|
|
293
|
+
return argument.name();
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* Get the longest command term length.
|
|
297
|
+
*
|
|
298
|
+
* @param {Command} cmd
|
|
299
|
+
* @param {Help} helper
|
|
300
|
+
* @returns {number}
|
|
301
|
+
*/
|
|
302
|
+
longestSubcommandTermLength(cmd, helper) {
|
|
303
|
+
return helper.visibleCommands(cmd).reduce((max, command) => {
|
|
304
|
+
return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
|
|
305
|
+
}, 0);
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* Get the longest option term length.
|
|
309
|
+
*
|
|
310
|
+
* @param {Command} cmd
|
|
311
|
+
* @param {Help} helper
|
|
312
|
+
* @returns {number}
|
|
313
|
+
*/
|
|
314
|
+
longestOptionTermLength(cmd, helper) {
|
|
315
|
+
return helper.visibleOptions(cmd).reduce((max, option) => {
|
|
316
|
+
return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
|
|
317
|
+
}, 0);
|
|
318
|
+
}
|
|
319
|
+
/**
|
|
320
|
+
* Get the longest global option term length.
|
|
321
|
+
*
|
|
322
|
+
* @param {Command} cmd
|
|
323
|
+
* @param {Help} helper
|
|
324
|
+
* @returns {number}
|
|
325
|
+
*/
|
|
326
|
+
longestGlobalOptionTermLength(cmd, helper) {
|
|
327
|
+
return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
|
|
328
|
+
return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
|
|
329
|
+
}, 0);
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* Get the longest argument term length.
|
|
333
|
+
*
|
|
334
|
+
* @param {Command} cmd
|
|
335
|
+
* @param {Help} helper
|
|
336
|
+
* @returns {number}
|
|
337
|
+
*/
|
|
338
|
+
longestArgumentTermLength(cmd, helper) {
|
|
339
|
+
return helper.visibleArguments(cmd).reduce((max, argument) => {
|
|
340
|
+
return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
|
|
341
|
+
}, 0);
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* Get the command usage to be displayed at the top of the built-in help.
|
|
345
|
+
*
|
|
346
|
+
* @param {Command} cmd
|
|
347
|
+
* @returns {string}
|
|
348
|
+
*/
|
|
349
|
+
commandUsage(cmd) {
|
|
350
|
+
let cmdName = cmd._name;
|
|
351
|
+
if (cmd._aliases[0]) cmdName = cmdName + "|" + cmd._aliases[0];
|
|
352
|
+
let ancestorCmdNames = "";
|
|
353
|
+
for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
|
|
354
|
+
return ancestorCmdNames + cmdName + " " + cmd.usage();
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* Get the description for the command.
|
|
358
|
+
*
|
|
359
|
+
* @param {Command} cmd
|
|
360
|
+
* @returns {string}
|
|
361
|
+
*/
|
|
362
|
+
commandDescription(cmd) {
|
|
363
|
+
return cmd.description();
|
|
364
|
+
}
|
|
365
|
+
/**
|
|
366
|
+
* Get the subcommand summary to show in the list of subcommands.
|
|
367
|
+
* (Fallback to description for backwards compatibility.)
|
|
368
|
+
*
|
|
369
|
+
* @param {Command} cmd
|
|
370
|
+
* @returns {string}
|
|
371
|
+
*/
|
|
372
|
+
subcommandDescription(cmd) {
|
|
373
|
+
return cmd.summary() || cmd.description();
|
|
374
|
+
}
|
|
375
|
+
/**
|
|
376
|
+
* Get the option description to show in the list of options.
|
|
377
|
+
*
|
|
378
|
+
* @param {Option} option
|
|
379
|
+
* @return {string}
|
|
380
|
+
*/
|
|
381
|
+
optionDescription(option) {
|
|
382
|
+
const extraInfo = [];
|
|
383
|
+
if (option.argChoices) extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
|
|
384
|
+
if (option.defaultValue !== void 0) {
|
|
385
|
+
if (option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean") extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
|
|
386
|
+
}
|
|
387
|
+
if (option.presetArg !== void 0 && option.optional) extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
|
|
388
|
+
if (option.envVar !== void 0) extraInfo.push(`env: ${option.envVar}`);
|
|
389
|
+
if (extraInfo.length > 0) {
|
|
390
|
+
const extraDescription = `(${extraInfo.join(", ")})`;
|
|
391
|
+
if (option.description) return `${option.description} ${extraDescription}`;
|
|
392
|
+
return extraDescription;
|
|
393
|
+
}
|
|
394
|
+
return option.description;
|
|
395
|
+
}
|
|
396
|
+
/**
|
|
397
|
+
* Get the argument description to show in the list of arguments.
|
|
398
|
+
*
|
|
399
|
+
* @param {Argument} argument
|
|
400
|
+
* @return {string}
|
|
401
|
+
*/
|
|
402
|
+
argumentDescription(argument) {
|
|
403
|
+
const extraInfo = [];
|
|
404
|
+
if (argument.argChoices) extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
|
|
405
|
+
if (argument.defaultValue !== void 0) extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
|
|
406
|
+
if (extraInfo.length > 0) {
|
|
407
|
+
const extraDescription = `(${extraInfo.join(", ")})`;
|
|
408
|
+
if (argument.description) return `${argument.description} ${extraDescription}`;
|
|
409
|
+
return extraDescription;
|
|
410
|
+
}
|
|
411
|
+
return argument.description;
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* Format a list of items, given a heading and an array of formatted items.
|
|
415
|
+
*
|
|
416
|
+
* @param {string} heading
|
|
417
|
+
* @param {string[]} items
|
|
418
|
+
* @param {Help} helper
|
|
419
|
+
* @returns string[]
|
|
420
|
+
*/
|
|
421
|
+
formatItemList(heading, items, helper) {
|
|
422
|
+
if (items.length === 0) return [];
|
|
423
|
+
return [
|
|
424
|
+
helper.styleTitle(heading),
|
|
425
|
+
...items,
|
|
426
|
+
""
|
|
427
|
+
];
|
|
428
|
+
}
|
|
429
|
+
/**
|
|
430
|
+
* Group items by their help group heading.
|
|
431
|
+
*
|
|
432
|
+
* @param {Command[] | Option[]} unsortedItems
|
|
433
|
+
* @param {Command[] | Option[]} visibleItems
|
|
434
|
+
* @param {Function} getGroup
|
|
435
|
+
* @returns {Map<string, Command[] | Option[]>}
|
|
436
|
+
*/
|
|
437
|
+
groupItems(unsortedItems, visibleItems, getGroup) {
|
|
438
|
+
const result = /* @__PURE__ */ new Map();
|
|
439
|
+
unsortedItems.forEach((item) => {
|
|
440
|
+
const group = getGroup(item);
|
|
441
|
+
if (!result.has(group)) result.set(group, []);
|
|
442
|
+
});
|
|
443
|
+
visibleItems.forEach((item) => {
|
|
444
|
+
const group = getGroup(item);
|
|
445
|
+
if (!result.has(group)) result.set(group, []);
|
|
446
|
+
result.get(group).push(item);
|
|
447
|
+
});
|
|
448
|
+
return result;
|
|
449
|
+
}
|
|
450
|
+
/**
|
|
451
|
+
* Generate the built-in help text.
|
|
452
|
+
*
|
|
453
|
+
* @param {Command} cmd
|
|
454
|
+
* @param {Help} helper
|
|
455
|
+
* @returns {string}
|
|
456
|
+
*/
|
|
457
|
+
formatHelp(cmd, helper) {
|
|
458
|
+
const termWidth = helper.padWidth(cmd, helper);
|
|
459
|
+
const helpWidth = helper.helpWidth ?? 80;
|
|
460
|
+
function callFormatItem(term, description) {
|
|
461
|
+
return helper.formatItem(term, termWidth, description, helper);
|
|
462
|
+
}
|
|
463
|
+
let output = [`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`, ""];
|
|
464
|
+
const commandDescription = helper.commandDescription(cmd);
|
|
465
|
+
if (commandDescription.length > 0) output = output.concat([helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth), ""]);
|
|
466
|
+
const argumentList = helper.visibleArguments(cmd).map((argument) => {
|
|
467
|
+
return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
|
|
468
|
+
});
|
|
469
|
+
output = output.concat(this.formatItemList("Arguments:", argumentList, helper));
|
|
470
|
+
this.groupItems(cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? "Options:").forEach((options, group) => {
|
|
471
|
+
const optionList = options.map((option) => {
|
|
472
|
+
return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
|
|
473
|
+
});
|
|
474
|
+
output = output.concat(this.formatItemList(group, optionList, helper));
|
|
475
|
+
});
|
|
476
|
+
if (helper.showGlobalOptions) {
|
|
477
|
+
const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
|
|
478
|
+
return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
|
|
479
|
+
});
|
|
480
|
+
output = output.concat(this.formatItemList("Global Options:", globalOptionList, helper));
|
|
481
|
+
}
|
|
482
|
+
this.groupItems(cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || "Commands:").forEach((commands, group) => {
|
|
483
|
+
const commandList = commands.map((sub) => {
|
|
484
|
+
return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)));
|
|
485
|
+
});
|
|
486
|
+
output = output.concat(this.formatItemList(group, commandList, helper));
|
|
487
|
+
});
|
|
488
|
+
return output.join("\n");
|
|
489
|
+
}
|
|
490
|
+
/**
|
|
491
|
+
* Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
|
|
492
|
+
*
|
|
493
|
+
* @param {string} str
|
|
494
|
+
* @returns {number}
|
|
495
|
+
*/
|
|
496
|
+
displayWidth(str) {
|
|
497
|
+
return stripVTControlCharacters(str).length;
|
|
498
|
+
}
|
|
499
|
+
/**
|
|
500
|
+
* Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
|
|
501
|
+
*
|
|
502
|
+
* @param {string} str
|
|
503
|
+
* @returns {string}
|
|
504
|
+
*/
|
|
505
|
+
styleTitle(str) {
|
|
506
|
+
return str;
|
|
507
|
+
}
|
|
508
|
+
styleUsage(str) {
|
|
509
|
+
return str.split(" ").map((word) => {
|
|
510
|
+
if (word === "[options]") return this.styleOptionText(word);
|
|
511
|
+
if (word === "[command]") return this.styleSubcommandText(word);
|
|
512
|
+
if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
|
|
513
|
+
return this.styleCommandText(word);
|
|
514
|
+
}).join(" ");
|
|
515
|
+
}
|
|
516
|
+
styleCommandDescription(str) {
|
|
517
|
+
return this.styleDescriptionText(str);
|
|
518
|
+
}
|
|
519
|
+
styleOptionDescription(str) {
|
|
520
|
+
return this.styleDescriptionText(str);
|
|
521
|
+
}
|
|
522
|
+
styleSubcommandDescription(str) {
|
|
523
|
+
return this.styleDescriptionText(str);
|
|
524
|
+
}
|
|
525
|
+
styleArgumentDescription(str) {
|
|
526
|
+
return this.styleDescriptionText(str);
|
|
527
|
+
}
|
|
528
|
+
styleDescriptionText(str) {
|
|
529
|
+
return str;
|
|
530
|
+
}
|
|
531
|
+
styleOptionTerm(str) {
|
|
532
|
+
return this.styleOptionText(str);
|
|
533
|
+
}
|
|
534
|
+
styleSubcommandTerm(str) {
|
|
535
|
+
return str.split(" ").map((word) => {
|
|
536
|
+
if (word === "[options]") return this.styleOptionText(word);
|
|
537
|
+
if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
|
|
538
|
+
return this.styleSubcommandText(word);
|
|
539
|
+
}).join(" ");
|
|
540
|
+
}
|
|
541
|
+
styleArgumentTerm(str) {
|
|
542
|
+
return this.styleArgumentText(str);
|
|
543
|
+
}
|
|
544
|
+
styleOptionText(str) {
|
|
545
|
+
return str;
|
|
546
|
+
}
|
|
547
|
+
styleArgumentText(str) {
|
|
548
|
+
return str;
|
|
549
|
+
}
|
|
550
|
+
styleSubcommandText(str) {
|
|
551
|
+
return str;
|
|
552
|
+
}
|
|
553
|
+
styleCommandText(str) {
|
|
554
|
+
return str;
|
|
555
|
+
}
|
|
556
|
+
/**
|
|
557
|
+
* Calculate the pad width from the maximum term length.
|
|
558
|
+
*
|
|
559
|
+
* @param {Command} cmd
|
|
560
|
+
* @param {Help} helper
|
|
561
|
+
* @returns {number}
|
|
562
|
+
*/
|
|
563
|
+
padWidth(cmd, helper) {
|
|
564
|
+
return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
|
|
565
|
+
}
|
|
566
|
+
/**
|
|
567
|
+
* Detect manually wrapped and indented strings by checking for line break followed by whitespace.
|
|
568
|
+
*
|
|
569
|
+
* @param {string} str
|
|
570
|
+
* @returns {boolean}
|
|
571
|
+
*/
|
|
572
|
+
preformatted(str) {
|
|
573
|
+
return /\n[^\S\r\n]/.test(str);
|
|
574
|
+
}
|
|
575
|
+
/**
|
|
576
|
+
* Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
|
|
577
|
+
*
|
|
578
|
+
* So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
|
|
579
|
+
* TTT DDD DDDD
|
|
580
|
+
* DD DDD
|
|
581
|
+
*
|
|
582
|
+
* @param {string} term
|
|
583
|
+
* @param {number} termWidth
|
|
584
|
+
* @param {string} description
|
|
585
|
+
* @param {Help} helper
|
|
586
|
+
* @returns {string}
|
|
587
|
+
*/
|
|
588
|
+
formatItem(term, termWidth, description, helper) {
|
|
589
|
+
const itemIndent = 2;
|
|
590
|
+
const itemIndentStr = " ".repeat(itemIndent);
|
|
591
|
+
if (!description) return itemIndentStr + term;
|
|
592
|
+
const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
|
|
593
|
+
const spacerWidth = 2;
|
|
594
|
+
const remainingWidth = (this.helpWidth ?? 80) - termWidth - spacerWidth - itemIndent;
|
|
595
|
+
let formattedDescription;
|
|
596
|
+
if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) formattedDescription = description;
|
|
597
|
+
else formattedDescription = helper.boxWrap(description, remainingWidth).replace(/\n/g, "\n" + " ".repeat(termWidth + spacerWidth));
|
|
598
|
+
return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `\n${itemIndentStr}`);
|
|
599
|
+
}
|
|
600
|
+
/**
|
|
601
|
+
* Wrap a string at whitespace, preserving existing line breaks.
|
|
602
|
+
* Wrapping is skipped if the width is less than `minWidthToWrap`.
|
|
603
|
+
*
|
|
604
|
+
* @param {string} str
|
|
605
|
+
* @param {number} width
|
|
606
|
+
* @returns {string}
|
|
607
|
+
*/
|
|
608
|
+
boxWrap(str, width) {
|
|
609
|
+
if (width < this.minWidthToWrap) return str;
|
|
610
|
+
const rawLines = str.split(/\r\n|\n/);
|
|
611
|
+
const chunkPattern = /[\s]*[^\s]+/g;
|
|
612
|
+
const wrappedLines = [];
|
|
613
|
+
rawLines.forEach((line) => {
|
|
614
|
+
const chunks = line.match(chunkPattern);
|
|
615
|
+
if (chunks === null) {
|
|
616
|
+
wrappedLines.push("");
|
|
617
|
+
return;
|
|
618
|
+
}
|
|
619
|
+
let sumChunks = [chunks.shift()];
|
|
620
|
+
let sumWidth = this.displayWidth(sumChunks[0]);
|
|
621
|
+
chunks.forEach((chunk) => {
|
|
622
|
+
const visibleWidth = this.displayWidth(chunk);
|
|
623
|
+
if (sumWidth + visibleWidth <= width) {
|
|
624
|
+
sumChunks.push(chunk);
|
|
625
|
+
sumWidth += visibleWidth;
|
|
626
|
+
return;
|
|
627
|
+
}
|
|
628
|
+
wrappedLines.push(sumChunks.join(""));
|
|
629
|
+
const nextChunk = chunk.trimStart();
|
|
630
|
+
sumChunks = [nextChunk];
|
|
631
|
+
sumWidth = this.displayWidth(nextChunk);
|
|
632
|
+
});
|
|
633
|
+
wrappedLines.push(sumChunks.join(""));
|
|
634
|
+
});
|
|
635
|
+
return wrappedLines.join("\n");
|
|
636
|
+
}
|
|
637
|
+
};
|
|
638
|
+
//#endregion
|
|
639
|
+
//#region ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/option.js
|
|
640
|
+
var Option = class {
|
|
641
|
+
/**
|
|
642
|
+
* Initialize a new `Option` with the given `flags` and `description`.
|
|
643
|
+
*
|
|
644
|
+
* @param {string} flags
|
|
645
|
+
* @param {string} [description]
|
|
646
|
+
*/
|
|
647
|
+
constructor(flags, description) {
|
|
648
|
+
this.flags = flags;
|
|
649
|
+
this.description = description || "";
|
|
650
|
+
this.required = flags.includes("<");
|
|
651
|
+
this.optional = flags.includes("[");
|
|
652
|
+
this.variadic = /\w\.\.\.[>\]]$/.test(flags);
|
|
653
|
+
this.mandatory = false;
|
|
654
|
+
const optionFlags = splitOptionFlags(flags);
|
|
655
|
+
this.short = optionFlags.shortFlag;
|
|
656
|
+
this.long = optionFlags.longFlag;
|
|
657
|
+
this.negate = false;
|
|
658
|
+
if (this.long) this.negate = this.long.startsWith("--no-");
|
|
659
|
+
this.defaultValue = void 0;
|
|
660
|
+
this.defaultValueDescription = void 0;
|
|
661
|
+
this.presetArg = void 0;
|
|
662
|
+
this.envVar = void 0;
|
|
663
|
+
this.parseArg = void 0;
|
|
664
|
+
this.hidden = false;
|
|
665
|
+
this.argChoices = void 0;
|
|
666
|
+
this.conflictsWith = [];
|
|
667
|
+
this.implied = void 0;
|
|
668
|
+
this.helpGroupHeading = void 0;
|
|
669
|
+
}
|
|
670
|
+
/**
|
|
671
|
+
* Set the default value, and optionally supply the description to be displayed in the help.
|
|
672
|
+
*
|
|
673
|
+
* @param {*} value
|
|
674
|
+
* @param {string} [description]
|
|
675
|
+
* @return {Option}
|
|
676
|
+
*/
|
|
677
|
+
default(value, description) {
|
|
678
|
+
this.defaultValue = value;
|
|
679
|
+
this.defaultValueDescription = description;
|
|
680
|
+
return this;
|
|
681
|
+
}
|
|
682
|
+
/**
|
|
683
|
+
* Preset to use when option used without option-argument, especially optional but also boolean and negated.
|
|
684
|
+
* The custom processing (parseArg) is called.
|
|
685
|
+
*
|
|
686
|
+
* @example
|
|
687
|
+
* new Option('--color').default('GREYSCALE').preset('RGB');
|
|
688
|
+
* new Option('--donate [amount]').preset('20').argParser(parseFloat);
|
|
689
|
+
*
|
|
690
|
+
* @param {*} arg
|
|
691
|
+
* @return {Option}
|
|
692
|
+
*/
|
|
693
|
+
preset(arg) {
|
|
694
|
+
this.presetArg = arg;
|
|
695
|
+
return this;
|
|
696
|
+
}
|
|
697
|
+
/**
|
|
698
|
+
* Add option name(s) that conflict with this option.
|
|
699
|
+
* An error will be displayed if conflicting options are found during parsing.
|
|
700
|
+
*
|
|
701
|
+
* @example
|
|
702
|
+
* new Option('--rgb').conflicts('cmyk');
|
|
703
|
+
* new Option('--js').conflicts(['ts', 'jsx']);
|
|
704
|
+
*
|
|
705
|
+
* @param {(string | string[])} names
|
|
706
|
+
* @return {Option}
|
|
707
|
+
*/
|
|
708
|
+
conflicts(names) {
|
|
709
|
+
this.conflictsWith = this.conflictsWith.concat(names);
|
|
710
|
+
return this;
|
|
711
|
+
}
|
|
712
|
+
/**
|
|
713
|
+
* Specify implied option values for when this option is set and the implied options are not.
|
|
714
|
+
*
|
|
715
|
+
* The custom processing (parseArg) is not called on the implied values.
|
|
716
|
+
*
|
|
717
|
+
* @example
|
|
718
|
+
* program
|
|
719
|
+
* .addOption(new Option('--log', 'write logging information to file'))
|
|
720
|
+
* .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
|
|
721
|
+
*
|
|
722
|
+
* @param {object} impliedOptionValues
|
|
723
|
+
* @return {Option}
|
|
724
|
+
*/
|
|
725
|
+
implies(impliedOptionValues) {
|
|
726
|
+
let newImplied = impliedOptionValues;
|
|
727
|
+
if (typeof impliedOptionValues === "string") newImplied = { [impliedOptionValues]: true };
|
|
728
|
+
this.implied = Object.assign(this.implied || {}, newImplied);
|
|
729
|
+
return this;
|
|
730
|
+
}
|
|
731
|
+
/**
|
|
732
|
+
* Set environment variable to check for option value.
|
|
733
|
+
*
|
|
734
|
+
* An environment variable is only used if when processed the current option value is
|
|
735
|
+
* undefined, or the source of the current value is 'default' or 'config' or 'env'.
|
|
736
|
+
*
|
|
737
|
+
* @param {string} name
|
|
738
|
+
* @return {Option}
|
|
739
|
+
*/
|
|
740
|
+
env(name) {
|
|
741
|
+
this.envVar = name;
|
|
742
|
+
return this;
|
|
743
|
+
}
|
|
744
|
+
/**
|
|
745
|
+
* Set the custom handler for processing CLI option arguments into option values.
|
|
746
|
+
*
|
|
747
|
+
* @param {Function} [fn]
|
|
748
|
+
* @return {Option}
|
|
749
|
+
*/
|
|
750
|
+
argParser(fn) {
|
|
751
|
+
this.parseArg = fn;
|
|
752
|
+
return this;
|
|
753
|
+
}
|
|
754
|
+
/**
|
|
755
|
+
* Whether the option is mandatory and must have a value after parsing.
|
|
756
|
+
*
|
|
757
|
+
* @param {boolean} [mandatory=true]
|
|
758
|
+
* @return {Option}
|
|
759
|
+
*/
|
|
760
|
+
makeOptionMandatory(mandatory = true) {
|
|
761
|
+
this.mandatory = !!mandatory;
|
|
762
|
+
return this;
|
|
763
|
+
}
|
|
764
|
+
/**
|
|
765
|
+
* Hide option in help.
|
|
766
|
+
*
|
|
767
|
+
* @param {boolean} [hide=true]
|
|
768
|
+
* @return {Option}
|
|
769
|
+
*/
|
|
770
|
+
hideHelp(hide = true) {
|
|
771
|
+
this.hidden = !!hide;
|
|
772
|
+
return this;
|
|
773
|
+
}
|
|
774
|
+
/**
|
|
775
|
+
* @package
|
|
776
|
+
*/
|
|
777
|
+
_collectValue(value, previous) {
|
|
778
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) return [value];
|
|
779
|
+
previous.push(value);
|
|
780
|
+
return previous;
|
|
781
|
+
}
|
|
782
|
+
/**
|
|
783
|
+
* Only allow option value to be one of choices.
|
|
784
|
+
*
|
|
785
|
+
* @param {string[]} values
|
|
786
|
+
* @return {Option}
|
|
787
|
+
*/
|
|
788
|
+
choices(values) {
|
|
789
|
+
this.argChoices = values.slice();
|
|
790
|
+
this.parseArg = (arg, previous) => {
|
|
791
|
+
if (!this.argChoices.includes(arg)) throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
|
|
792
|
+
if (this.variadic) return this._collectValue(arg, previous);
|
|
793
|
+
return arg;
|
|
794
|
+
};
|
|
795
|
+
return this;
|
|
796
|
+
}
|
|
797
|
+
/**
|
|
798
|
+
* Return option name.
|
|
799
|
+
*
|
|
800
|
+
* @return {string}
|
|
801
|
+
*/
|
|
802
|
+
name() {
|
|
803
|
+
if (this.long) return this.long.replace(/^--/, "");
|
|
804
|
+
return this.short.replace(/^-/, "");
|
|
805
|
+
}
|
|
806
|
+
/**
|
|
807
|
+
* Return option name, in a camelcase format that can be used
|
|
808
|
+
* as an object attribute key.
|
|
809
|
+
*
|
|
810
|
+
* @return {string}
|
|
811
|
+
*/
|
|
812
|
+
attributeName() {
|
|
813
|
+
if (this.negate) return camelcase(this.name().replace(/^no-/, ""));
|
|
814
|
+
return camelcase(this.name());
|
|
815
|
+
}
|
|
816
|
+
/**
|
|
817
|
+
* Set the help group heading.
|
|
818
|
+
*
|
|
819
|
+
* @param {string} heading
|
|
820
|
+
* @return {Option}
|
|
821
|
+
*/
|
|
822
|
+
helpGroup(heading) {
|
|
823
|
+
this.helpGroupHeading = heading;
|
|
824
|
+
return this;
|
|
825
|
+
}
|
|
826
|
+
/**
|
|
827
|
+
* Check if `arg` matches the short or long flag.
|
|
828
|
+
*
|
|
829
|
+
* @param {string} arg
|
|
830
|
+
* @return {boolean}
|
|
831
|
+
* @package
|
|
832
|
+
*/
|
|
833
|
+
is(arg) {
|
|
834
|
+
return this.short === arg || this.long === arg;
|
|
835
|
+
}
|
|
836
|
+
/**
|
|
837
|
+
* Return whether a boolean option.
|
|
838
|
+
*
|
|
839
|
+
* Options are one of boolean, negated, required argument, or optional argument.
|
|
840
|
+
*
|
|
841
|
+
* @return {boolean}
|
|
842
|
+
* @package
|
|
843
|
+
*/
|
|
844
|
+
isBoolean() {
|
|
845
|
+
return !this.required && !this.optional && !this.negate;
|
|
846
|
+
}
|
|
847
|
+
};
|
|
848
|
+
/**
|
|
849
|
+
* This class is to make it easier to work with dual options, without changing the existing
|
|
850
|
+
* implementation. We support separate dual options for separate positive and negative options,
|
|
851
|
+
* like `--build` and `--no-build`, which share a single option value. This works nicely for some
|
|
852
|
+
* use cases, but is tricky for others where we want separate behaviours despite
|
|
853
|
+
* the single shared option value.
|
|
854
|
+
*/
|
|
855
|
+
var DualOptions = class {
|
|
856
|
+
/**
|
|
857
|
+
* @param {Option[]} options
|
|
858
|
+
*/
|
|
859
|
+
constructor(options) {
|
|
860
|
+
this.positiveOptions = /* @__PURE__ */ new Map();
|
|
861
|
+
this.negativeOptions = /* @__PURE__ */ new Map();
|
|
862
|
+
this.dualOptions = /* @__PURE__ */ new Set();
|
|
863
|
+
options.forEach((option) => {
|
|
864
|
+
if (option.negate) this.negativeOptions.set(option.attributeName(), option);
|
|
865
|
+
else this.positiveOptions.set(option.attributeName(), option);
|
|
866
|
+
});
|
|
867
|
+
this.negativeOptions.forEach((value, key) => {
|
|
868
|
+
if (this.positiveOptions.has(key)) this.dualOptions.add(key);
|
|
869
|
+
});
|
|
870
|
+
}
|
|
871
|
+
/**
|
|
872
|
+
* Did the value come from the option, and not from possible matching dual option?
|
|
873
|
+
*
|
|
874
|
+
* @param {*} value
|
|
875
|
+
* @param {Option} option
|
|
876
|
+
* @returns {boolean}
|
|
877
|
+
*/
|
|
878
|
+
valueFromOption(value, option) {
|
|
879
|
+
const optionKey = option.attributeName();
|
|
880
|
+
if (!this.dualOptions.has(optionKey)) return true;
|
|
881
|
+
const preset = this.negativeOptions.get(optionKey).presetArg;
|
|
882
|
+
const negativeValue = preset !== void 0 ? preset : false;
|
|
883
|
+
return option.negate === (negativeValue === value);
|
|
884
|
+
}
|
|
885
|
+
};
|
|
886
|
+
/**
|
|
887
|
+
* Convert string from kebab-case to camelCase.
|
|
888
|
+
*
|
|
889
|
+
* @param {string} str
|
|
890
|
+
* @return {string}
|
|
891
|
+
* @private
|
|
892
|
+
*/
|
|
893
|
+
function camelcase(str) {
|
|
894
|
+
return str.split("-").reduce((str, word) => {
|
|
895
|
+
return str + word[0].toUpperCase() + word.slice(1);
|
|
896
|
+
});
|
|
897
|
+
}
|
|
898
|
+
/**
|
|
899
|
+
* Split the short and long flag out of something like '-m,--mixed <value>'
|
|
900
|
+
*
|
|
901
|
+
* @private
|
|
902
|
+
*/
|
|
903
|
+
function splitOptionFlags(flags) {
|
|
904
|
+
let shortFlag;
|
|
905
|
+
let longFlag;
|
|
906
|
+
const shortFlagExp = /^-[^-]$/;
|
|
907
|
+
const longFlagExp = /^--[^-]/;
|
|
908
|
+
const flagParts = flags.split(/[ |,]+/).concat("guard");
|
|
909
|
+
if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
|
|
910
|
+
if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
|
|
911
|
+
if (!shortFlag && shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
|
|
912
|
+
if (!shortFlag && longFlagExp.test(flagParts[0])) {
|
|
913
|
+
shortFlag = longFlag;
|
|
914
|
+
longFlag = flagParts.shift();
|
|
915
|
+
}
|
|
916
|
+
if (flagParts[0].startsWith("-")) {
|
|
917
|
+
const unsupportedFlag = flagParts[0];
|
|
918
|
+
const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
|
|
919
|
+
if (/^-[^-][^-]/.test(unsupportedFlag)) throw new Error(`${baseError}
|
|
920
|
+
- a short flag is a single dash and a single character
|
|
921
|
+
- either use a single dash and a single character (for a short flag)
|
|
922
|
+
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
|
|
923
|
+
if (shortFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
|
|
924
|
+
- too many short flags`);
|
|
925
|
+
if (longFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
|
|
926
|
+
- too many long flags`);
|
|
927
|
+
throw new Error(`${baseError}
|
|
928
|
+
- unrecognised flag format`);
|
|
929
|
+
}
|
|
930
|
+
if (shortFlag === void 0 && longFlag === void 0) throw new Error(`option creation failed due to no flags found in '${flags}'.`);
|
|
931
|
+
return {
|
|
932
|
+
shortFlag,
|
|
933
|
+
longFlag
|
|
934
|
+
};
|
|
935
|
+
}
|
|
936
|
+
//#endregion
|
|
937
|
+
//#region ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/suggestSimilar.js
|
|
938
|
+
const maxDistance = 3;
|
|
939
|
+
function editDistance(a, b) {
|
|
940
|
+
if (Math.abs(a.length - b.length) > maxDistance) return Math.max(a.length, b.length);
|
|
941
|
+
const d = [];
|
|
942
|
+
for (let i = 0; i <= a.length; i++) d[i] = [i];
|
|
943
|
+
for (let j = 0; j <= b.length; j++) d[0][j] = j;
|
|
944
|
+
for (let j = 1; j <= b.length; j++) for (let i = 1; i <= a.length; i++) {
|
|
945
|
+
let cost;
|
|
946
|
+
if (a[i - 1] === b[j - 1]) cost = 0;
|
|
947
|
+
else cost = 1;
|
|
948
|
+
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
|
|
949
|
+
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
|
|
950
|
+
}
|
|
951
|
+
return d[a.length][b.length];
|
|
952
|
+
}
|
|
953
|
+
/**
|
|
954
|
+
* Find close matches, restricted to same number of edits.
|
|
955
|
+
*
|
|
956
|
+
* @param {string} word
|
|
957
|
+
* @param {string[]} candidates
|
|
958
|
+
* @returns {string}
|
|
959
|
+
*/
|
|
960
|
+
function suggestSimilar(word, candidates) {
|
|
961
|
+
if (!candidates || candidates.length === 0) return "";
|
|
962
|
+
candidates = Array.from(new Set(candidates));
|
|
963
|
+
const searchingOptions = word.startsWith("--");
|
|
964
|
+
if (searchingOptions) {
|
|
965
|
+
word = word.slice(2);
|
|
966
|
+
candidates = candidates.map((candidate) => candidate.slice(2));
|
|
967
|
+
}
|
|
968
|
+
let similar = [];
|
|
969
|
+
let bestDistance = maxDistance;
|
|
970
|
+
const minSimilarity = .4;
|
|
971
|
+
candidates.forEach((candidate) => {
|
|
972
|
+
if (candidate.length <= 1) return;
|
|
973
|
+
const distance = editDistance(word, candidate);
|
|
974
|
+
const length = Math.max(word.length, candidate.length);
|
|
975
|
+
if ((length - distance) / length > minSimilarity) {
|
|
976
|
+
if (distance < bestDistance) {
|
|
977
|
+
bestDistance = distance;
|
|
978
|
+
similar = [candidate];
|
|
979
|
+
} else if (distance === bestDistance) similar.push(candidate);
|
|
980
|
+
}
|
|
981
|
+
});
|
|
982
|
+
similar.sort((a, b) => a.localeCompare(b));
|
|
983
|
+
if (searchingOptions) similar = similar.map((candidate) => `--${candidate}`);
|
|
984
|
+
if (similar.length > 1) return `\n(Did you mean one of ${similar.join(", ")}?)`;
|
|
985
|
+
if (similar.length === 1) return `\n(Did you mean ${similar[0]}?)`;
|
|
986
|
+
return "";
|
|
987
|
+
}
|
|
988
|
+
//#endregion
|
|
989
|
+
//#region ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/command.js
|
|
990
|
+
var Command = class Command extends EventEmitter {
|
|
991
|
+
/**
|
|
992
|
+
* Initialize a new `Command`.
|
|
993
|
+
*
|
|
994
|
+
* @param {string} [name]
|
|
995
|
+
*/
|
|
996
|
+
constructor(name) {
|
|
997
|
+
super();
|
|
998
|
+
/** @type {Command[]} */
|
|
999
|
+
this.commands = [];
|
|
1000
|
+
/** @type {Option[]} */
|
|
1001
|
+
this.options = [];
|
|
1002
|
+
this.parent = null;
|
|
1003
|
+
this._allowUnknownOption = false;
|
|
1004
|
+
this._allowExcessArguments = false;
|
|
1005
|
+
/** @type {Argument[]} */
|
|
1006
|
+
this.registeredArguments = [];
|
|
1007
|
+
this._args = this.registeredArguments;
|
|
1008
|
+
/** @type {string[]} */
|
|
1009
|
+
this.args = [];
|
|
1010
|
+
this.rawArgs = [];
|
|
1011
|
+
this.processedArgs = [];
|
|
1012
|
+
this._scriptPath = null;
|
|
1013
|
+
this._name = name || "";
|
|
1014
|
+
this._optionValues = {};
|
|
1015
|
+
this._optionValueSources = {};
|
|
1016
|
+
this._storeOptionsAsProperties = false;
|
|
1017
|
+
this._actionHandler = null;
|
|
1018
|
+
this._executableHandler = false;
|
|
1019
|
+
this._executableFile = null;
|
|
1020
|
+
this._executableDir = null;
|
|
1021
|
+
this._defaultCommandName = null;
|
|
1022
|
+
this._exitCallback = null;
|
|
1023
|
+
this._aliases = [];
|
|
1024
|
+
this._combineFlagAndOptionalValue = true;
|
|
1025
|
+
this._description = "";
|
|
1026
|
+
this._summary = "";
|
|
1027
|
+
this._argsDescription = void 0;
|
|
1028
|
+
this._enablePositionalOptions = false;
|
|
1029
|
+
this._passThroughOptions = false;
|
|
1030
|
+
this._lifeCycleHooks = {};
|
|
1031
|
+
/** @type {(boolean | string)} */
|
|
1032
|
+
this._showHelpAfterError = false;
|
|
1033
|
+
this._showSuggestionAfterError = true;
|
|
1034
|
+
this._savedState = null;
|
|
1035
|
+
this._outputConfiguration = {
|
|
1036
|
+
writeOut: (str) => process$1.stdout.write(str),
|
|
1037
|
+
writeErr: (str) => process$1.stderr.write(str),
|
|
1038
|
+
outputError: (str, write) => write(str),
|
|
1039
|
+
getOutHelpWidth: () => process$1.stdout.isTTY ? process$1.stdout.columns : void 0,
|
|
1040
|
+
getErrHelpWidth: () => process$1.stderr.isTTY ? process$1.stderr.columns : void 0,
|
|
1041
|
+
getOutHasColors: () => useColor() ?? (process$1.stdout.isTTY && process$1.stdout.hasColors?.()),
|
|
1042
|
+
getErrHasColors: () => useColor() ?? (process$1.stderr.isTTY && process$1.stderr.hasColors?.()),
|
|
1043
|
+
stripColor: (str) => stripVTControlCharacters(str)
|
|
1044
|
+
};
|
|
1045
|
+
this._hidden = false;
|
|
1046
|
+
/** @type {(Option | null | undefined)} */
|
|
1047
|
+
this._helpOption = void 0;
|
|
1048
|
+
this._addImplicitHelpCommand = void 0;
|
|
1049
|
+
/** @type {Command} */
|
|
1050
|
+
this._helpCommand = void 0;
|
|
1051
|
+
this._helpConfiguration = {};
|
|
1052
|
+
/** @type {string | undefined} */
|
|
1053
|
+
this._helpGroupHeading = void 0;
|
|
1054
|
+
/** @type {string | undefined} */
|
|
1055
|
+
this._defaultCommandGroup = void 0;
|
|
1056
|
+
/** @type {string | undefined} */
|
|
1057
|
+
this._defaultOptionGroup = void 0;
|
|
1058
|
+
}
|
|
1059
|
+
/**
|
|
1060
|
+
* Copy settings that are useful to have in common across root command and subcommands.
|
|
1061
|
+
*
|
|
1062
|
+
* (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
|
|
1063
|
+
*
|
|
1064
|
+
* @param {Command} sourceCommand
|
|
1065
|
+
* @return {Command} `this` command for chaining
|
|
1066
|
+
*/
|
|
1067
|
+
copyInheritedSettings(sourceCommand) {
|
|
1068
|
+
this._outputConfiguration = sourceCommand._outputConfiguration;
|
|
1069
|
+
this._helpOption = sourceCommand._helpOption;
|
|
1070
|
+
this._helpCommand = sourceCommand._helpCommand;
|
|
1071
|
+
this._helpConfiguration = sourceCommand._helpConfiguration;
|
|
1072
|
+
this._exitCallback = sourceCommand._exitCallback;
|
|
1073
|
+
this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
|
|
1074
|
+
this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
|
|
1075
|
+
this._allowExcessArguments = sourceCommand._allowExcessArguments;
|
|
1076
|
+
this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
|
|
1077
|
+
this._showHelpAfterError = sourceCommand._showHelpAfterError;
|
|
1078
|
+
this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
|
|
1079
|
+
return this;
|
|
1080
|
+
}
|
|
1081
|
+
/**
|
|
1082
|
+
* @returns {Command[]}
|
|
1083
|
+
* @private
|
|
1084
|
+
*/
|
|
1085
|
+
_getCommandAndAncestors() {
|
|
1086
|
+
const result = [];
|
|
1087
|
+
for (let command = this; command; command = command.parent) result.push(command);
|
|
1088
|
+
return result;
|
|
1089
|
+
}
|
|
1090
|
+
/**
|
|
1091
|
+
* Define a command.
|
|
1092
|
+
*
|
|
1093
|
+
* There are two styles of command: pay attention to where to put the description.
|
|
1094
|
+
*
|
|
1095
|
+
* @example
|
|
1096
|
+
* // Command implemented using action handler (description is supplied separately to `.command`)
|
|
1097
|
+
* program
|
|
1098
|
+
* .command('clone <source> [destination]')
|
|
1099
|
+
* .description('clone a repository into a newly created directory')
|
|
1100
|
+
* .action((source, destination) => {
|
|
1101
|
+
* console.log('clone command called');
|
|
1102
|
+
* });
|
|
1103
|
+
*
|
|
1104
|
+
* // Command implemented using separate executable file (description is second parameter to `.command`)
|
|
1105
|
+
* program
|
|
1106
|
+
* .command('start <service>', 'start named service')
|
|
1107
|
+
* .command('stop [service]', 'stop named service, or all if no name supplied');
|
|
1108
|
+
*
|
|
1109
|
+
* @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
|
|
1110
|
+
* @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
|
|
1111
|
+
* @param {object} [execOpts] - configuration options (for executable)
|
|
1112
|
+
* @return {Command} returns new command for action handler, or `this` for executable command
|
|
1113
|
+
*/
|
|
1114
|
+
command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
|
|
1115
|
+
let desc = actionOptsOrExecDesc;
|
|
1116
|
+
let opts = execOpts;
|
|
1117
|
+
if (typeof desc === "object" && desc !== null) {
|
|
1118
|
+
opts = desc;
|
|
1119
|
+
desc = null;
|
|
1120
|
+
}
|
|
1121
|
+
opts = opts || {};
|
|
1122
|
+
const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
|
|
1123
|
+
const cmd = this.createCommand(name);
|
|
1124
|
+
if (desc) {
|
|
1125
|
+
cmd.description(desc);
|
|
1126
|
+
cmd._executableHandler = true;
|
|
1127
|
+
}
|
|
1128
|
+
if (opts.isDefault) this._defaultCommandName = cmd._name;
|
|
1129
|
+
cmd._hidden = !!(opts.noHelp || opts.hidden);
|
|
1130
|
+
cmd._executableFile = opts.executableFile || null;
|
|
1131
|
+
if (args) cmd.arguments(args);
|
|
1132
|
+
this._registerCommand(cmd);
|
|
1133
|
+
cmd.parent = this;
|
|
1134
|
+
cmd.copyInheritedSettings(this);
|
|
1135
|
+
if (desc) return this;
|
|
1136
|
+
return cmd;
|
|
1137
|
+
}
|
|
1138
|
+
/**
|
|
1139
|
+
* Factory routine to create a new unattached command.
|
|
1140
|
+
*
|
|
1141
|
+
* See .command() for creating an attached subcommand, which uses this routine to
|
|
1142
|
+
* create the command. You can override createCommand to customise subcommands.
|
|
1143
|
+
*
|
|
1144
|
+
* @param {string} [name]
|
|
1145
|
+
* @return {Command} new command
|
|
1146
|
+
*/
|
|
1147
|
+
createCommand(name) {
|
|
1148
|
+
return new Command(name);
|
|
1149
|
+
}
|
|
1150
|
+
/**
|
|
1151
|
+
* You can customise the help with a subclass of Help by overriding createHelp,
|
|
1152
|
+
* or by overriding Help properties using configureHelp().
|
|
1153
|
+
*
|
|
1154
|
+
* @return {Help}
|
|
1155
|
+
*/
|
|
1156
|
+
createHelp() {
|
|
1157
|
+
return Object.assign(new Help(), this.configureHelp());
|
|
1158
|
+
}
|
|
1159
|
+
/**
|
|
1160
|
+
* You can customise the help by overriding Help properties using configureHelp(),
|
|
1161
|
+
* or with a subclass of Help by overriding createHelp().
|
|
1162
|
+
*
|
|
1163
|
+
* @param {object} [configuration] - configuration options
|
|
1164
|
+
* @return {(Command | object)} `this` command for chaining, or stored configuration
|
|
1165
|
+
*/
|
|
1166
|
+
configureHelp(configuration) {
|
|
1167
|
+
if (configuration === void 0) return this._helpConfiguration;
|
|
1168
|
+
this._helpConfiguration = configuration;
|
|
1169
|
+
return this;
|
|
1170
|
+
}
|
|
1171
|
+
/**
|
|
1172
|
+
* The default output goes to stdout and stderr. You can customise this for special
|
|
1173
|
+
* applications. You can also customise the display of errors by overriding outputError.
|
|
1174
|
+
*
|
|
1175
|
+
* The configuration properties are all functions:
|
|
1176
|
+
*
|
|
1177
|
+
* // change how output being written, defaults to stdout and stderr
|
|
1178
|
+
* writeOut(str)
|
|
1179
|
+
* writeErr(str)
|
|
1180
|
+
* // change how output being written for errors, defaults to writeErr
|
|
1181
|
+
* outputError(str, write) // used for displaying errors and not used for displaying help
|
|
1182
|
+
* // specify width for wrapping help
|
|
1183
|
+
* getOutHelpWidth()
|
|
1184
|
+
* getErrHelpWidth()
|
|
1185
|
+
* // color support, currently only used with Help
|
|
1186
|
+
* getOutHasColors()
|
|
1187
|
+
* getErrHasColors()
|
|
1188
|
+
* stripColor() // used to remove ANSI escape codes if output does not have colors
|
|
1189
|
+
*
|
|
1190
|
+
* @param {object} [configuration] - configuration options
|
|
1191
|
+
* @return {(Command | object)} `this` command for chaining, or stored configuration
|
|
1192
|
+
*/
|
|
1193
|
+
configureOutput(configuration) {
|
|
1194
|
+
if (configuration === void 0) return this._outputConfiguration;
|
|
1195
|
+
this._outputConfiguration = {
|
|
1196
|
+
...this._outputConfiguration,
|
|
1197
|
+
...configuration
|
|
1198
|
+
};
|
|
1199
|
+
return this;
|
|
1200
|
+
}
|
|
1201
|
+
/**
|
|
1202
|
+
* Display the help or a custom message after an error occurs.
|
|
1203
|
+
*
|
|
1204
|
+
* @param {(boolean|string)} [displayHelp]
|
|
1205
|
+
* @return {Command} `this` command for chaining
|
|
1206
|
+
*/
|
|
1207
|
+
showHelpAfterError(displayHelp = true) {
|
|
1208
|
+
if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
|
|
1209
|
+
this._showHelpAfterError = displayHelp;
|
|
1210
|
+
return this;
|
|
1211
|
+
}
|
|
1212
|
+
/**
|
|
1213
|
+
* Display suggestion of similar commands for unknown commands, or options for unknown options.
|
|
1214
|
+
*
|
|
1215
|
+
* @param {boolean} [displaySuggestion]
|
|
1216
|
+
* @return {Command} `this` command for chaining
|
|
1217
|
+
*/
|
|
1218
|
+
showSuggestionAfterError(displaySuggestion = true) {
|
|
1219
|
+
this._showSuggestionAfterError = !!displaySuggestion;
|
|
1220
|
+
return this;
|
|
1221
|
+
}
|
|
1222
|
+
/**
|
|
1223
|
+
* Add a prepared subcommand.
|
|
1224
|
+
*
|
|
1225
|
+
* See .command() for creating an attached subcommand which inherits settings from its parent.
|
|
1226
|
+
*
|
|
1227
|
+
* @param {Command} cmd - new subcommand
|
|
1228
|
+
* @param {object} [opts] - configuration options
|
|
1229
|
+
* @return {Command} `this` command for chaining
|
|
1230
|
+
*/
|
|
1231
|
+
addCommand(cmd, opts) {
|
|
1232
|
+
if (!cmd._name) throw new Error(`Command passed to .addCommand() must have a name
|
|
1233
|
+
- specify the name in Command constructor or using .name()`);
|
|
1234
|
+
opts = opts || {};
|
|
1235
|
+
if (opts.isDefault) this._defaultCommandName = cmd._name;
|
|
1236
|
+
if (opts.noHelp || opts.hidden) cmd._hidden = true;
|
|
1237
|
+
this._registerCommand(cmd);
|
|
1238
|
+
cmd.parent = this;
|
|
1239
|
+
cmd._checkForBrokenPassThrough();
|
|
1240
|
+
return this;
|
|
1241
|
+
}
|
|
1242
|
+
/**
|
|
1243
|
+
* Factory routine to create a new unattached argument.
|
|
1244
|
+
*
|
|
1245
|
+
* See .argument() for creating an attached argument, which uses this routine to
|
|
1246
|
+
* create the argument. You can override createArgument to return a custom argument.
|
|
1247
|
+
*
|
|
1248
|
+
* @param {string} name
|
|
1249
|
+
* @param {string} [description]
|
|
1250
|
+
* @return {Argument} new argument
|
|
1251
|
+
*/
|
|
1252
|
+
createArgument(name, description) {
|
|
1253
|
+
return new Argument(name, description);
|
|
1254
|
+
}
|
|
1255
|
+
/**
|
|
1256
|
+
* Define argument syntax for command.
|
|
1257
|
+
*
|
|
1258
|
+
* The default is that the argument is required, and you can explicitly
|
|
1259
|
+
* indicate this with <> around the name. Put [] around the name for an optional argument.
|
|
1260
|
+
*
|
|
1261
|
+
* @example
|
|
1262
|
+
* program.argument('<input-file>');
|
|
1263
|
+
* program.argument('[output-file]');
|
|
1264
|
+
*
|
|
1265
|
+
* @param {string} name
|
|
1266
|
+
* @param {string} [description]
|
|
1267
|
+
* @param {(Function|*)} [parseArg] - custom argument processing function or default value
|
|
1268
|
+
* @param {*} [defaultValue]
|
|
1269
|
+
* @return {Command} `this` command for chaining
|
|
1270
|
+
*/
|
|
1271
|
+
argument(name, description, parseArg, defaultValue) {
|
|
1272
|
+
const argument = this.createArgument(name, description);
|
|
1273
|
+
if (typeof parseArg === "function") argument.default(defaultValue).argParser(parseArg);
|
|
1274
|
+
else argument.default(parseArg);
|
|
1275
|
+
this.addArgument(argument);
|
|
1276
|
+
return this;
|
|
1277
|
+
}
|
|
1278
|
+
/**
|
|
1279
|
+
* Define argument syntax for command, adding multiple at once (without descriptions).
|
|
1280
|
+
*
|
|
1281
|
+
* See also .argument().
|
|
1282
|
+
*
|
|
1283
|
+
* @example
|
|
1284
|
+
* program.arguments('<cmd> [env]');
|
|
1285
|
+
*
|
|
1286
|
+
* @param {string} names
|
|
1287
|
+
* @return {Command} `this` command for chaining
|
|
1288
|
+
*/
|
|
1289
|
+
arguments(names) {
|
|
1290
|
+
names.trim().split(/ +/).forEach((detail) => {
|
|
1291
|
+
this.argument(detail);
|
|
1292
|
+
});
|
|
1293
|
+
return this;
|
|
1294
|
+
}
|
|
1295
|
+
/**
|
|
1296
|
+
* Define argument syntax for command, adding a prepared argument.
|
|
1297
|
+
*
|
|
1298
|
+
* @param {Argument} argument
|
|
1299
|
+
* @return {Command} `this` command for chaining
|
|
1300
|
+
*/
|
|
1301
|
+
addArgument(argument) {
|
|
1302
|
+
const previousArgument = this.registeredArguments.slice(-1)[0];
|
|
1303
|
+
if (previousArgument?.variadic) throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
|
|
1304
|
+
if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
|
|
1305
|
+
this.registeredArguments.push(argument);
|
|
1306
|
+
return this;
|
|
1307
|
+
}
|
|
1308
|
+
/**
|
|
1309
|
+
* Customise or override default help command. By default a help command is automatically added if your command has subcommands.
|
|
1310
|
+
*
|
|
1311
|
+
* @example
|
|
1312
|
+
* program.helpCommand('help [cmd]');
|
|
1313
|
+
* program.helpCommand('help [cmd]', 'show help');
|
|
1314
|
+
* program.helpCommand(false); // suppress default help command
|
|
1315
|
+
* program.helpCommand(true); // add help command even if no subcommands
|
|
1316
|
+
*
|
|
1317
|
+
* @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
|
|
1318
|
+
* @param {string} [description] - custom description
|
|
1319
|
+
* @return {Command} `this` command for chaining
|
|
1320
|
+
*/
|
|
1321
|
+
helpCommand(enableOrNameAndArgs, description) {
|
|
1322
|
+
if (typeof enableOrNameAndArgs === "boolean") {
|
|
1323
|
+
this._addImplicitHelpCommand = enableOrNameAndArgs;
|
|
1324
|
+
if (enableOrNameAndArgs && this._defaultCommandGroup) this._initCommandGroup(this._getHelpCommand());
|
|
1325
|
+
return this;
|
|
1326
|
+
}
|
|
1327
|
+
const [, helpName, helpArgs] = (enableOrNameAndArgs ?? "help [command]").match(/([^ ]+) *(.*)/);
|
|
1328
|
+
const helpDescription = description ?? "display help for command";
|
|
1329
|
+
const helpCommand = this.createCommand(helpName);
|
|
1330
|
+
helpCommand.helpOption(false);
|
|
1331
|
+
if (helpArgs) helpCommand.arguments(helpArgs);
|
|
1332
|
+
if (helpDescription) helpCommand.description(helpDescription);
|
|
1333
|
+
this._addImplicitHelpCommand = true;
|
|
1334
|
+
this._helpCommand = helpCommand;
|
|
1335
|
+
if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
|
|
1336
|
+
return this;
|
|
1337
|
+
}
|
|
1338
|
+
/**
|
|
1339
|
+
* Add prepared custom help command.
|
|
1340
|
+
*
|
|
1341
|
+
* @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
|
|
1342
|
+
* @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
|
|
1343
|
+
* @return {Command} `this` command for chaining
|
|
1344
|
+
*/
|
|
1345
|
+
addHelpCommand(helpCommand, deprecatedDescription) {
|
|
1346
|
+
if (typeof helpCommand !== "object") {
|
|
1347
|
+
this.helpCommand(helpCommand, deprecatedDescription);
|
|
1348
|
+
return this;
|
|
1349
|
+
}
|
|
1350
|
+
this._addImplicitHelpCommand = true;
|
|
1351
|
+
this._helpCommand = helpCommand;
|
|
1352
|
+
this._initCommandGroup(helpCommand);
|
|
1353
|
+
return this;
|
|
1354
|
+
}
|
|
1355
|
+
/**
|
|
1356
|
+
* Lazy create help command.
|
|
1357
|
+
*
|
|
1358
|
+
* @return {(Command|null)}
|
|
1359
|
+
* @package
|
|
1360
|
+
*/
|
|
1361
|
+
_getHelpCommand() {
|
|
1362
|
+
if (this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"))) {
|
|
1363
|
+
if (this._helpCommand === void 0) this.helpCommand(void 0, void 0);
|
|
1364
|
+
return this._helpCommand;
|
|
1365
|
+
}
|
|
1366
|
+
return null;
|
|
1367
|
+
}
|
|
1368
|
+
/**
|
|
1369
|
+
* Add hook for life cycle event.
|
|
1370
|
+
*
|
|
1371
|
+
* @param {string} event
|
|
1372
|
+
* @param {Function} listener
|
|
1373
|
+
* @return {Command} `this` command for chaining
|
|
1374
|
+
*/
|
|
1375
|
+
hook(event, listener) {
|
|
1376
|
+
const allowedValues = [
|
|
1377
|
+
"preSubcommand",
|
|
1378
|
+
"preAction",
|
|
1379
|
+
"postAction"
|
|
1380
|
+
];
|
|
1381
|
+
if (!allowedValues.includes(event)) throw new Error(`Unexpected value for event passed to hook : '${event}'.
|
|
1382
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
1383
|
+
if (this._lifeCycleHooks[event]) this._lifeCycleHooks[event].push(listener);
|
|
1384
|
+
else this._lifeCycleHooks[event] = [listener];
|
|
1385
|
+
return this;
|
|
1386
|
+
}
|
|
1387
|
+
/**
|
|
1388
|
+
* Register callback to use as replacement for calling process.exit.
|
|
1389
|
+
*
|
|
1390
|
+
* @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
|
|
1391
|
+
* @return {Command} `this` command for chaining
|
|
1392
|
+
*/
|
|
1393
|
+
exitOverride(fn) {
|
|
1394
|
+
if (fn) this._exitCallback = fn;
|
|
1395
|
+
else this._exitCallback = (err) => {
|
|
1396
|
+
if (err.code !== "commander.executeSubCommandAsync") throw err;
|
|
1397
|
+
};
|
|
1398
|
+
return this;
|
|
1399
|
+
}
|
|
1400
|
+
/**
|
|
1401
|
+
* Call process.exit, and _exitCallback if defined.
|
|
1402
|
+
*
|
|
1403
|
+
* @param {number} exitCode exit code for using with process.exit
|
|
1404
|
+
* @param {string} code an id string representing the error
|
|
1405
|
+
* @param {string} message human-readable description of the error
|
|
1406
|
+
* @return never
|
|
1407
|
+
* @private
|
|
1408
|
+
*/
|
|
1409
|
+
_exit(exitCode, code, message) {
|
|
1410
|
+
if (this._exitCallback) this._exitCallback(new CommanderError(exitCode, code, message));
|
|
1411
|
+
process$1.exit(exitCode);
|
|
1412
|
+
}
|
|
1413
|
+
/**
|
|
1414
|
+
* Register callback `fn` for the command.
|
|
1415
|
+
*
|
|
1416
|
+
* @example
|
|
1417
|
+
* program
|
|
1418
|
+
* .command('serve')
|
|
1419
|
+
* .description('start service')
|
|
1420
|
+
* .action(function() {
|
|
1421
|
+
* // do work here
|
|
1422
|
+
* });
|
|
1423
|
+
*
|
|
1424
|
+
* @param {Function} fn
|
|
1425
|
+
* @return {Command} `this` command for chaining
|
|
1426
|
+
*/
|
|
1427
|
+
action(fn) {
|
|
1428
|
+
const listener = (args) => {
|
|
1429
|
+
const expectedArgsCount = this.registeredArguments.length;
|
|
1430
|
+
const actionArgs = args.slice(0, expectedArgsCount);
|
|
1431
|
+
if (this._storeOptionsAsProperties) actionArgs[expectedArgsCount] = this;
|
|
1432
|
+
else actionArgs[expectedArgsCount] = this.opts();
|
|
1433
|
+
actionArgs.push(this);
|
|
1434
|
+
return fn.apply(this, actionArgs);
|
|
1435
|
+
};
|
|
1436
|
+
this._actionHandler = listener;
|
|
1437
|
+
return this;
|
|
1438
|
+
}
|
|
1439
|
+
/**
|
|
1440
|
+
* Factory routine to create a new unattached option.
|
|
1441
|
+
*
|
|
1442
|
+
* See .option() for creating an attached option, which uses this routine to
|
|
1443
|
+
* create the option. You can override createOption to return a custom option.
|
|
1444
|
+
*
|
|
1445
|
+
* @param {string} flags
|
|
1446
|
+
* @param {string} [description]
|
|
1447
|
+
* @return {Option} new option
|
|
1448
|
+
*/
|
|
1449
|
+
createOption(flags, description) {
|
|
1450
|
+
return new Option(flags, description);
|
|
1451
|
+
}
|
|
1452
|
+
/**
|
|
1453
|
+
* Wrap parseArgs to catch 'commander.invalidArgument'.
|
|
1454
|
+
*
|
|
1455
|
+
* @param {(Option | Argument)} target
|
|
1456
|
+
* @param {string} value
|
|
1457
|
+
* @param {*} previous
|
|
1458
|
+
* @param {string} invalidArgumentMessage
|
|
1459
|
+
* @private
|
|
1460
|
+
*/
|
|
1461
|
+
_callParseArg(target, value, previous, invalidArgumentMessage) {
|
|
1462
|
+
try {
|
|
1463
|
+
return target.parseArg(value, previous);
|
|
1464
|
+
} catch (err) {
|
|
1465
|
+
if (err.code === "commander.invalidArgument") {
|
|
1466
|
+
const message = `${invalidArgumentMessage} ${err.message}`;
|
|
1467
|
+
this.error(message, {
|
|
1468
|
+
exitCode: err.exitCode,
|
|
1469
|
+
code: err.code
|
|
1470
|
+
});
|
|
1471
|
+
}
|
|
1472
|
+
throw err;
|
|
1473
|
+
}
|
|
1474
|
+
}
|
|
1475
|
+
/**
|
|
1476
|
+
* Check for option flag conflicts.
|
|
1477
|
+
* Register option if no conflicts found, or throw on conflict.
|
|
1478
|
+
*
|
|
1479
|
+
* @param {Option} option
|
|
1480
|
+
* @private
|
|
1481
|
+
*/
|
|
1482
|
+
_registerOption(option) {
|
|
1483
|
+
const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
|
|
1484
|
+
if (matchingOption) {
|
|
1485
|
+
const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
|
|
1486
|
+
throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
|
|
1487
|
+
- already used by option '${matchingOption.flags}'`);
|
|
1488
|
+
}
|
|
1489
|
+
this._initOptionGroup(option);
|
|
1490
|
+
this.options.push(option);
|
|
1491
|
+
}
|
|
1492
|
+
/**
|
|
1493
|
+
* Check for command name and alias conflicts with existing commands.
|
|
1494
|
+
* Register command if no conflicts found, or throw on conflict.
|
|
1495
|
+
*
|
|
1496
|
+
* @param {Command} command
|
|
1497
|
+
* @private
|
|
1498
|
+
*/
|
|
1499
|
+
_registerCommand(command) {
|
|
1500
|
+
const knownBy = (cmd) => {
|
|
1501
|
+
return [cmd.name()].concat(cmd.aliases());
|
|
1502
|
+
};
|
|
1503
|
+
const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
|
|
1504
|
+
if (alreadyUsed) {
|
|
1505
|
+
const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
|
|
1506
|
+
const newCmd = knownBy(command).join("|");
|
|
1507
|
+
throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
|
|
1508
|
+
}
|
|
1509
|
+
this._initCommandGroup(command);
|
|
1510
|
+
this.commands.push(command);
|
|
1511
|
+
}
|
|
1512
|
+
/**
|
|
1513
|
+
* Add an option.
|
|
1514
|
+
*
|
|
1515
|
+
* @param {Option} option
|
|
1516
|
+
* @return {Command} `this` command for chaining
|
|
1517
|
+
*/
|
|
1518
|
+
addOption(option) {
|
|
1519
|
+
this._registerOption(option);
|
|
1520
|
+
const oname = option.name();
|
|
1521
|
+
const name = option.attributeName();
|
|
1522
|
+
if (option.defaultValue !== void 0) this.setOptionValueWithSource(name, option.defaultValue, "default");
|
|
1523
|
+
const handleOptionValue = (val, invalidValueMessage, valueSource) => {
|
|
1524
|
+
if (val == null && option.presetArg !== void 0) val = option.presetArg;
|
|
1525
|
+
const oldValue = this.getOptionValue(name);
|
|
1526
|
+
if (val !== null && option.parseArg) val = this._callParseArg(option, val, oldValue, invalidValueMessage);
|
|
1527
|
+
else if (val !== null && option.variadic) val = option._collectValue(val, oldValue);
|
|
1528
|
+
if (val == null) {
|
|
1529
|
+
if (option.negate) val = false;
|
|
1530
|
+
else if (option.isBoolean() || option.optional) val = true;
|
|
1531
|
+
else val = "";
|
|
1532
|
+
}
|
|
1533
|
+
this.setOptionValueWithSource(name, val, valueSource);
|
|
1534
|
+
};
|
|
1535
|
+
this.on("option:" + oname, (val) => {
|
|
1536
|
+
const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
|
|
1537
|
+
handleOptionValue(val, invalidValueMessage, "cli");
|
|
1538
|
+
});
|
|
1539
|
+
if (option.envVar) this.on("optionEnv:" + oname, (val) => {
|
|
1540
|
+
const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
|
|
1541
|
+
handleOptionValue(val, invalidValueMessage, "env");
|
|
1542
|
+
});
|
|
1543
|
+
return this;
|
|
1544
|
+
}
|
|
1545
|
+
/**
|
|
1546
|
+
* Internal implementation shared by .option() and .requiredOption()
|
|
1547
|
+
*
|
|
1548
|
+
* @return {Command} `this` command for chaining
|
|
1549
|
+
* @private
|
|
1550
|
+
*/
|
|
1551
|
+
_optionEx(config, flags, description, fn, defaultValue) {
|
|
1552
|
+
if (typeof flags === "object" && flags instanceof Option) throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
|
|
1553
|
+
const option = this.createOption(flags, description);
|
|
1554
|
+
option.makeOptionMandatory(!!config.mandatory);
|
|
1555
|
+
if (typeof fn === "function") option.default(defaultValue).argParser(fn);
|
|
1556
|
+
else if (fn instanceof RegExp) {
|
|
1557
|
+
const regex = fn;
|
|
1558
|
+
fn = (val, def) => {
|
|
1559
|
+
const m = regex.exec(val);
|
|
1560
|
+
return m ? m[0] : def;
|
|
1561
|
+
};
|
|
1562
|
+
option.default(defaultValue).argParser(fn);
|
|
1563
|
+
} else option.default(fn);
|
|
1564
|
+
return this.addOption(option);
|
|
1565
|
+
}
|
|
1566
|
+
/**
|
|
1567
|
+
* Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
|
|
1568
|
+
*
|
|
1569
|
+
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
|
|
1570
|
+
* option-argument is indicated by `<>` and an optional option-argument by `[]`.
|
|
1571
|
+
*
|
|
1572
|
+
* See the README for more details, and see also addOption() and requiredOption().
|
|
1573
|
+
*
|
|
1574
|
+
* @example
|
|
1575
|
+
* program
|
|
1576
|
+
* .option('-p, --pepper', 'add pepper')
|
|
1577
|
+
* .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
|
|
1578
|
+
* .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
|
|
1579
|
+
* .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
|
|
1580
|
+
*
|
|
1581
|
+
* @param {string} flags
|
|
1582
|
+
* @param {string} [description]
|
|
1583
|
+
* @param {(Function|*)} [parseArg] - custom option processing function or default value
|
|
1584
|
+
* @param {*} [defaultValue]
|
|
1585
|
+
* @return {Command} `this` command for chaining
|
|
1586
|
+
*/
|
|
1587
|
+
option(flags, description, parseArg, defaultValue) {
|
|
1588
|
+
return this._optionEx({}, flags, description, parseArg, defaultValue);
|
|
1589
|
+
}
|
|
1590
|
+
/**
|
|
1591
|
+
* Add a required option which must have a value after parsing. This usually means
|
|
1592
|
+
* the option must be specified on the command line. (Otherwise the same as .option().)
|
|
1593
|
+
*
|
|
1594
|
+
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
|
|
1595
|
+
*
|
|
1596
|
+
* @param {string} flags
|
|
1597
|
+
* @param {string} [description]
|
|
1598
|
+
* @param {(Function|*)} [parseArg] - custom option processing function or default value
|
|
1599
|
+
* @param {*} [defaultValue]
|
|
1600
|
+
* @return {Command} `this` command for chaining
|
|
1601
|
+
*/
|
|
1602
|
+
requiredOption(flags, description, parseArg, defaultValue) {
|
|
1603
|
+
return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
|
|
1604
|
+
}
|
|
1605
|
+
/**
|
|
1606
|
+
* Alter parsing of short flags with optional values.
|
|
1607
|
+
*
|
|
1608
|
+
* @example
|
|
1609
|
+
* // for `.option('-f,--flag [value]'):
|
|
1610
|
+
* program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
|
|
1611
|
+
* program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
|
|
1612
|
+
*
|
|
1613
|
+
* @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
|
|
1614
|
+
* @return {Command} `this` command for chaining
|
|
1615
|
+
*/
|
|
1616
|
+
combineFlagAndOptionalValue(combine = true) {
|
|
1617
|
+
this._combineFlagAndOptionalValue = !!combine;
|
|
1618
|
+
return this;
|
|
1619
|
+
}
|
|
1620
|
+
/**
|
|
1621
|
+
* Allow unknown options on the command line.
|
|
1622
|
+
*
|
|
1623
|
+
* @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
|
|
1624
|
+
* @return {Command} `this` command for chaining
|
|
1625
|
+
*/
|
|
1626
|
+
allowUnknownOption(allowUnknown = true) {
|
|
1627
|
+
this._allowUnknownOption = !!allowUnknown;
|
|
1628
|
+
return this;
|
|
1629
|
+
}
|
|
1630
|
+
/**
|
|
1631
|
+
* Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
|
|
1632
|
+
*
|
|
1633
|
+
* @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
|
|
1634
|
+
* @return {Command} `this` command for chaining
|
|
1635
|
+
*/
|
|
1636
|
+
allowExcessArguments(allowExcess = true) {
|
|
1637
|
+
this._allowExcessArguments = !!allowExcess;
|
|
1638
|
+
return this;
|
|
1639
|
+
}
|
|
1640
|
+
/**
|
|
1641
|
+
* Enable positional options. Positional means global options are specified before subcommands which lets
|
|
1642
|
+
* subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
|
|
1643
|
+
* The default behaviour is non-positional and global options may appear anywhere on the command line.
|
|
1644
|
+
*
|
|
1645
|
+
* @param {boolean} [positional]
|
|
1646
|
+
* @return {Command} `this` command for chaining
|
|
1647
|
+
*/
|
|
1648
|
+
enablePositionalOptions(positional = true) {
|
|
1649
|
+
this._enablePositionalOptions = !!positional;
|
|
1650
|
+
return this;
|
|
1651
|
+
}
|
|
1652
|
+
/**
|
|
1653
|
+
* Pass through options that come after command-arguments rather than treat them as command-options,
|
|
1654
|
+
* so actual command-options come before command-arguments. Turning this on for a subcommand requires
|
|
1655
|
+
* positional options to have been enabled on the program (parent commands).
|
|
1656
|
+
* The default behaviour is non-positional and options may appear before or after command-arguments.
|
|
1657
|
+
*
|
|
1658
|
+
* @param {boolean} [passThrough] for unknown options.
|
|
1659
|
+
* @return {Command} `this` command for chaining
|
|
1660
|
+
*/
|
|
1661
|
+
passThroughOptions(passThrough = true) {
|
|
1662
|
+
this._passThroughOptions = !!passThrough;
|
|
1663
|
+
this._checkForBrokenPassThrough();
|
|
1664
|
+
return this;
|
|
1665
|
+
}
|
|
1666
|
+
/**
|
|
1667
|
+
* @private
|
|
1668
|
+
*/
|
|
1669
|
+
_checkForBrokenPassThrough() {
|
|
1670
|
+
if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
|
|
1671
|
+
}
|
|
1672
|
+
/**
|
|
1673
|
+
* Whether to store option values as properties on command object,
|
|
1674
|
+
* or store separately (specify false). In both cases the option values can be accessed using .opts().
|
|
1675
|
+
*
|
|
1676
|
+
* @param {boolean} [storeAsProperties=true]
|
|
1677
|
+
* @return {Command} `this` command for chaining
|
|
1678
|
+
*/
|
|
1679
|
+
storeOptionsAsProperties(storeAsProperties = true) {
|
|
1680
|
+
if (this.options.length) throw new Error("call .storeOptionsAsProperties() before adding options");
|
|
1681
|
+
if (Object.keys(this._optionValues).length) throw new Error("call .storeOptionsAsProperties() before setting option values");
|
|
1682
|
+
this._storeOptionsAsProperties = !!storeAsProperties;
|
|
1683
|
+
return this;
|
|
1684
|
+
}
|
|
1685
|
+
/**
|
|
1686
|
+
* Retrieve option value.
|
|
1687
|
+
*
|
|
1688
|
+
* @param {string} key
|
|
1689
|
+
* @return {object} value
|
|
1690
|
+
*/
|
|
1691
|
+
getOptionValue(key) {
|
|
1692
|
+
if (this._storeOptionsAsProperties) return this[key];
|
|
1693
|
+
return this._optionValues[key];
|
|
1694
|
+
}
|
|
1695
|
+
/**
|
|
1696
|
+
* Store option value.
|
|
1697
|
+
*
|
|
1698
|
+
* @param {string} key
|
|
1699
|
+
* @param {object} value
|
|
1700
|
+
* @return {Command} `this` command for chaining
|
|
1701
|
+
*/
|
|
1702
|
+
setOptionValue(key, value) {
|
|
1703
|
+
return this.setOptionValueWithSource(key, value, void 0);
|
|
1704
|
+
}
|
|
1705
|
+
/**
|
|
1706
|
+
* Store option value and where the value came from.
|
|
1707
|
+
*
|
|
1708
|
+
* @param {string} key
|
|
1709
|
+
* @param {object} value
|
|
1710
|
+
* @param {string} source - expected values are default/config/env/cli/implied
|
|
1711
|
+
* @return {Command} `this` command for chaining
|
|
1712
|
+
*/
|
|
1713
|
+
setOptionValueWithSource(key, value, source) {
|
|
1714
|
+
if (this._storeOptionsAsProperties) this[key] = value;
|
|
1715
|
+
else this._optionValues[key] = value;
|
|
1716
|
+
this._optionValueSources[key] = source;
|
|
1717
|
+
return this;
|
|
1718
|
+
}
|
|
1719
|
+
/**
|
|
1720
|
+
* Get source of option value.
|
|
1721
|
+
* Expected values are default | config | env | cli | implied
|
|
1722
|
+
*
|
|
1723
|
+
* @param {string} key
|
|
1724
|
+
* @return {string}
|
|
1725
|
+
*/
|
|
1726
|
+
getOptionValueSource(key) {
|
|
1727
|
+
return this._optionValueSources[key];
|
|
1728
|
+
}
|
|
1729
|
+
/**
|
|
1730
|
+
* Get source of option value. See also .optsWithGlobals().
|
|
1731
|
+
* Expected values are default | config | env | cli | implied
|
|
1732
|
+
*
|
|
1733
|
+
* @param {string} key
|
|
1734
|
+
* @return {string}
|
|
1735
|
+
*/
|
|
1736
|
+
getOptionValueSourceWithGlobals(key) {
|
|
1737
|
+
let source;
|
|
1738
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
1739
|
+
if (cmd.getOptionValueSource(key) !== void 0) source = cmd.getOptionValueSource(key);
|
|
1740
|
+
});
|
|
1741
|
+
return source;
|
|
1742
|
+
}
|
|
1743
|
+
/**
|
|
1744
|
+
* Get user arguments from implied or explicit arguments.
|
|
1745
|
+
* Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
|
|
1746
|
+
*
|
|
1747
|
+
* @private
|
|
1748
|
+
*/
|
|
1749
|
+
_prepareUserArgs(argv, parseOptions) {
|
|
1750
|
+
if (argv !== void 0 && !Array.isArray(argv)) throw new Error("first parameter to parse must be array or undefined");
|
|
1751
|
+
parseOptions = parseOptions || {};
|
|
1752
|
+
if (argv === void 0 && parseOptions.from === void 0) {
|
|
1753
|
+
if (process$1.versions?.electron) parseOptions.from = "electron";
|
|
1754
|
+
const execArgv = process$1.execArgv ?? [];
|
|
1755
|
+
if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) parseOptions.from = "eval";
|
|
1756
|
+
}
|
|
1757
|
+
if (argv === void 0) argv = process$1.argv;
|
|
1758
|
+
this.rawArgs = argv.slice();
|
|
1759
|
+
let userArgs;
|
|
1760
|
+
switch (parseOptions.from) {
|
|
1761
|
+
case void 0:
|
|
1762
|
+
case "node":
|
|
1763
|
+
this._scriptPath = argv[1];
|
|
1764
|
+
userArgs = argv.slice(2);
|
|
1765
|
+
break;
|
|
1766
|
+
case "electron":
|
|
1767
|
+
if (process$1.defaultApp) {
|
|
1768
|
+
this._scriptPath = argv[1];
|
|
1769
|
+
userArgs = argv.slice(2);
|
|
1770
|
+
} else userArgs = argv.slice(1);
|
|
1771
|
+
break;
|
|
1772
|
+
case "user":
|
|
1773
|
+
userArgs = argv.slice(0);
|
|
1774
|
+
break;
|
|
1775
|
+
case "eval":
|
|
1776
|
+
userArgs = argv.slice(1);
|
|
1777
|
+
break;
|
|
1778
|
+
default: throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
|
|
1779
|
+
}
|
|
1780
|
+
if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);
|
|
1781
|
+
this._name = this._name || "program";
|
|
1782
|
+
return userArgs;
|
|
1783
|
+
}
|
|
1784
|
+
/**
|
|
1785
|
+
* Parse `argv`, setting options and invoking commands when defined.
|
|
1786
|
+
*
|
|
1787
|
+
* Use parseAsync instead of parse if any of your action handlers are async.
|
|
1788
|
+
*
|
|
1789
|
+
* Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
|
|
1790
|
+
*
|
|
1791
|
+
* Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
|
|
1792
|
+
* - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
|
|
1793
|
+
* - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
|
|
1794
|
+
* - `'user'`: just user arguments
|
|
1795
|
+
*
|
|
1796
|
+
* @example
|
|
1797
|
+
* program.parse(); // parse process.argv and auto-detect electron and special node flags
|
|
1798
|
+
* program.parse(process.argv); // assume argv[0] is app and argv[1] is script
|
|
1799
|
+
* program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
|
|
1800
|
+
*
|
|
1801
|
+
* @param {string[]} [argv] - optional, defaults to process.argv
|
|
1802
|
+
* @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
|
|
1803
|
+
* @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
|
|
1804
|
+
* @return {Command} `this` command for chaining
|
|
1805
|
+
*/
|
|
1806
|
+
parse(argv, parseOptions) {
|
|
1807
|
+
this._prepareForParse();
|
|
1808
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
1809
|
+
this._parseCommand([], userArgs);
|
|
1810
|
+
return this;
|
|
1811
|
+
}
|
|
1812
|
+
/**
|
|
1813
|
+
* Parse `argv`, setting options and invoking commands when defined.
|
|
1814
|
+
*
|
|
1815
|
+
* Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
|
|
1816
|
+
*
|
|
1817
|
+
* Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
|
|
1818
|
+
* - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
|
|
1819
|
+
* - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
|
|
1820
|
+
* - `'user'`: just user arguments
|
|
1821
|
+
*
|
|
1822
|
+
* @example
|
|
1823
|
+
* await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
|
|
1824
|
+
* await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
|
|
1825
|
+
* await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
|
|
1826
|
+
*
|
|
1827
|
+
* @param {string[]} [argv]
|
|
1828
|
+
* @param {object} [parseOptions]
|
|
1829
|
+
* @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
|
|
1830
|
+
* @return {Promise}
|
|
1831
|
+
*/
|
|
1832
|
+
async parseAsync(argv, parseOptions) {
|
|
1833
|
+
this._prepareForParse();
|
|
1834
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
1835
|
+
await this._parseCommand([], userArgs);
|
|
1836
|
+
return this;
|
|
1837
|
+
}
|
|
1838
|
+
_prepareForParse() {
|
|
1839
|
+
if (this._savedState === null) {
|
|
1840
|
+
this.options.filter((option) => option.negate && option.defaultValue === void 0 && this.getOptionValue(option.attributeName()) === void 0).forEach((option) => {
|
|
1841
|
+
const positiveLongFlag = option.long.replace(/^--no-/, "--");
|
|
1842
|
+
if (!this._findOption(positiveLongFlag)) this.setOptionValueWithSource(option.attributeName(), true, "default");
|
|
1843
|
+
});
|
|
1844
|
+
this.saveStateBeforeParse();
|
|
1845
|
+
} else this.restoreStateBeforeParse();
|
|
1846
|
+
}
|
|
1847
|
+
/**
|
|
1848
|
+
* Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
|
|
1849
|
+
* Not usually called directly, but available for subclasses to save their custom state.
|
|
1850
|
+
*
|
|
1851
|
+
* This is called in a lazy way. Only commands used in parsing chain will have state saved.
|
|
1852
|
+
*/
|
|
1853
|
+
saveStateBeforeParse() {
|
|
1854
|
+
this._savedState = {
|
|
1855
|
+
_name: this._name,
|
|
1856
|
+
_optionValues: { ...this._optionValues },
|
|
1857
|
+
_optionValueSources: { ...this._optionValueSources }
|
|
1858
|
+
};
|
|
1859
|
+
}
|
|
1860
|
+
/**
|
|
1861
|
+
* Restore state before parse for calls after the first.
|
|
1862
|
+
* Not usually called directly, but available for subclasses to save their custom state.
|
|
1863
|
+
*
|
|
1864
|
+
* This is called in a lazy way. Only commands used in parsing chain will have state restored.
|
|
1865
|
+
*/
|
|
1866
|
+
restoreStateBeforeParse() {
|
|
1867
|
+
if (this._storeOptionsAsProperties) throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
1868
|
+
- either make a new Command for each call to parse, or stop storing options as properties`);
|
|
1869
|
+
this._name = this._savedState._name;
|
|
1870
|
+
this._scriptPath = null;
|
|
1871
|
+
this.rawArgs = [];
|
|
1872
|
+
this._optionValues = { ...this._savedState._optionValues };
|
|
1873
|
+
this._optionValueSources = { ...this._savedState._optionValueSources };
|
|
1874
|
+
this.args = [];
|
|
1875
|
+
this.processedArgs = [];
|
|
1876
|
+
}
|
|
1877
|
+
/**
|
|
1878
|
+
* Throw if expected executable is missing. Add lots of help for author.
|
|
1879
|
+
*
|
|
1880
|
+
* @param {string} executableFile
|
|
1881
|
+
* @param {string} executableDir
|
|
1882
|
+
* @param {string} subcommandName
|
|
1883
|
+
*/
|
|
1884
|
+
_checkForMissingExecutable(executableFile, executableDir, subcommandName) {
|
|
1885
|
+
if (fs.existsSync(executableFile)) return;
|
|
1886
|
+
const executableMissing = `'${executableFile}' does not exist
|
|
1887
|
+
- if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
1888
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
1889
|
+
- ${executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory"}`;
|
|
1890
|
+
throw new Error(executableMissing);
|
|
1891
|
+
}
|
|
1892
|
+
/**
|
|
1893
|
+
* Execute a sub-command executable.
|
|
1894
|
+
*
|
|
1895
|
+
* @private
|
|
1896
|
+
*/
|
|
1897
|
+
_executeSubCommand(subcommand, args) {
|
|
1898
|
+
args = args.slice();
|
|
1899
|
+
const sourceExt = [
|
|
1900
|
+
".js",
|
|
1901
|
+
".ts",
|
|
1902
|
+
".tsx",
|
|
1903
|
+
".mjs",
|
|
1904
|
+
".cjs"
|
|
1905
|
+
];
|
|
1906
|
+
function findFile(baseDir, baseName) {
|
|
1907
|
+
const localBin = path.resolve(baseDir, baseName);
|
|
1908
|
+
if (fs.existsSync(localBin)) return localBin;
|
|
1909
|
+
if (sourceExt.includes(path.extname(baseName))) return void 0;
|
|
1910
|
+
const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
|
|
1911
|
+
if (foundExt) return `${localBin}${foundExt}`;
|
|
1912
|
+
}
|
|
1913
|
+
this._checkForMissingMandatoryOptions();
|
|
1914
|
+
this._checkForConflictingOptions();
|
|
1915
|
+
let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
|
|
1916
|
+
let executableDir = this._executableDir || "";
|
|
1917
|
+
if (this._scriptPath) {
|
|
1918
|
+
let resolvedScriptPath;
|
|
1919
|
+
try {
|
|
1920
|
+
resolvedScriptPath = fs.realpathSync(this._scriptPath);
|
|
1921
|
+
} catch {
|
|
1922
|
+
resolvedScriptPath = this._scriptPath;
|
|
1923
|
+
}
|
|
1924
|
+
executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
|
|
1925
|
+
}
|
|
1926
|
+
if (executableDir) {
|
|
1927
|
+
let localFile = findFile(executableDir, executableFile);
|
|
1928
|
+
if (!localFile && !subcommand._executableFile && this._scriptPath) {
|
|
1929
|
+
const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
|
|
1930
|
+
if (legacyName !== this._name) localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
|
|
1931
|
+
}
|
|
1932
|
+
executableFile = localFile || executableFile;
|
|
1933
|
+
}
|
|
1934
|
+
const launchWithNode = sourceExt.includes(path.extname(executableFile));
|
|
1935
|
+
let proc;
|
|
1936
|
+
if (process$1.platform !== "win32") {
|
|
1937
|
+
if (launchWithNode) {
|
|
1938
|
+
args.unshift(executableFile);
|
|
1939
|
+
args = incrementNodeInspectorPort(process$1.execArgv).concat(args);
|
|
1940
|
+
proc = childProcess.spawn(process$1.argv[0], args, { stdio: "inherit" });
|
|
1941
|
+
} else proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
|
|
1942
|
+
} else {
|
|
1943
|
+
this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
|
|
1944
|
+
args.unshift(executableFile);
|
|
1945
|
+
args = incrementNodeInspectorPort(process$1.execArgv).concat(args);
|
|
1946
|
+
proc = childProcess.spawn(process$1.execPath, args, { stdio: "inherit" });
|
|
1947
|
+
}
|
|
1948
|
+
if (!proc.killed) [
|
|
1949
|
+
"SIGUSR1",
|
|
1950
|
+
"SIGUSR2",
|
|
1951
|
+
"SIGTERM",
|
|
1952
|
+
"SIGINT",
|
|
1953
|
+
"SIGHUP"
|
|
1954
|
+
].forEach((signal) => {
|
|
1955
|
+
process$1.on(signal, () => {
|
|
1956
|
+
if (proc.killed === false && proc.exitCode === null) proc.kill(signal);
|
|
1957
|
+
});
|
|
1958
|
+
});
|
|
1959
|
+
const exitCallback = this._exitCallback;
|
|
1960
|
+
proc.on("close", (code) => {
|
|
1961
|
+
code = code ?? 1;
|
|
1962
|
+
if (!exitCallback) process$1.exit(code);
|
|
1963
|
+
else exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
|
|
1964
|
+
});
|
|
1965
|
+
proc.on("error", (err) => {
|
|
1966
|
+
if (err.code === "ENOENT") this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
|
|
1967
|
+
else if (err.code === "EACCES") throw new Error(`'${executableFile}' not executable`);
|
|
1968
|
+
if (!exitCallback) process$1.exit(1);
|
|
1969
|
+
else {
|
|
1970
|
+
const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
|
|
1971
|
+
wrappedError.nestedError = err;
|
|
1972
|
+
exitCallback(wrappedError);
|
|
1973
|
+
}
|
|
1974
|
+
});
|
|
1975
|
+
this.runningCommand = proc;
|
|
1976
|
+
}
|
|
1977
|
+
/**
|
|
1978
|
+
* @private
|
|
1979
|
+
*/
|
|
1980
|
+
_dispatchSubcommand(commandName, operands, unknown) {
|
|
1981
|
+
const subCommand = this._findCommand(commandName);
|
|
1982
|
+
if (!subCommand) this.help({ error: true });
|
|
1983
|
+
subCommand._prepareForParse();
|
|
1984
|
+
let promiseChain;
|
|
1985
|
+
promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
|
|
1986
|
+
promiseChain = this._chainOrCall(promiseChain, () => {
|
|
1987
|
+
if (subCommand._executableHandler) this._executeSubCommand(subCommand, operands.concat(unknown));
|
|
1988
|
+
else return subCommand._parseCommand(operands, unknown);
|
|
1989
|
+
});
|
|
1990
|
+
return promiseChain;
|
|
1991
|
+
}
|
|
1992
|
+
/**
|
|
1993
|
+
* Invoke help directly if possible, or dispatch if necessary.
|
|
1994
|
+
* e.g. help foo
|
|
1995
|
+
*
|
|
1996
|
+
* @private
|
|
1997
|
+
*/
|
|
1998
|
+
_dispatchHelpCommand(subcommandName) {
|
|
1999
|
+
if (!subcommandName) this.help();
|
|
2000
|
+
const subCommand = this._findCommand(subcommandName);
|
|
2001
|
+
if (subCommand && !subCommand._executableHandler) subCommand.help();
|
|
2002
|
+
return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
|
|
2003
|
+
}
|
|
2004
|
+
/**
|
|
2005
|
+
* Check this.args against expected this.registeredArguments.
|
|
2006
|
+
*
|
|
2007
|
+
* @private
|
|
2008
|
+
*/
|
|
2009
|
+
_checkNumberOfArguments() {
|
|
2010
|
+
this.registeredArguments.forEach((arg, i) => {
|
|
2011
|
+
if (arg.required && this.args[i] == null) this.missingArgument(arg.name());
|
|
2012
|
+
});
|
|
2013
|
+
if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) return;
|
|
2014
|
+
if (this.args.length > this.registeredArguments.length) this._excessArguments(this.args);
|
|
2015
|
+
}
|
|
2016
|
+
/**
|
|
2017
|
+
* Process this.args using this.registeredArguments and save as this.processedArgs!
|
|
2018
|
+
*
|
|
2019
|
+
* @private
|
|
2020
|
+
*/
|
|
2021
|
+
_processArguments() {
|
|
2022
|
+
const myParseArg = (argument, value, previous) => {
|
|
2023
|
+
let parsedValue = value;
|
|
2024
|
+
if (value !== null && argument.parseArg) {
|
|
2025
|
+
const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
|
|
2026
|
+
parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
|
|
2027
|
+
}
|
|
2028
|
+
return parsedValue;
|
|
2029
|
+
};
|
|
2030
|
+
this._checkNumberOfArguments();
|
|
2031
|
+
const processedArgs = [];
|
|
2032
|
+
this.registeredArguments.forEach((declaredArg, index) => {
|
|
2033
|
+
let value = declaredArg.defaultValue;
|
|
2034
|
+
if (declaredArg.variadic) {
|
|
2035
|
+
if (index < this.args.length) {
|
|
2036
|
+
value = this.args.slice(index);
|
|
2037
|
+
if (declaredArg.parseArg) value = value.reduce((processed, v) => {
|
|
2038
|
+
return myParseArg(declaredArg, v, processed);
|
|
2039
|
+
}, declaredArg.defaultValue);
|
|
2040
|
+
} else if (value === void 0) value = [];
|
|
2041
|
+
} else if (index < this.args.length) {
|
|
2042
|
+
value = this.args[index];
|
|
2043
|
+
if (declaredArg.parseArg) value = myParseArg(declaredArg, value, declaredArg.defaultValue);
|
|
2044
|
+
}
|
|
2045
|
+
processedArgs[index] = value;
|
|
2046
|
+
});
|
|
2047
|
+
this.processedArgs = processedArgs;
|
|
2048
|
+
}
|
|
2049
|
+
/**
|
|
2050
|
+
* Once we have a promise we chain, but call synchronously until then.
|
|
2051
|
+
*
|
|
2052
|
+
* @param {(Promise|undefined)} promise
|
|
2053
|
+
* @param {Function} fn
|
|
2054
|
+
* @return {(Promise|undefined)}
|
|
2055
|
+
* @private
|
|
2056
|
+
*/
|
|
2057
|
+
_chainOrCall(promise, fn) {
|
|
2058
|
+
if (promise?.then && typeof promise.then === "function") return promise.then(() => fn());
|
|
2059
|
+
return fn();
|
|
2060
|
+
}
|
|
2061
|
+
/**
|
|
2062
|
+
*
|
|
2063
|
+
* @param {(Promise|undefined)} promise
|
|
2064
|
+
* @param {string} event
|
|
2065
|
+
* @return {(Promise|undefined)}
|
|
2066
|
+
* @private
|
|
2067
|
+
*/
|
|
2068
|
+
_chainOrCallHooks(promise, event) {
|
|
2069
|
+
let result = promise;
|
|
2070
|
+
const hooks = [];
|
|
2071
|
+
this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
|
|
2072
|
+
hookedCommand._lifeCycleHooks[event].forEach((callback) => {
|
|
2073
|
+
hooks.push({
|
|
2074
|
+
hookedCommand,
|
|
2075
|
+
callback
|
|
2076
|
+
});
|
|
2077
|
+
});
|
|
2078
|
+
});
|
|
2079
|
+
if (event === "postAction") hooks.reverse();
|
|
2080
|
+
hooks.forEach((hookDetail) => {
|
|
2081
|
+
result = this._chainOrCall(result, () => {
|
|
2082
|
+
return hookDetail.callback(hookDetail.hookedCommand, this);
|
|
2083
|
+
});
|
|
2084
|
+
});
|
|
2085
|
+
return result;
|
|
2086
|
+
}
|
|
2087
|
+
/**
|
|
2088
|
+
*
|
|
2089
|
+
* @param {(Promise|undefined)} promise
|
|
2090
|
+
* @param {Command} subCommand
|
|
2091
|
+
* @param {string} event
|
|
2092
|
+
* @return {(Promise|undefined)}
|
|
2093
|
+
* @private
|
|
2094
|
+
*/
|
|
2095
|
+
_chainOrCallSubCommandHook(promise, subCommand, event) {
|
|
2096
|
+
let result = promise;
|
|
2097
|
+
if (this._lifeCycleHooks[event] !== void 0) this._lifeCycleHooks[event].forEach((hook) => {
|
|
2098
|
+
result = this._chainOrCall(result, () => {
|
|
2099
|
+
return hook(this, subCommand);
|
|
2100
|
+
});
|
|
2101
|
+
});
|
|
2102
|
+
return result;
|
|
2103
|
+
}
|
|
2104
|
+
/**
|
|
2105
|
+
* Process arguments in context of this command.
|
|
2106
|
+
* Returns action result, in case it is a promise.
|
|
2107
|
+
*
|
|
2108
|
+
* @private
|
|
2109
|
+
*/
|
|
2110
|
+
_parseCommand(operands, unknown) {
|
|
2111
|
+
const parsed = this.parseOptions(unknown);
|
|
2112
|
+
this._parseOptionsEnv();
|
|
2113
|
+
this._parseOptionsImplied();
|
|
2114
|
+
operands = operands.concat(parsed.operands);
|
|
2115
|
+
unknown = parsed.unknown;
|
|
2116
|
+
this.args = operands.concat(unknown);
|
|
2117
|
+
if (operands && this._findCommand(operands[0])) return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
|
|
2118
|
+
if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) return this._dispatchHelpCommand(operands[1]);
|
|
2119
|
+
if (this._defaultCommandName) {
|
|
2120
|
+
this._outputHelpIfRequested(unknown);
|
|
2121
|
+
return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
|
|
2122
|
+
}
|
|
2123
|
+
if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) this.help({ error: true });
|
|
2124
|
+
this._outputHelpIfRequested(parsed.unknown);
|
|
2125
|
+
this._checkForMissingMandatoryOptions();
|
|
2126
|
+
this._checkForConflictingOptions();
|
|
2127
|
+
const checkForUnknownOptions = () => {
|
|
2128
|
+
if (parsed.unknown.length > 0) this.unknownOption(parsed.unknown[0]);
|
|
2129
|
+
};
|
|
2130
|
+
const commandEvent = `command:${this.name()}`;
|
|
2131
|
+
if (this._actionHandler) {
|
|
2132
|
+
checkForUnknownOptions();
|
|
2133
|
+
this._processArguments();
|
|
2134
|
+
let promiseChain;
|
|
2135
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
|
|
2136
|
+
promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
|
|
2137
|
+
if (this.parent) promiseChain = this._chainOrCall(promiseChain, () => {
|
|
2138
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
2139
|
+
});
|
|
2140
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
|
|
2141
|
+
return promiseChain;
|
|
2142
|
+
}
|
|
2143
|
+
if (this.parent?.listenerCount(commandEvent)) {
|
|
2144
|
+
checkForUnknownOptions();
|
|
2145
|
+
this._processArguments();
|
|
2146
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
2147
|
+
} else if (operands.length) {
|
|
2148
|
+
if (this._findCommand("*")) return this._dispatchSubcommand("*", operands, unknown);
|
|
2149
|
+
if (this.listenerCount("command:*")) this.emit("command:*", operands, unknown);
|
|
2150
|
+
else if (this.commands.length) this.unknownCommand();
|
|
2151
|
+
else {
|
|
2152
|
+
checkForUnknownOptions();
|
|
2153
|
+
this._processArguments();
|
|
2154
|
+
}
|
|
2155
|
+
} else if (this.commands.length) {
|
|
2156
|
+
checkForUnknownOptions();
|
|
2157
|
+
this.help({ error: true });
|
|
2158
|
+
} else {
|
|
2159
|
+
checkForUnknownOptions();
|
|
2160
|
+
this._processArguments();
|
|
2161
|
+
}
|
|
2162
|
+
}
|
|
2163
|
+
/**
|
|
2164
|
+
* Find matching command.
|
|
2165
|
+
*
|
|
2166
|
+
* @private
|
|
2167
|
+
* @return {Command | undefined}
|
|
2168
|
+
*/
|
|
2169
|
+
_findCommand(name) {
|
|
2170
|
+
if (!name) return void 0;
|
|
2171
|
+
return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
|
|
2172
|
+
}
|
|
2173
|
+
/**
|
|
2174
|
+
* Return an option matching `arg` if any.
|
|
2175
|
+
*
|
|
2176
|
+
* @param {string} arg
|
|
2177
|
+
* @return {Option}
|
|
2178
|
+
* @package
|
|
2179
|
+
*/
|
|
2180
|
+
_findOption(arg) {
|
|
2181
|
+
return this.options.find((option) => option.is(arg));
|
|
2182
|
+
}
|
|
2183
|
+
/**
|
|
2184
|
+
* Display an error message if a mandatory option does not have a value.
|
|
2185
|
+
* Called after checking for help flags in leaf subcommand.
|
|
2186
|
+
*
|
|
2187
|
+
* @private
|
|
2188
|
+
*/
|
|
2189
|
+
_checkForMissingMandatoryOptions() {
|
|
2190
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
2191
|
+
cmd.options.forEach((anOption) => {
|
|
2192
|
+
if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) cmd.missingMandatoryOptionValue(anOption);
|
|
2193
|
+
});
|
|
2194
|
+
});
|
|
2195
|
+
}
|
|
2196
|
+
/**
|
|
2197
|
+
* Display an error message if conflicting options are used together in this.
|
|
2198
|
+
*
|
|
2199
|
+
* @private
|
|
2200
|
+
*/
|
|
2201
|
+
_checkForConflictingLocalOptions() {
|
|
2202
|
+
const definedNonDefaultOptions = this.options.filter((option) => {
|
|
2203
|
+
const optionKey = option.attributeName();
|
|
2204
|
+
if (this.getOptionValue(optionKey) === void 0) return false;
|
|
2205
|
+
return this.getOptionValueSource(optionKey) !== "default";
|
|
2206
|
+
});
|
|
2207
|
+
definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0).forEach((option) => {
|
|
2208
|
+
const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
|
|
2209
|
+
if (conflictingAndDefined) this._conflictingOption(option, conflictingAndDefined);
|
|
2210
|
+
});
|
|
2211
|
+
}
|
|
2212
|
+
/**
|
|
2213
|
+
* Display an error message if conflicting options are used together.
|
|
2214
|
+
* Called after checking for help flags in leaf subcommand.
|
|
2215
|
+
*
|
|
2216
|
+
* @private
|
|
2217
|
+
*/
|
|
2218
|
+
_checkForConflictingOptions() {
|
|
2219
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
2220
|
+
cmd._checkForConflictingLocalOptions();
|
|
2221
|
+
});
|
|
2222
|
+
}
|
|
2223
|
+
/**
|
|
2224
|
+
* Parse options from `argv` removing known options,
|
|
2225
|
+
* and return argv split into operands and unknown arguments.
|
|
2226
|
+
*
|
|
2227
|
+
* Side effects: modifies command by storing options. Does not reset state if called again.
|
|
2228
|
+
*
|
|
2229
|
+
* Examples:
|
|
2230
|
+
*
|
|
2231
|
+
* argv => operands, unknown
|
|
2232
|
+
* --known kkk op => [op], []
|
|
2233
|
+
* op --known kkk => [op], []
|
|
2234
|
+
* sub --unknown uuu op => [sub], [--unknown uuu op]
|
|
2235
|
+
* sub -- --unknown uuu op => [sub --unknown uuu op], []
|
|
2236
|
+
*
|
|
2237
|
+
* @param {string[]} args
|
|
2238
|
+
* @return {{operands: string[], unknown: string[]}}
|
|
2239
|
+
*/
|
|
2240
|
+
parseOptions(args) {
|
|
2241
|
+
const operands = [];
|
|
2242
|
+
const unknown = [];
|
|
2243
|
+
let dest = operands;
|
|
2244
|
+
function maybeOption(arg) {
|
|
2245
|
+
return arg.length > 1 && arg[0] === "-";
|
|
2246
|
+
}
|
|
2247
|
+
const negativeNumberArg = (arg) => {
|
|
2248
|
+
if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
|
|
2249
|
+
return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short)));
|
|
2250
|
+
};
|
|
2251
|
+
let activeVariadicOption = null;
|
|
2252
|
+
let activeGroup = null;
|
|
2253
|
+
let i = 0;
|
|
2254
|
+
while (i < args.length || activeGroup) {
|
|
2255
|
+
const arg = activeGroup ?? args[i++];
|
|
2256
|
+
activeGroup = null;
|
|
2257
|
+
if (arg === "--") {
|
|
2258
|
+
if (dest === unknown) dest.push(arg);
|
|
2259
|
+
dest.push(...args.slice(i));
|
|
2260
|
+
break;
|
|
2261
|
+
}
|
|
2262
|
+
if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
|
|
2263
|
+
this.emit(`option:${activeVariadicOption.name()}`, arg);
|
|
2264
|
+
continue;
|
|
2265
|
+
}
|
|
2266
|
+
activeVariadicOption = null;
|
|
2267
|
+
if (maybeOption(arg)) {
|
|
2268
|
+
const option = this._findOption(arg);
|
|
2269
|
+
if (option) {
|
|
2270
|
+
if (option.required) {
|
|
2271
|
+
const value = args[i++];
|
|
2272
|
+
if (value === void 0) this.optionMissingArgument(option);
|
|
2273
|
+
this.emit(`option:${option.name()}`, value);
|
|
2274
|
+
} else if (option.optional) {
|
|
2275
|
+
let value = null;
|
|
2276
|
+
if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) value = args[i++];
|
|
2277
|
+
this.emit(`option:${option.name()}`, value);
|
|
2278
|
+
} else this.emit(`option:${option.name()}`);
|
|
2279
|
+
activeVariadicOption = option.variadic ? option : null;
|
|
2280
|
+
continue;
|
|
2281
|
+
}
|
|
2282
|
+
}
|
|
2283
|
+
if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
|
|
2284
|
+
const option = this._findOption(`-${arg[1]}`);
|
|
2285
|
+
if (option) {
|
|
2286
|
+
if (option.required || option.optional && this._combineFlagAndOptionalValue) this.emit(`option:${option.name()}`, arg.slice(2));
|
|
2287
|
+
else {
|
|
2288
|
+
this.emit(`option:${option.name()}`);
|
|
2289
|
+
activeGroup = `-${arg.slice(2)}`;
|
|
2290
|
+
}
|
|
2291
|
+
continue;
|
|
2292
|
+
}
|
|
2293
|
+
}
|
|
2294
|
+
if (/^--[^=]+=/.test(arg)) {
|
|
2295
|
+
const index = arg.indexOf("=");
|
|
2296
|
+
const option = this._findOption(arg.slice(0, index));
|
|
2297
|
+
if (option && (option.required || option.optional)) {
|
|
2298
|
+
this.emit(`option:${option.name()}`, arg.slice(index + 1));
|
|
2299
|
+
continue;
|
|
2300
|
+
}
|
|
2301
|
+
}
|
|
2302
|
+
if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) dest = unknown;
|
|
2303
|
+
if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
|
|
2304
|
+
if (this._findCommand(arg)) {
|
|
2305
|
+
operands.push(arg);
|
|
2306
|
+
unknown.push(...args.slice(i));
|
|
2307
|
+
break;
|
|
2308
|
+
} else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
|
|
2309
|
+
operands.push(arg, ...args.slice(i));
|
|
2310
|
+
break;
|
|
2311
|
+
} else if (this._defaultCommandName) {
|
|
2312
|
+
unknown.push(arg, ...args.slice(i));
|
|
2313
|
+
break;
|
|
2314
|
+
}
|
|
2315
|
+
}
|
|
2316
|
+
if (this._passThroughOptions) {
|
|
2317
|
+
dest.push(arg, ...args.slice(i));
|
|
2318
|
+
break;
|
|
2319
|
+
}
|
|
2320
|
+
dest.push(arg);
|
|
2321
|
+
}
|
|
2322
|
+
return {
|
|
2323
|
+
operands,
|
|
2324
|
+
unknown
|
|
2325
|
+
};
|
|
2326
|
+
}
|
|
2327
|
+
/**
|
|
2328
|
+
* Return an object containing local option values as key-value pairs.
|
|
2329
|
+
*
|
|
2330
|
+
* @return {object}
|
|
2331
|
+
*/
|
|
2332
|
+
opts() {
|
|
2333
|
+
if (this._storeOptionsAsProperties) {
|
|
2334
|
+
const result = {};
|
|
2335
|
+
const len = this.options.length;
|
|
2336
|
+
for (let i = 0; i < len; i++) {
|
|
2337
|
+
const key = this.options[i].attributeName();
|
|
2338
|
+
result[key] = key === this._versionOptionName ? this._version : this[key];
|
|
2339
|
+
}
|
|
2340
|
+
return result;
|
|
2341
|
+
}
|
|
2342
|
+
return this._optionValues;
|
|
2343
|
+
}
|
|
2344
|
+
/**
|
|
2345
|
+
* Return an object containing merged local and global option values as key-value pairs.
|
|
2346
|
+
*
|
|
2347
|
+
* @return {object}
|
|
2348
|
+
*/
|
|
2349
|
+
optsWithGlobals() {
|
|
2350
|
+
return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
|
|
2351
|
+
}
|
|
2352
|
+
/**
|
|
2353
|
+
* Display error message and exit (or call exitOverride).
|
|
2354
|
+
*
|
|
2355
|
+
* @param {string} message
|
|
2356
|
+
* @param {object} [errorOptions]
|
|
2357
|
+
* @param {string} [errorOptions.code] - an id string representing the error
|
|
2358
|
+
* @param {number} [errorOptions.exitCode] - used with process.exit
|
|
2359
|
+
*/
|
|
2360
|
+
error(message, errorOptions) {
|
|
2361
|
+
this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);
|
|
2362
|
+
if (typeof this._showHelpAfterError === "string") this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);
|
|
2363
|
+
else if (this._showHelpAfterError) {
|
|
2364
|
+
this._outputConfiguration.writeErr("\n");
|
|
2365
|
+
this.outputHelp({ error: true });
|
|
2366
|
+
}
|
|
2367
|
+
const config = errorOptions || {};
|
|
2368
|
+
const exitCode = config.exitCode || 1;
|
|
2369
|
+
const code = config.code || "commander.error";
|
|
2370
|
+
this._exit(exitCode, code, message);
|
|
2371
|
+
}
|
|
2372
|
+
/**
|
|
2373
|
+
* Apply any option related environment variables, if option does
|
|
2374
|
+
* not have a value from cli or client code.
|
|
2375
|
+
*
|
|
2376
|
+
* @private
|
|
2377
|
+
*/
|
|
2378
|
+
_parseOptionsEnv() {
|
|
2379
|
+
this.options.forEach((option) => {
|
|
2380
|
+
if (option.envVar && option.envVar in process$1.env) {
|
|
2381
|
+
const optionKey = option.attributeName();
|
|
2382
|
+
if (this.getOptionValue(optionKey) === void 0 || [
|
|
2383
|
+
"default",
|
|
2384
|
+
"config",
|
|
2385
|
+
"env"
|
|
2386
|
+
].includes(this.getOptionValueSource(optionKey))) {
|
|
2387
|
+
if (option.required || option.optional) this.emit(`optionEnv:${option.name()}`, process$1.env[option.envVar]);
|
|
2388
|
+
else this.emit(`optionEnv:${option.name()}`);
|
|
2389
|
+
}
|
|
2390
|
+
}
|
|
2391
|
+
});
|
|
2392
|
+
}
|
|
2393
|
+
/**
|
|
2394
|
+
* Apply any implied option values, if option is undefined or default value.
|
|
2395
|
+
*
|
|
2396
|
+
* @private
|
|
2397
|
+
*/
|
|
2398
|
+
_parseOptionsImplied() {
|
|
2399
|
+
const dualHelper = new DualOptions(this.options);
|
|
2400
|
+
const hasCustomOptionValue = (optionKey) => {
|
|
2401
|
+
return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
|
|
2402
|
+
};
|
|
2403
|
+
this.options.filter((option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
|
|
2404
|
+
Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
|
|
2405
|
+
this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
|
|
2406
|
+
});
|
|
2407
|
+
});
|
|
2408
|
+
}
|
|
2409
|
+
/**
|
|
2410
|
+
* Argument `name` is missing.
|
|
2411
|
+
*
|
|
2412
|
+
* @param {string} name
|
|
2413
|
+
* @private
|
|
2414
|
+
*/
|
|
2415
|
+
missingArgument(name) {
|
|
2416
|
+
const message = `error: missing required argument '${name}'`;
|
|
2417
|
+
this.error(message, { code: "commander.missingArgument" });
|
|
2418
|
+
}
|
|
2419
|
+
/**
|
|
2420
|
+
* `Option` is missing an argument.
|
|
2421
|
+
*
|
|
2422
|
+
* @param {Option} option
|
|
2423
|
+
* @private
|
|
2424
|
+
*/
|
|
2425
|
+
optionMissingArgument(option) {
|
|
2426
|
+
const message = `error: option '${option.flags}' argument missing`;
|
|
2427
|
+
this.error(message, { code: "commander.optionMissingArgument" });
|
|
2428
|
+
}
|
|
2429
|
+
/**
|
|
2430
|
+
* `Option` does not have a value, and is a mandatory option.
|
|
2431
|
+
*
|
|
2432
|
+
* @param {Option} option
|
|
2433
|
+
* @private
|
|
2434
|
+
*/
|
|
2435
|
+
missingMandatoryOptionValue(option) {
|
|
2436
|
+
const message = `error: required option '${option.flags}' not specified`;
|
|
2437
|
+
this.error(message, { code: "commander.missingMandatoryOptionValue" });
|
|
2438
|
+
}
|
|
2439
|
+
/**
|
|
2440
|
+
* `Option` conflicts with another option.
|
|
2441
|
+
*
|
|
2442
|
+
* @param {Option} option
|
|
2443
|
+
* @param {Option} conflictingOption
|
|
2444
|
+
* @private
|
|
2445
|
+
*/
|
|
2446
|
+
_conflictingOption(option, conflictingOption) {
|
|
2447
|
+
const findBestOptionFromValue = (option) => {
|
|
2448
|
+
const optionKey = option.attributeName();
|
|
2449
|
+
const optionValue = this.getOptionValue(optionKey);
|
|
2450
|
+
const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
|
|
2451
|
+
const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
|
|
2452
|
+
if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) return negativeOption;
|
|
2453
|
+
return positiveOption || option;
|
|
2454
|
+
};
|
|
2455
|
+
const getErrorMessage = (option) => {
|
|
2456
|
+
const bestOption = findBestOptionFromValue(option);
|
|
2457
|
+
const optionKey = bestOption.attributeName();
|
|
2458
|
+
if (this.getOptionValueSource(optionKey) === "env") return `environment variable '${bestOption.envVar}'`;
|
|
2459
|
+
return `option '${bestOption.flags}'`;
|
|
2460
|
+
};
|
|
2461
|
+
const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
|
|
2462
|
+
this.error(message, { code: "commander.conflictingOption" });
|
|
2463
|
+
}
|
|
2464
|
+
/**
|
|
2465
|
+
* Unknown option `flag`.
|
|
2466
|
+
*
|
|
2467
|
+
* @param {string} flag
|
|
2468
|
+
* @private
|
|
2469
|
+
*/
|
|
2470
|
+
unknownOption(flag) {
|
|
2471
|
+
if (this._allowUnknownOption) return;
|
|
2472
|
+
let suggestion = "";
|
|
2473
|
+
if (flag.startsWith("--") && this._showSuggestionAfterError) {
|
|
2474
|
+
let candidateFlags = [];
|
|
2475
|
+
let command = this;
|
|
2476
|
+
do {
|
|
2477
|
+
const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
|
|
2478
|
+
candidateFlags = candidateFlags.concat(moreFlags);
|
|
2479
|
+
command = command.parent;
|
|
2480
|
+
} while (command && !command._enablePositionalOptions);
|
|
2481
|
+
suggestion = suggestSimilar(flag, candidateFlags);
|
|
2482
|
+
}
|
|
2483
|
+
const message = `error: unknown option '${flag}'${suggestion}`;
|
|
2484
|
+
this.error(message, { code: "commander.unknownOption" });
|
|
2485
|
+
}
|
|
2486
|
+
/**
|
|
2487
|
+
* Excess arguments, more than expected.
|
|
2488
|
+
*
|
|
2489
|
+
* @param {string[]} receivedArgs
|
|
2490
|
+
* @private
|
|
2491
|
+
*/
|
|
2492
|
+
_excessArguments(receivedArgs) {
|
|
2493
|
+
if (this._allowExcessArguments) return;
|
|
2494
|
+
const expected = this.registeredArguments.length;
|
|
2495
|
+
const s = expected === 1 ? "" : "s";
|
|
2496
|
+
const received = receivedArgs.length;
|
|
2497
|
+
const message = `error: too many arguments${this.parent ? ` for '${this.name()}'` : ""}. Expected ${expected} argument${s} but got ${received}: ${receivedArgs.join(", ")}.`;
|
|
2498
|
+
this.error(message, { code: "commander.excessArguments" });
|
|
2499
|
+
}
|
|
2500
|
+
/**
|
|
2501
|
+
* Unknown command.
|
|
2502
|
+
*
|
|
2503
|
+
* @private
|
|
2504
|
+
*/
|
|
2505
|
+
unknownCommand() {
|
|
2506
|
+
const unknownName = this.args[0];
|
|
2507
|
+
let suggestion = "";
|
|
2508
|
+
if (this._showSuggestionAfterError) {
|
|
2509
|
+
const candidateNames = [];
|
|
2510
|
+
this.createHelp().visibleCommands(this).forEach((command) => {
|
|
2511
|
+
candidateNames.push(command.name());
|
|
2512
|
+
if (command.alias()) candidateNames.push(command.alias());
|
|
2513
|
+
});
|
|
2514
|
+
suggestion = suggestSimilar(unknownName, candidateNames);
|
|
2515
|
+
}
|
|
2516
|
+
const message = `error: unknown command '${unknownName}'${suggestion}`;
|
|
2517
|
+
this.error(message, { code: "commander.unknownCommand" });
|
|
2518
|
+
}
|
|
2519
|
+
/**
|
|
2520
|
+
* Get or set the program version.
|
|
2521
|
+
*
|
|
2522
|
+
* This method auto-registers the "-V, --version" option which will print the version number.
|
|
2523
|
+
*
|
|
2524
|
+
* You can optionally supply the flags and description to override the defaults.
|
|
2525
|
+
*
|
|
2526
|
+
* @param {string} [str]
|
|
2527
|
+
* @param {string} [flags]
|
|
2528
|
+
* @param {string} [description]
|
|
2529
|
+
* @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
|
|
2530
|
+
*/
|
|
2531
|
+
version(str, flags, description) {
|
|
2532
|
+
if (str === void 0) return this._version;
|
|
2533
|
+
this._version = str;
|
|
2534
|
+
flags = flags || "-V, --version";
|
|
2535
|
+
description = description || "output the version number";
|
|
2536
|
+
const versionOption = this.createOption(flags, description);
|
|
2537
|
+
this._versionOptionName = versionOption.attributeName();
|
|
2538
|
+
this._registerOption(versionOption);
|
|
2539
|
+
this.on("option:" + versionOption.name(), () => {
|
|
2540
|
+
this._outputConfiguration.writeOut(`${str}\n`);
|
|
2541
|
+
this._exit(0, "commander.version", str);
|
|
2542
|
+
});
|
|
2543
|
+
return this;
|
|
2544
|
+
}
|
|
2545
|
+
/**
|
|
2546
|
+
* Set the description.
|
|
2547
|
+
*
|
|
2548
|
+
* @param {string} [str]
|
|
2549
|
+
* @param {object} [argsDescription]
|
|
2550
|
+
* @return {(string|Command)}
|
|
2551
|
+
*/
|
|
2552
|
+
description(str, argsDescription) {
|
|
2553
|
+
if (str === void 0 && argsDescription === void 0) return this._description;
|
|
2554
|
+
this._description = str;
|
|
2555
|
+
if (argsDescription) this._argsDescription = argsDescription;
|
|
2556
|
+
return this;
|
|
2557
|
+
}
|
|
2558
|
+
/**
|
|
2559
|
+
* Set the summary. Used when listed as subcommand of parent.
|
|
2560
|
+
*
|
|
2561
|
+
* @param {string} [str]
|
|
2562
|
+
* @return {(string|Command)}
|
|
2563
|
+
*/
|
|
2564
|
+
summary(str) {
|
|
2565
|
+
if (str === void 0) return this._summary;
|
|
2566
|
+
this._summary = str;
|
|
2567
|
+
return this;
|
|
2568
|
+
}
|
|
2569
|
+
/**
|
|
2570
|
+
* Set an alias for the command.
|
|
2571
|
+
*
|
|
2572
|
+
* You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
|
|
2573
|
+
*
|
|
2574
|
+
* @param {string} [alias]
|
|
2575
|
+
* @return {(string|Command)}
|
|
2576
|
+
*/
|
|
2577
|
+
alias(alias) {
|
|
2578
|
+
if (alias === void 0) return this._aliases[0];
|
|
2579
|
+
/** @type {Command} */
|
|
2580
|
+
let command = this;
|
|
2581
|
+
if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) command = this.commands[this.commands.length - 1];
|
|
2582
|
+
if (alias === command._name) throw new Error("Command alias can't be the same as its name");
|
|
2583
|
+
const matchingCommand = this.parent?._findCommand(alias);
|
|
2584
|
+
if (matchingCommand) {
|
|
2585
|
+
const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
|
|
2586
|
+
throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
|
|
2587
|
+
}
|
|
2588
|
+
command._aliases.push(alias);
|
|
2589
|
+
return this;
|
|
2590
|
+
}
|
|
2591
|
+
/**
|
|
2592
|
+
* Set aliases for the command.
|
|
2593
|
+
*
|
|
2594
|
+
* Only the first alias is shown in the auto-generated help.
|
|
2595
|
+
*
|
|
2596
|
+
* @param {string[]} [aliases]
|
|
2597
|
+
* @return {(string[]|Command)}
|
|
2598
|
+
*/
|
|
2599
|
+
aliases(aliases) {
|
|
2600
|
+
if (aliases === void 0) return this._aliases;
|
|
2601
|
+
aliases.forEach((alias) => this.alias(alias));
|
|
2602
|
+
return this;
|
|
2603
|
+
}
|
|
2604
|
+
/**
|
|
2605
|
+
* Set / get the command usage `str`.
|
|
2606
|
+
*
|
|
2607
|
+
* @param {string} [str]
|
|
2608
|
+
* @return {(string|Command)}
|
|
2609
|
+
*/
|
|
2610
|
+
usage(str) {
|
|
2611
|
+
if (str === void 0) {
|
|
2612
|
+
if (this._usage) return this._usage;
|
|
2613
|
+
const args = this.registeredArguments.map((arg) => {
|
|
2614
|
+
return humanReadableArgName(arg);
|
|
2615
|
+
});
|
|
2616
|
+
return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
|
|
2617
|
+
}
|
|
2618
|
+
this._usage = str;
|
|
2619
|
+
return this;
|
|
2620
|
+
}
|
|
2621
|
+
/**
|
|
2622
|
+
* Get or set the name of the command.
|
|
2623
|
+
*
|
|
2624
|
+
* @param {string} [str]
|
|
2625
|
+
* @return {(string|Command)}
|
|
2626
|
+
*/
|
|
2627
|
+
name(str) {
|
|
2628
|
+
if (str === void 0) return this._name;
|
|
2629
|
+
this._name = str;
|
|
2630
|
+
return this;
|
|
2631
|
+
}
|
|
2632
|
+
/**
|
|
2633
|
+
* Set/get the help group heading for this subcommand in parent command's help.
|
|
2634
|
+
*
|
|
2635
|
+
* @param {string} [heading]
|
|
2636
|
+
* @return {Command | string}
|
|
2637
|
+
*/
|
|
2638
|
+
helpGroup(heading) {
|
|
2639
|
+
if (heading === void 0) return this._helpGroupHeading ?? "";
|
|
2640
|
+
this._helpGroupHeading = heading;
|
|
2641
|
+
return this;
|
|
2642
|
+
}
|
|
2643
|
+
/**
|
|
2644
|
+
* Set/get the default help group heading for subcommands added to this command.
|
|
2645
|
+
* (This does not override a group set directly on the subcommand using .helpGroup().)
|
|
2646
|
+
*
|
|
2647
|
+
* @example
|
|
2648
|
+
* program.commandsGroup('Development Commands:);
|
|
2649
|
+
* program.command('watch')...
|
|
2650
|
+
* program.command('lint')...
|
|
2651
|
+
* ...
|
|
2652
|
+
*
|
|
2653
|
+
* @param {string} [heading]
|
|
2654
|
+
* @returns {Command | string}
|
|
2655
|
+
*/
|
|
2656
|
+
commandsGroup(heading) {
|
|
2657
|
+
if (heading === void 0) return this._defaultCommandGroup ?? "";
|
|
2658
|
+
this._defaultCommandGroup = heading;
|
|
2659
|
+
return this;
|
|
2660
|
+
}
|
|
2661
|
+
/**
|
|
2662
|
+
* Set/get the default help group heading for options added to this command.
|
|
2663
|
+
* (This does not override a group set directly on the option using .helpGroup().)
|
|
2664
|
+
*
|
|
2665
|
+
* @example
|
|
2666
|
+
* program
|
|
2667
|
+
* .optionsGroup('Development Options:')
|
|
2668
|
+
* .option('-d, --debug', 'output extra debugging')
|
|
2669
|
+
* .option('-p, --profile', 'output profiling information')
|
|
2670
|
+
*
|
|
2671
|
+
* @param {string} [heading]
|
|
2672
|
+
* @returns {Command | string}
|
|
2673
|
+
*/
|
|
2674
|
+
optionsGroup(heading) {
|
|
2675
|
+
if (heading === void 0) return this._defaultOptionGroup ?? "";
|
|
2676
|
+
this._defaultOptionGroup = heading;
|
|
2677
|
+
return this;
|
|
2678
|
+
}
|
|
2679
|
+
/**
|
|
2680
|
+
* @param {Option} option
|
|
2681
|
+
* @private
|
|
2682
|
+
*/
|
|
2683
|
+
_initOptionGroup(option) {
|
|
2684
|
+
if (this._defaultOptionGroup && !option.helpGroupHeading) option.helpGroup(this._defaultOptionGroup);
|
|
2685
|
+
}
|
|
2686
|
+
/**
|
|
2687
|
+
* @param {Command} cmd
|
|
2688
|
+
* @private
|
|
2689
|
+
*/
|
|
2690
|
+
_initCommandGroup(cmd) {
|
|
2691
|
+
if (this._defaultCommandGroup && !cmd.helpGroup()) cmd.helpGroup(this._defaultCommandGroup);
|
|
2692
|
+
}
|
|
2693
|
+
/**
|
|
2694
|
+
* Set the name of the command from script filename, such as process.argv[1],
|
|
2695
|
+
* or import.meta.filename.
|
|
2696
|
+
*
|
|
2697
|
+
* (Used internally and public although not documented in README.)
|
|
2698
|
+
*
|
|
2699
|
+
* @example
|
|
2700
|
+
* program.nameFromFilename(import.meta.filename);
|
|
2701
|
+
*
|
|
2702
|
+
* @param {string} filename
|
|
2703
|
+
* @return {Command}
|
|
2704
|
+
*/
|
|
2705
|
+
nameFromFilename(filename) {
|
|
2706
|
+
this._name = path.basename(filename, path.extname(filename));
|
|
2707
|
+
return this;
|
|
2708
|
+
}
|
|
2709
|
+
/**
|
|
2710
|
+
* Get or set the directory for searching for executable subcommands of this command.
|
|
2711
|
+
*
|
|
2712
|
+
* @example
|
|
2713
|
+
* program.executableDir(import.meta.dirname);
|
|
2714
|
+
* // or
|
|
2715
|
+
* program.executableDir('subcommands');
|
|
2716
|
+
*
|
|
2717
|
+
* @param {string} [path]
|
|
2718
|
+
* @return {(string|null|Command)}
|
|
2719
|
+
*/
|
|
2720
|
+
executableDir(path) {
|
|
2721
|
+
if (path === void 0) return this._executableDir;
|
|
2722
|
+
this._executableDir = path;
|
|
2723
|
+
return this;
|
|
2724
|
+
}
|
|
2725
|
+
/**
|
|
2726
|
+
* Return program help documentation.
|
|
2727
|
+
*
|
|
2728
|
+
* @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
|
|
2729
|
+
* @return {string}
|
|
2730
|
+
*/
|
|
2731
|
+
helpInformation(contextOptions) {
|
|
2732
|
+
const helper = this.createHelp();
|
|
2733
|
+
const context = this._getOutputContext(contextOptions);
|
|
2734
|
+
helper.prepareContext({
|
|
2735
|
+
error: context.error,
|
|
2736
|
+
helpWidth: context.helpWidth,
|
|
2737
|
+
outputHasColors: context.hasColors
|
|
2738
|
+
});
|
|
2739
|
+
const text = helper.formatHelp(this, helper);
|
|
2740
|
+
if (context.hasColors) return text;
|
|
2741
|
+
return this._outputConfiguration.stripColor(text);
|
|
2742
|
+
}
|
|
2743
|
+
/**
|
|
2744
|
+
* @typedef HelpContext
|
|
2745
|
+
* @type {object}
|
|
2746
|
+
* @property {boolean} error
|
|
2747
|
+
* @property {number} helpWidth
|
|
2748
|
+
* @property {boolean} hasColors
|
|
2749
|
+
* @property {function} write - includes stripColor if needed
|
|
2750
|
+
*
|
|
2751
|
+
* @returns {HelpContext}
|
|
2752
|
+
* @private
|
|
2753
|
+
*/
|
|
2754
|
+
_getOutputContext(contextOptions) {
|
|
2755
|
+
contextOptions = contextOptions || {};
|
|
2756
|
+
const error = !!contextOptions.error;
|
|
2757
|
+
let baseWrite;
|
|
2758
|
+
let hasColors;
|
|
2759
|
+
let helpWidth;
|
|
2760
|
+
if (error) {
|
|
2761
|
+
baseWrite = (str) => this._outputConfiguration.writeErr(str);
|
|
2762
|
+
hasColors = this._outputConfiguration.getErrHasColors();
|
|
2763
|
+
helpWidth = this._outputConfiguration.getErrHelpWidth();
|
|
2764
|
+
} else {
|
|
2765
|
+
baseWrite = (str) => this._outputConfiguration.writeOut(str);
|
|
2766
|
+
hasColors = this._outputConfiguration.getOutHasColors();
|
|
2767
|
+
helpWidth = this._outputConfiguration.getOutHelpWidth();
|
|
2768
|
+
}
|
|
2769
|
+
const write = (str) => {
|
|
2770
|
+
if (!hasColors) str = this._outputConfiguration.stripColor(str);
|
|
2771
|
+
return baseWrite(str);
|
|
2772
|
+
};
|
|
2773
|
+
return {
|
|
2774
|
+
error,
|
|
2775
|
+
write,
|
|
2776
|
+
hasColors,
|
|
2777
|
+
helpWidth
|
|
2778
|
+
};
|
|
2779
|
+
}
|
|
2780
|
+
/**
|
|
2781
|
+
* Output help information for this command.
|
|
2782
|
+
*
|
|
2783
|
+
* Outputs built-in help, and custom text added using `.addHelpText()`.
|
|
2784
|
+
*
|
|
2785
|
+
* @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
|
|
2786
|
+
*/
|
|
2787
|
+
outputHelp(contextOptions) {
|
|
2788
|
+
let deprecatedCallback;
|
|
2789
|
+
if (typeof contextOptions === "function") {
|
|
2790
|
+
deprecatedCallback = contextOptions;
|
|
2791
|
+
contextOptions = void 0;
|
|
2792
|
+
}
|
|
2793
|
+
const outputContext = this._getOutputContext(contextOptions);
|
|
2794
|
+
/** @type {HelpTextEventContext} */
|
|
2795
|
+
const eventContext = {
|
|
2796
|
+
error: outputContext.error,
|
|
2797
|
+
write: outputContext.write,
|
|
2798
|
+
command: this
|
|
2799
|
+
};
|
|
2800
|
+
this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
|
|
2801
|
+
this.emit("beforeHelp", eventContext);
|
|
2802
|
+
let helpInformation = this.helpInformation({ error: outputContext.error });
|
|
2803
|
+
if (deprecatedCallback) {
|
|
2804
|
+
helpInformation = deprecatedCallback(helpInformation);
|
|
2805
|
+
if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) throw new Error("outputHelp callback must return a string or a Buffer");
|
|
2806
|
+
}
|
|
2807
|
+
outputContext.write(helpInformation);
|
|
2808
|
+
if (this._getHelpOption()?.long) this.emit(this._getHelpOption().long);
|
|
2809
|
+
this.emit("afterHelp", eventContext);
|
|
2810
|
+
this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
|
|
2811
|
+
}
|
|
2812
|
+
/**
|
|
2813
|
+
* You can pass in flags and a description to customise the built-in help option.
|
|
2814
|
+
* Pass in false to disable the built-in help option.
|
|
2815
|
+
*
|
|
2816
|
+
* @example
|
|
2817
|
+
* program.helpOption('-?, --help' 'show help'); // customise
|
|
2818
|
+
* program.helpOption(false); // disable
|
|
2819
|
+
*
|
|
2820
|
+
* @param {(string | boolean)} flags
|
|
2821
|
+
* @param {string} [description]
|
|
2822
|
+
* @return {Command} `this` command for chaining
|
|
2823
|
+
*/
|
|
2824
|
+
helpOption(flags, description) {
|
|
2825
|
+
if (typeof flags === "boolean") {
|
|
2826
|
+
if (flags) {
|
|
2827
|
+
if (this._helpOption === null) this._helpOption = void 0;
|
|
2828
|
+
if (this._defaultOptionGroup) this._initOptionGroup(this._getHelpOption());
|
|
2829
|
+
} else this._helpOption = null;
|
|
2830
|
+
return this;
|
|
2831
|
+
}
|
|
2832
|
+
this._helpOption = this.createOption(flags ?? "-h, --help", description ?? "display help for command");
|
|
2833
|
+
if (flags || description) this._initOptionGroup(this._helpOption);
|
|
2834
|
+
return this;
|
|
2835
|
+
}
|
|
2836
|
+
/**
|
|
2837
|
+
* Lazy create help option.
|
|
2838
|
+
* Returns null if has been disabled with .helpOption(false).
|
|
2839
|
+
*
|
|
2840
|
+
* @returns {(Option | null)} the help option
|
|
2841
|
+
* @package
|
|
2842
|
+
*/
|
|
2843
|
+
_getHelpOption() {
|
|
2844
|
+
if (this._helpOption === void 0) this.helpOption(void 0, void 0);
|
|
2845
|
+
return this._helpOption;
|
|
2846
|
+
}
|
|
2847
|
+
/**
|
|
2848
|
+
* Supply your own option to use for the built-in help option.
|
|
2849
|
+
* This is an alternative to using helpOption() to customise the flags and description etc.
|
|
2850
|
+
*
|
|
2851
|
+
* @param {Option} option
|
|
2852
|
+
* @return {Command} `this` command for chaining
|
|
2853
|
+
*/
|
|
2854
|
+
addHelpOption(option) {
|
|
2855
|
+
this._helpOption = option;
|
|
2856
|
+
this._initOptionGroup(option);
|
|
2857
|
+
return this;
|
|
2858
|
+
}
|
|
2859
|
+
/**
|
|
2860
|
+
* Output help information and exit.
|
|
2861
|
+
*
|
|
2862
|
+
* Outputs built-in help, and custom text added using `.addHelpText()`.
|
|
2863
|
+
*
|
|
2864
|
+
* @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
|
|
2865
|
+
*/
|
|
2866
|
+
help(contextOptions) {
|
|
2867
|
+
this.outputHelp(contextOptions);
|
|
2868
|
+
let exitCode = Number(process$1.exitCode ?? 0);
|
|
2869
|
+
if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) exitCode = 1;
|
|
2870
|
+
this._exit(exitCode, "commander.help", "(outputHelp)");
|
|
2871
|
+
}
|
|
2872
|
+
/**
|
|
2873
|
+
* // Do a little typing to coordinate emit and listener for the help text events.
|
|
2874
|
+
* @typedef HelpTextEventContext
|
|
2875
|
+
* @type {object}
|
|
2876
|
+
* @property {boolean} error
|
|
2877
|
+
* @property {Command} command
|
|
2878
|
+
* @property {function} write
|
|
2879
|
+
*/
|
|
2880
|
+
/**
|
|
2881
|
+
* Add additional text to be displayed with the built-in help.
|
|
2882
|
+
*
|
|
2883
|
+
* Position is 'before' or 'after' to affect just this command,
|
|
2884
|
+
* and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
|
|
2885
|
+
*
|
|
2886
|
+
* @param {string} position - before or after built-in help
|
|
2887
|
+
* @param {(string | Function)} text - string to add, or a function returning a string
|
|
2888
|
+
* @return {Command} `this` command for chaining
|
|
2889
|
+
*/
|
|
2890
|
+
addHelpText(position, text) {
|
|
2891
|
+
const allowedValues = [
|
|
2892
|
+
"beforeAll",
|
|
2893
|
+
"before",
|
|
2894
|
+
"after",
|
|
2895
|
+
"afterAll"
|
|
2896
|
+
];
|
|
2897
|
+
if (!allowedValues.includes(position)) throw new Error(`Unexpected value for position to addHelpText.
|
|
2898
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
2899
|
+
const helpEvent = `${position}Help`;
|
|
2900
|
+
this.on(helpEvent, (context) => {
|
|
2901
|
+
let helpStr;
|
|
2902
|
+
if (typeof text === "function") helpStr = text({
|
|
2903
|
+
error: context.error,
|
|
2904
|
+
command: context.command
|
|
2905
|
+
});
|
|
2906
|
+
else helpStr = text;
|
|
2907
|
+
if (helpStr) context.write(`${helpStr}\n`);
|
|
2908
|
+
});
|
|
2909
|
+
return this;
|
|
2910
|
+
}
|
|
2911
|
+
/**
|
|
2912
|
+
* Output help information if help flags specified
|
|
2913
|
+
*
|
|
2914
|
+
* @param {Array} args - array of options to search for help flags
|
|
2915
|
+
* @private
|
|
2916
|
+
*/
|
|
2917
|
+
_outputHelpIfRequested(args) {
|
|
2918
|
+
const helpOption = this._getHelpOption();
|
|
2919
|
+
if (helpOption && args.find((arg) => helpOption.is(arg))) {
|
|
2920
|
+
this.outputHelp();
|
|
2921
|
+
this._exit(0, "commander.helpDisplayed", "(outputHelp)");
|
|
2922
|
+
}
|
|
2923
|
+
}
|
|
2924
|
+
};
|
|
2925
|
+
/**
|
|
2926
|
+
* Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
|
|
2927
|
+
*
|
|
2928
|
+
* @param {string[]} args - array of arguments from node.execArgv
|
|
2929
|
+
* @returns {string[]}
|
|
2930
|
+
* @private
|
|
2931
|
+
*/
|
|
2932
|
+
function incrementNodeInspectorPort(args) {
|
|
2933
|
+
return args.map((arg) => {
|
|
2934
|
+
if (!arg.startsWith("--inspect")) return arg;
|
|
2935
|
+
let debugOption;
|
|
2936
|
+
let debugHost = "127.0.0.1";
|
|
2937
|
+
let debugPort = "9229";
|
|
2938
|
+
let match;
|
|
2939
|
+
if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) debugOption = match[1];
|
|
2940
|
+
else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
|
|
2941
|
+
debugOption = match[1];
|
|
2942
|
+
if (/^\d+$/.test(match[3])) debugPort = match[3];
|
|
2943
|
+
else debugHost = match[3];
|
|
2944
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
|
|
2945
|
+
debugOption = match[1];
|
|
2946
|
+
debugHost = match[3];
|
|
2947
|
+
debugPort = match[4];
|
|
2948
|
+
}
|
|
2949
|
+
if (debugOption && debugPort !== "0") return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
|
|
2950
|
+
return arg;
|
|
2951
|
+
});
|
|
2952
|
+
}
|
|
2953
|
+
/**
|
|
2954
|
+
* Exported for using from tests, not otherwise used outside this file.
|
|
2955
|
+
*
|
|
2956
|
+
* @returns {boolean | undefined}
|
|
2957
|
+
* @package
|
|
2958
|
+
*/
|
|
2959
|
+
function useColor() {
|
|
2960
|
+
if (process$1.env.NO_COLOR || process$1.env.FORCE_COLOR === "0" || process$1.env.FORCE_COLOR === "false") return false;
|
|
2961
|
+
if (process$1.env.FORCE_COLOR || process$1.env.CLICOLOR_FORCE !== void 0) return true;
|
|
2962
|
+
}
|
|
2963
|
+
new Command();
|
|
2964
|
+
//#endregion
|
|
2965
|
+
//#region src/mcp/install.ts
|
|
2966
|
+
/**
|
|
2967
|
+
* The WhatsApp server as the shared installer registers it.
|
|
2968
|
+
*
|
|
2969
|
+
* The facts — the package, the `mcp` argument `npx` needs, the `--account` pin, and the warning about other WhatsApp
|
|
2970
|
+
* servers — are core's `CHANNEL_SERVERS.whatsapp`, derived from this package's manifest, which the core server's
|
|
2971
|
+
* `comms_server_install` registers from too, so both surfaces say the same. What is added here is what only this
|
|
2972
|
+
* package knows: its own version, and where its code is (for `--launcher local`).
|
|
2973
|
+
*/
|
|
2974
|
+
const WHATSAPP_MCP = {
|
|
2975
|
+
...CHANNEL_SERVERS.whatsapp,
|
|
2976
|
+
version: VERSION,
|
|
2977
|
+
moduleUrl: import.meta.url
|
|
2978
|
+
};
|
|
2979
|
+
//#endregion
|
|
2980
|
+
//#region src/operations/accounts.ts
|
|
2981
|
+
/**
|
|
2982
|
+
* Adding and removing an account: which message store a name reads.
|
|
2983
|
+
*
|
|
2984
|
+
* Both are commands only, with no tool, and both refuse an agent. Choosing which file on this Mac an agent may read is
|
|
2985
|
+
* a person's decision, made at their own terminal — and the first read of WhatsApp's container is also the moment
|
|
2986
|
+
* macOS asks that person for permission, which a background server could not answer anyway. The refusal is core's
|
|
2987
|
+
* agent marker, a speed bump rather than a boundary; the boundary is that no tool offers either.
|
|
2988
|
+
*
|
|
2989
|
+
* The account itself is core's generic record in `config.json` (`config.ts`). Adding one loosens no setting core's
|
|
2990
|
+
* classifier judges — a new account in `read` on a platform whose only mode is `read` — so nothing is approved here:
|
|
2991
|
+
* the person typing the command is the one deciding.
|
|
2992
|
+
*/
|
|
2993
|
+
/** Refuses a command that is the person's to run, when an agent is running it — or when it is not at a terminal. */
|
|
2994
|
+
function refuseAnAgent(context, command, what) {
|
|
2995
|
+
const marker = agentMarker(context.env);
|
|
2996
|
+
if (marker !== null || context.surface !== "cli") throw new CommsError("LOOSENING_REFUSED", `only a person ${what}`, {
|
|
2997
|
+
hint: `Ask the person to run \`agent-whatsapp ${command}\` in their own terminal.`,
|
|
2998
|
+
...marker === null ? {} : { details: { marker } }
|
|
2999
|
+
});
|
|
3000
|
+
}
|
|
3001
|
+
async function addAccount(context, request) {
|
|
3002
|
+
refuseAnAgent(context, `add ${request.name}`, "chooses which WhatsApp store an agent may read");
|
|
3003
|
+
const problem = nameShapeProblem(request.name, PLATFORM);
|
|
3004
|
+
if (problem) throw new CommsError("USAGE", problem);
|
|
3005
|
+
const isDefault = request.source === void 0;
|
|
3006
|
+
const path = isDefault ? defaultStorePath(context.env) : checkStorePath(expandSource(request.source, context.env));
|
|
3007
|
+
const store = {
|
|
3008
|
+
path,
|
|
3009
|
+
isDefault
|
|
3010
|
+
};
|
|
3011
|
+
const identity = storeIdentity(path, isDefault);
|
|
3012
|
+
/** The same checks, before the store is opened and again inside the write: anything can happen in between. */
|
|
3013
|
+
const refuseTaken = (config) => {
|
|
3014
|
+
requireNamedConfig(config);
|
|
3015
|
+
const free = nameAvailable(config, "account", request.name, PLATFORM);
|
|
3016
|
+
if (!free.ok) throw lookupName(config, "account", request.name)?.platform === "whatsapp" ? new CommsError("USAGE", `"${request.name}" is already added`, { hint: `Remove it first with \`agent-whatsapp remove ${request.name}\` to point it at another store.` }) : free.error;
|
|
3017
|
+
for (const [name, other] of Object.entries(config.accounts)) {
|
|
3018
|
+
if (other.platform !== "whatsapp") continue;
|
|
3019
|
+
if (context.storeOf(other).path === path || other.workspace === identity.workspace) throw new CommsError("USAGE", `that store is already added, as "${name}"`, { hint: "One name per message store." });
|
|
3020
|
+
}
|
|
3021
|
+
};
|
|
3022
|
+
refuseTaken(await context.config());
|
|
3023
|
+
await probeStore(path, context.sourceOptions(isDefault));
|
|
3024
|
+
const account = newWhatsAppAccount({
|
|
3025
|
+
now: context.now(),
|
|
3026
|
+
store
|
|
3027
|
+
});
|
|
3028
|
+
await context.core.config.update((config) => {
|
|
3029
|
+
refuseTaken(config);
|
|
3030
|
+
return {
|
|
3031
|
+
...config,
|
|
3032
|
+
accounts: {
|
|
3033
|
+
...config.accounts,
|
|
3034
|
+
[request.name]: account
|
|
3035
|
+
}
|
|
3036
|
+
};
|
|
3037
|
+
});
|
|
3038
|
+
return {
|
|
3039
|
+
account: request.name,
|
|
3040
|
+
id: account.id,
|
|
3041
|
+
store: {
|
|
3042
|
+
path,
|
|
3043
|
+
default: isDefault,
|
|
3044
|
+
id: account.workspace
|
|
3045
|
+
},
|
|
3046
|
+
next: `agent-whatsapp sync --account ${request.name}`
|
|
3047
|
+
};
|
|
3048
|
+
}
|
|
3049
|
+
/**
|
|
3050
|
+
* How long a remove waits for a sync of the same account to finish. A sync copies the whole store, which on a large
|
|
3051
|
+
* one takes a while; after this the person is told to try again, and nothing is removed.
|
|
3052
|
+
*/
|
|
3053
|
+
const REMOVE_WAIT_MS = 6e4;
|
|
3054
|
+
async function removeAccount(context, request) {
|
|
3055
|
+
refuseAnAgent(context, `remove ${request.name}`, "removes a WhatsApp account");
|
|
3056
|
+
const { account } = requireAccount(await context.config(), request.name);
|
|
3057
|
+
await withFileLock(context.syncLock(account), async () => {
|
|
3058
|
+
await context.core.config.update((config) => {
|
|
3059
|
+
if (lookupName(config, "account", request.name)?.id !== account.id) throw new CommsError("TRANSIENT", `"${request.name}" changed while it was being removed`, { hint: "Nothing was removed. Run it again." });
|
|
3060
|
+
const { [request.name]: _removed, ...rest } = config.accounts;
|
|
3061
|
+
return {
|
|
3062
|
+
...config,
|
|
3063
|
+
accounts: rest
|
|
3064
|
+
};
|
|
3065
|
+
});
|
|
3066
|
+
await rm(context.accountDir(account), {
|
|
3067
|
+
recursive: true,
|
|
3068
|
+
force: true
|
|
3069
|
+
});
|
|
3070
|
+
await context.lists.forget(account.id);
|
|
3071
|
+
}, { timeoutMs: REMOVE_WAIT_MS });
|
|
3072
|
+
return {
|
|
3073
|
+
account: request.name,
|
|
3074
|
+
removed: true,
|
|
3075
|
+
indexDeleted: true,
|
|
3076
|
+
listsForgotten: true
|
|
3077
|
+
};
|
|
3078
|
+
}
|
|
3079
|
+
//#endregion
|
|
3080
|
+
//#region src/operations/chat-lists.ts
|
|
3081
|
+
function without(list, chatId) {
|
|
3082
|
+
const key = listKey(chatId);
|
|
3083
|
+
return list.filter((entry) => listKey(entry) !== key);
|
|
3084
|
+
}
|
|
3085
|
+
function withEntry(list, chatId) {
|
|
3086
|
+
return list.some((entry) => listKey(entry) === listKey(chatId)) ? [...list] : [...list, chatId];
|
|
3087
|
+
}
|
|
3088
|
+
function effectOf(lists) {
|
|
3089
|
+
const denied = lists.deny.length > 0 ? `, except the ${lists.deny.length} denied` : "";
|
|
3090
|
+
if (lists.allow.length > 0) return `An agent sees only the ${lists.allow.length} allowed chat(s)${denied}.`;
|
|
3091
|
+
return `An agent sees every chat${denied}; status updates only when it asks for them.`;
|
|
3092
|
+
}
|
|
3093
|
+
/**
|
|
3094
|
+
* The chat an entry names, looked up in the index as the person sees it — every chat the last sync kept, whatever the
|
|
3095
|
+
* lists say now — so a mistyped number is noticed rather than trusted.
|
|
3096
|
+
*/
|
|
3097
|
+
async function named(context, name, account, chatId) {
|
|
3098
|
+
let index;
|
|
3099
|
+
try {
|
|
3100
|
+
index = await WhatsAppIndex.open(context.accountDir(account), name, new Visibility(void 0));
|
|
3101
|
+
} catch (error) {
|
|
3102
|
+
if (!isCommsError(error) || error.details?.reason !== "NOT_SYNCED") throw error;
|
|
3103
|
+
return {
|
|
3104
|
+
chat: null,
|
|
3105
|
+
warning: `"${name}" has not been synced, so whether a chat is ${chatId} could not be checked. The entry is kept.`
|
|
3106
|
+
};
|
|
3107
|
+
}
|
|
3108
|
+
try {
|
|
3109
|
+
const chat = index.chat(chatId);
|
|
3110
|
+
if (chat) return { chat: new Presenter(name).chat(chat) };
|
|
3111
|
+
return {
|
|
3112
|
+
chat: null,
|
|
3113
|
+
warning: `There is no chat ${chatId} in the index as of the last sync — check the number. The entry is kept, and applies to that chat if one appears; one the lists hid at the last sync is not in the index either.`
|
|
3114
|
+
};
|
|
3115
|
+
} finally {
|
|
3116
|
+
index.close();
|
|
3117
|
+
}
|
|
3118
|
+
}
|
|
3119
|
+
/** The one path every list change takes: the person check first, before any input is read. */
|
|
3120
|
+
async function change(context, command, request, next) {
|
|
3121
|
+
refuseAnAgent(context, command, "changes which chats an agent may see");
|
|
3122
|
+
const chatId = request.chat === void 0 ? void 0 : chatRefOf(request.chat, { international: true }).id;
|
|
3123
|
+
const { name, account } = await context.account(request.account);
|
|
3124
|
+
const { before, after } = await context.lists.update(account.id, (lists) => next(lists, chatId));
|
|
3125
|
+
return {
|
|
3126
|
+
account: name,
|
|
3127
|
+
allow: [...after.allow],
|
|
3128
|
+
deny: [...after.deny],
|
|
3129
|
+
changed: JSON.stringify(before) !== JSON.stringify(after),
|
|
3130
|
+
effect: effectOf(after),
|
|
3131
|
+
next: `agent-whatsapp sync --account ${name}`,
|
|
3132
|
+
...chatId === void 0 ? {} : await named(context, name, account, chatId)
|
|
3133
|
+
};
|
|
3134
|
+
}
|
|
3135
|
+
/** Lets an agent see this chat. Once anything is allowed, only allowed chats are visible. Takes it off the deny list. */
|
|
3136
|
+
function allowChat(context, request) {
|
|
3137
|
+
return change(context, "allow", request, (lists, chatId) => ({
|
|
3138
|
+
allow: withEntry(lists.allow, chatId),
|
|
3139
|
+
deny: without(lists.deny, chatId)
|
|
3140
|
+
}));
|
|
3141
|
+
}
|
|
3142
|
+
/**
|
|
3143
|
+
* Hides this chat from agents entirely. The allow list is left as it is: taking the chat off it could empty it, and
|
|
3144
|
+
* an empty allow list shows everything.
|
|
3145
|
+
*/
|
|
3146
|
+
function denyChat(context, request) {
|
|
3147
|
+
return change(context, "deny", request, (lists, chatId) => ({
|
|
3148
|
+
allow: [...lists.allow],
|
|
3149
|
+
deny: withEntry(lists.deny, chatId)
|
|
3150
|
+
}));
|
|
3151
|
+
}
|
|
3152
|
+
/** Takes one chat off both lists, or with no chat, empties both. */
|
|
3153
|
+
function clearChats(context, request) {
|
|
3154
|
+
return change(context, "clear", request, (lists, chatId) => chatId === void 0 ? {
|
|
3155
|
+
allow: [],
|
|
3156
|
+
deny: []
|
|
3157
|
+
} : {
|
|
3158
|
+
allow: without(lists.allow, chatId),
|
|
3159
|
+
deny: without(lists.deny, chatId)
|
|
3160
|
+
});
|
|
3161
|
+
}
|
|
3162
|
+
//#endregion
|
|
3163
|
+
//#region src/cli/opener.ts
|
|
3164
|
+
function openLink(url, platform = process.platform) {
|
|
3165
|
+
if (!/^(?:whatsapp:\/\/send\?|https:\/\/wa\.me\/)/.test(url)) return false;
|
|
3166
|
+
const [command, args] = platform === "darwin" ? ["open", [url]] : platform === "win32" ? ["cmd", [
|
|
3167
|
+
"/c",
|
|
3168
|
+
"start",
|
|
3169
|
+
"",
|
|
3170
|
+
url
|
|
3171
|
+
]] : ["xdg-open", [url]];
|
|
3172
|
+
try {
|
|
3173
|
+
const child = spawn(command, args, {
|
|
3174
|
+
stdio: "ignore",
|
|
3175
|
+
detached: true
|
|
3176
|
+
});
|
|
3177
|
+
child.on("error", () => void 0);
|
|
3178
|
+
child.unref();
|
|
3179
|
+
return true;
|
|
3180
|
+
} catch {
|
|
3181
|
+
return false;
|
|
3182
|
+
}
|
|
3183
|
+
}
|
|
3184
|
+
//#endregion
|
|
3185
|
+
//#region src/cli/render.ts
|
|
3186
|
+
/**
|
|
3187
|
+
* What a person sees without `--json`. Every contact-controlled string passes core's display escaper on its way to
|
|
3188
|
+
* the terminal, so no byte in a message can move the cursor, write the clipboard or reorder a line.
|
|
3189
|
+
*/
|
|
3190
|
+
function name(field, fallback, width = 32) {
|
|
3191
|
+
const text = innerText(field);
|
|
3192
|
+
return text === "" ? escapeForDisplay(fallback) : truncateDisplay(text, width);
|
|
3193
|
+
}
|
|
3194
|
+
function size(bytes) {
|
|
3195
|
+
if (bytes === null) return "size unknown";
|
|
3196
|
+
if (bytes < 1024) return `${bytes} B`;
|
|
3197
|
+
if (bytes < 1048576) return `${(bytes / 1024).toFixed(0)} KB`;
|
|
3198
|
+
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
|
|
3199
|
+
}
|
|
3200
|
+
function renderAdded(result, color) {
|
|
3201
|
+
return [`${paint(color, "green", "Added")} ${result.account} → ${escapeForDisplay(result.store.path)}${result.store.default ? " (WhatsApp for Mac)" : ""}`, `Next: ${result.next}`].join("\n");
|
|
3202
|
+
}
|
|
3203
|
+
function renderRemoved(result, color) {
|
|
3204
|
+
return `${paint(color, "green", "Removed")} ${result.account}, and its local index. WhatsApp's own store was not touched.`;
|
|
3205
|
+
}
|
|
3206
|
+
function renderStatus(result, color) {
|
|
3207
|
+
const lines = [];
|
|
3208
|
+
if (result.accounts.length === 0) lines.push(`No WhatsApp account yet. ${result.setup ?? ""}`);
|
|
3209
|
+
for (const account of result.accounts) {
|
|
3210
|
+
lines.push(paint(color, "bold", account.account));
|
|
3211
|
+
lines.push(` store ${escapeForDisplay(account.store.path)}${account.store.default ? " (WhatsApp for Mac)" : ""}`);
|
|
3212
|
+
const access = account.access.state === "readable" ? paint(color, "green", "readable") : paint(color, account.access.state === "not-checked" ? "dim" : "yellow", account.access.state);
|
|
3213
|
+
lines.push(` access ${access}${account.access.message ? ` — ${account.access.message}` : ""}`);
|
|
3214
|
+
if (account.chatLists.allow > 0 || account.chatLists.deny > 0) lines.push(` lists ${account.chatLists.allow} allowed, ${account.chatLists.deny} denied`);
|
|
3215
|
+
if (account.access.hint) lines.push(` ${account.access.hint}`);
|
|
3216
|
+
if (account.index.synced) {
|
|
3217
|
+
lines.push(` index ${account.index.chats} chats, ${account.index.messages} messages, ${account.index.media} with media, ${account.index.statusChats} status-update chat(s) · synced ${account.index.indexedAt}`);
|
|
3218
|
+
if (account.index.unattributedStatus > 0) lines.push(` ${unattributed(account.index.unattributedStatus)}`);
|
|
3219
|
+
for (const entry of account.index.degraded) lines.push(paint(color, "dim", ` without ${entry.part}: ${entry.costs}`));
|
|
3220
|
+
} else lines.push(` index not synced yet — agent-whatsapp sync --account ${account.account}`);
|
|
3221
|
+
}
|
|
3222
|
+
lines.push("", paint(color, "dim", `Reads: ${result.reads}.`), paint(color, "dim", `Sends: ${result.sends}.`));
|
|
3223
|
+
return lines.join("\n");
|
|
3224
|
+
}
|
|
3225
|
+
function renderSync(result, color) {
|
|
3226
|
+
const lines = [
|
|
3227
|
+
`${paint(color, "green", "Synced")} ${result.account}: ${result.chats} chats, ${result.messages} messages, ${result.media} with media.`,
|
|
3228
|
+
paint(color, "dim", `${result.statusChats} status-update chat(s) are indexed too, and listed or searched only with --kind status.`),
|
|
3229
|
+
paint(color, "dim", `Copied ${result.copied.join(" and ")} (attempt ${result.snapshot.attempts}); the copy is deleted. WhatsApp's files were only read.`)
|
|
3230
|
+
];
|
|
3231
|
+
if (result.unattributedStatus > 0) lines.push(paint(color, "dim", unattributed(result.unattributedStatus)));
|
|
3232
|
+
for (const entry of result.degraded) lines.push(paint(color, "yellow", `Without ${entry.part}: ${entry.costs}.`));
|
|
3233
|
+
return lines.join("\n");
|
|
3234
|
+
}
|
|
3235
|
+
/** Status updates the lists hid because nobody could be named as their author. */
|
|
3236
|
+
function unattributed(count) {
|
|
3237
|
+
return `${count} status update(s) hidden: WhatsApp recorded no author for them, and while the lists hide anyone, a post that could be theirs is not shown.`;
|
|
3238
|
+
}
|
|
3239
|
+
function renderChatLists(result, color) {
|
|
3240
|
+
const list = (entries) => entries.length === 0 ? paint(color, "dim", "(none)") : entries.join(", ");
|
|
3241
|
+
const chat = result.chat ? [` chat ${name(result.chat.name, result.chat.phone ? `+${result.chat.phone}` : result.chat.id, 60)} · ${result.chat.kind} · ${escapeForDisplay(result.chat.id)}`] : [];
|
|
3242
|
+
return [
|
|
3243
|
+
`${paint(color, "green", result.changed ? "Updated" : "Unchanged")} ${result.account}. ${result.effect}`,
|
|
3244
|
+
...chat,
|
|
3245
|
+
...result.warning ? [paint(color, "yellow", result.warning)] : [],
|
|
3246
|
+
` allow ${list(result.allow)}`,
|
|
3247
|
+
` deny ${list(result.deny)}`,
|
|
3248
|
+
paint(color, "dim", `Every read and draft applies this now. What is hidden leaves the index, and what the last sync left out comes back, at the next sync: ${result.next}`)
|
|
3249
|
+
].join("\n");
|
|
3250
|
+
}
|
|
3251
|
+
function renderChats(result, color) {
|
|
3252
|
+
const lines = [paint(color, "bold", `${"CHAT".padEnd(34)} ${"KIND".padEnd(13)} ${"MSGS".padStart(6)} LAST`)];
|
|
3253
|
+
for (const chat of result.chats) {
|
|
3254
|
+
lines.push(`${name(chat.name, chat.phone ? `+${chat.phone}` : chat.id, 34).padEnd(34)} ${chat.kind.padEnd(13)} ${String(chat.messages).padStart(6)} ${chat.lastMessageAt ?? ""}`);
|
|
3255
|
+
lines.push(paint(color, "dim", ` ${escapeForDisplay(chat.id)}`));
|
|
3256
|
+
}
|
|
3257
|
+
if (!result.complete) lines.push("", paint(color, "dim", "More chats remain: ask for a larger --limit."));
|
|
3258
|
+
lines.push(paint(color, "dim", `As of the last sync, ${result.indexedAt}.`));
|
|
3259
|
+
return lines.join("\n");
|
|
3260
|
+
}
|
|
3261
|
+
function renderMessage(message, color, chatLabel) {
|
|
3262
|
+
const who = message.fromMe ? "me" : name(message.sender?.name ?? null, message.sender?.jid ?? "unknown", 28);
|
|
3263
|
+
const marks = [];
|
|
3264
|
+
if (message.kind !== "text" && message.kind !== "link") marks.push(message.kind);
|
|
3265
|
+
if (message.viewOnce) marks.push("view once");
|
|
3266
|
+
if (message.hidden.characters > 0) marks.push(paint(color, "yellow", `${message.hidden.characters} hidden character(s)${message.hidden.bidi ? ", bidi" : ""}`));
|
|
3267
|
+
if (message.tokensNeutralised > 0) marks.push(paint(color, "yellow", `${message.tokensNeutralised} token(s) defused`));
|
|
3268
|
+
for (const link of message.links) if (link.flags.length > 0) marks.push(paint(color, "yellow", `link ${link.domain ?? "?"}: ${link.flags.join(", ")}`));
|
|
3269
|
+
const parts = [[
|
|
3270
|
+
chatLabel ? paint(color, "dim", chatLabel) : null,
|
|
3271
|
+
paint(color, "bold", who),
|
|
3272
|
+
paint(color, "dim", `${message.at ?? "?"} · #${message.id}`),
|
|
3273
|
+
marks.length ? marks.join(" · ") : null
|
|
3274
|
+
].filter(Boolean).join(" ")];
|
|
3275
|
+
const body = innerText(message.content);
|
|
3276
|
+
if (body) parts.push(escapeForDisplay(body).replace(/^/gm, " "));
|
|
3277
|
+
if (message.media) parts.push(paint(color, "dim", ` [${message.media.type}${message.media.mime ? ` ${message.media.mime}` : ""}, ${size(message.media.size)}${message.media.name ? `, ${name(message.media.name, "", 60)}` : ""} — not downloaded]`));
|
|
3278
|
+
return parts.join("\n");
|
|
3279
|
+
}
|
|
3280
|
+
function renderHistory(result, color) {
|
|
3281
|
+
const title = name(result.chat.name, result.chat.phone ? `+${result.chat.phone}` : result.chat.id, 60);
|
|
3282
|
+
const lines = [paint(color, "bold", `${title} · ${result.chat.kind} · newest ${result.messages.length}`), ""];
|
|
3283
|
+
if (result.messages.length === 0) lines.push(paint(color, "dim", "No messages."));
|
|
3284
|
+
for (const message of result.messages) lines.push(renderMessage(message, color), "");
|
|
3285
|
+
if (!result.complete) lines.push(paint(color, "dim", `Older messages remain: --before ${result.next}`));
|
|
3286
|
+
lines.push(paint(color, "dim", `As of the last sync, ${result.indexedAt}.`));
|
|
3287
|
+
return lines.join("\n");
|
|
3288
|
+
}
|
|
3289
|
+
function renderSearch(result, color) {
|
|
3290
|
+
const lines = [paint(color, "bold", `${result.results.length} match(es) for ${result.words.join(" ")}`), ""];
|
|
3291
|
+
for (const hit of result.results) lines.push(renderMessage(hit.message, color, name(hit.chat.name, hit.chat.id, 30)), "");
|
|
3292
|
+
if (!result.complete) lines.push(paint(color, "dim", "More matches remain: ask for a larger --limit."));
|
|
3293
|
+
lines.push(paint(color, "dim", `As of the last sync, ${result.indexedAt}.`));
|
|
3294
|
+
return lines.join("\n");
|
|
3295
|
+
}
|
|
3296
|
+
function renderDraft(result, color, opened) {
|
|
3297
|
+
const lines = [
|
|
3298
|
+
paint(color, "bold", `Draft to ${result.to.phone ? `+${result.to.phone}` : result.to.chat ?? "?"}`),
|
|
3299
|
+
escapeForDisplay(result.text).replace(/^/gm, " "),
|
|
3300
|
+
""
|
|
3301
|
+
];
|
|
3302
|
+
if (result.links) {
|
|
3303
|
+
lines.push(`Open in WhatsApp: ${result.links.app}`, `Or in a browser: ${result.links.web}`);
|
|
3304
|
+
if (opened) lines.push(paint(color, "green", "Opened WhatsApp with the text filled in. Check it, then press send."));
|
|
3305
|
+
} else lines.push(paint(color, "yellow", result.reason ?? "Paste the text into WhatsApp."));
|
|
3306
|
+
lines.push("", paint(color, "dim", result.note));
|
|
3307
|
+
return lines.join("\n");
|
|
3308
|
+
}
|
|
3309
|
+
//#endregion
|
|
3310
|
+
//#region src/cli/program.ts
|
|
3311
|
+
/**
|
|
3312
|
+
* Every channel's approve command that can have prepared a send, from the manifests: the channels whose accounts can
|
|
3313
|
+
* be in `send`. WhatsApp's is not among them — it never sends — and a channel added later is, without an edit here.
|
|
3314
|
+
*/
|
|
3315
|
+
function sendApproveCommands() {
|
|
3316
|
+
const commands = CHANNELS.flatMap((channel) => {
|
|
3317
|
+
const manifest = channelManifest(channel);
|
|
3318
|
+
return manifest?.approve && manifest.accounts?.modes.includes("send") ? [`\`${manifest.approve}\``] : [];
|
|
3319
|
+
});
|
|
3320
|
+
return commands.length <= 1 ? commands.join("") : `${commands.slice(0, -1).join(", ")} or ${commands.at(-1)}`;
|
|
3321
|
+
}
|
|
3322
|
+
async function run(argv, deps = {}) {
|
|
3323
|
+
const streams = deps.streams ?? {
|
|
3324
|
+
stdout: process.stdout,
|
|
3325
|
+
stderr: process.stderr,
|
|
3326
|
+
stdin: process.stdin
|
|
3327
|
+
};
|
|
3328
|
+
const env = deps.env ?? process.env;
|
|
3329
|
+
const open = deps.open ?? openLink;
|
|
3330
|
+
const program = new Command();
|
|
3331
|
+
let exitCode = 0;
|
|
3332
|
+
let ran = false;
|
|
3333
|
+
program.name("agent-whatsapp").description("WhatsApp for coding agents, read-only: read, list and search the chats WhatsApp for Mac keeps on this Mac, and draft replies the person sends. No network, no sending.").version(VERSION, "-v, --version").option("--json", "print the result as {\"ok\":true,\"schemaVersion\":1,\"data\":…}", false).option("--no-color", "never colour the output").configureOutput({
|
|
3334
|
+
writeOut: (text) => streams.stdout.write(text),
|
|
3335
|
+
writeErr: (text) => streams.stderr.write(text)
|
|
3336
|
+
}).addHelpText("after", `
|
|
3337
|
+
Getting started (a person, in a terminal):
|
|
3338
|
+
agent-whatsapp add personal/whatsapp reads WhatsApp for Mac's store; macOS may ask to allow access
|
|
3339
|
+
agent-whatsapp sync --account personal/whatsapp
|
|
3340
|
+
agent-whatsapp chats --account personal/whatsapp
|
|
3341
|
+
agent-whatsapp search "invoice" --account personal/whatsapp
|
|
3342
|
+
agent-whatsapp draft +15555550101 "On my way" a link; you press send in WhatsApp
|
|
3343
|
+
agent-whatsapp deny +15555550102 --account personal/whatsapp agents never see that chat
|
|
3344
|
+
agent-whatsapp mcp install --client claude-code --account personal/whatsapp
|
|
3345
|
+
|
|
3346
|
+
Nothing here connects to WhatsApp or any other server, and nothing here can send. Needs Node 22.16 or newer.
|
|
3347
|
+
|
|
3348
|
+
Exit codes: 0 ok · 1 unexpected · 10 only a person may do that, or a change needs approval · 64 usage
|
|
3349
|
+
· 65 bad data (a store whose layout changed) · 66 not found · 69 unavailable · 75 temporary (retry;
|
|
3350
|
+
a macOS dialog may be waiting) · 77 permission needed (macOS privacy) · 78 configuration problem.`).exitOverride();
|
|
3351
|
+
const output = () => {
|
|
3352
|
+
const options = program.opts();
|
|
3353
|
+
return {
|
|
3354
|
+
json: Boolean(options.json),
|
|
3355
|
+
color: colorEnabled(env, streams.stdout, options.color)
|
|
3356
|
+
};
|
|
3357
|
+
};
|
|
3358
|
+
/**
|
|
3359
|
+
* A command that succeeded but wants a non-zero exit code — `mcp install` that registered an entry which did not
|
|
3360
|
+
* start — where the result *is* the output and `--json` must still print one envelope.
|
|
3361
|
+
*/
|
|
3362
|
+
let softExit = null;
|
|
3363
|
+
const act = (body) => async (...args) => {
|
|
3364
|
+
ran = true;
|
|
3365
|
+
softExit = null;
|
|
3366
|
+
exitCode = await runCommand(output(), async () => {
|
|
3367
|
+
requireSupportedNode();
|
|
3368
|
+
await body(new WhatsAppContext({
|
|
3369
|
+
...deps,
|
|
3370
|
+
env,
|
|
3371
|
+
surface: "cli",
|
|
3372
|
+
log: deps.log ?? ((line) => streams.stderr.write(`${line}\n`))
|
|
3373
|
+
}), output(), ...args);
|
|
3374
|
+
}, streams);
|
|
3375
|
+
if (exitCode === 0 && softExit !== null) exitCode = softExit;
|
|
3376
|
+
};
|
|
3377
|
+
const accountOption = (command) => command.requiredOption("--account <name>", "which WhatsApp account, as `organisation/whatsapp`");
|
|
3378
|
+
program.command("add <name>").description("give WhatsApp for Mac's message store a name, as organisation/whatsapp — a person does this").option("--source <path>", "a ChatStorage.sqlite elsewhere, e.g. WhatsApp Business’s; the default is WhatsApp for Mac’s").action(act(async (context, options, name, flags) => {
|
|
3379
|
+
const result = await addAccount(context, {
|
|
3380
|
+
name,
|
|
3381
|
+
source: flags.source === void 0 ? void 0 : String(flags.source)
|
|
3382
|
+
});
|
|
3383
|
+
writeResult(result, options, () => renderAdded(result, options.color), streams);
|
|
3384
|
+
}));
|
|
3385
|
+
program.command("remove <name>").description("forget an account, its chat lists and its local index — a person does this; WhatsApp's own store is not touched").action(act(async (context, options, name) => {
|
|
3386
|
+
const result = await removeAccount(context, { name });
|
|
3387
|
+
writeResult(result, options, () => renderRemoved(result, options.color), streams);
|
|
3388
|
+
}));
|
|
3389
|
+
accountOption(program.command("allow <chat>")).description("let agents see this chat; once any chat is allowed, agents see only allowed chats — a person does this").action(act(async (context, options, chat, flags) => {
|
|
3390
|
+
const result = await allowChat(context, {
|
|
3391
|
+
account: String(flags.account),
|
|
3392
|
+
chat
|
|
3393
|
+
});
|
|
3394
|
+
writeResult(result, options, () => renderChatLists(result, options.color), streams);
|
|
3395
|
+
}));
|
|
3396
|
+
accountOption(program.command("deny <chat>")).description("hide this chat from agents entirely: not listed, searched, read or drafted to — a person does this").action(act(async (context, options, chat, flags) => {
|
|
3397
|
+
const result = await denyChat(context, {
|
|
3398
|
+
account: String(flags.account),
|
|
3399
|
+
chat
|
|
3400
|
+
});
|
|
3401
|
+
writeResult(result, options, () => renderChatLists(result, options.color), streams);
|
|
3402
|
+
}));
|
|
3403
|
+
accountOption(program.command("clear [chat]")).description("take a chat off both lists, or with no chat, empty them — a person does this").action(act(async (context, options, chat, flags) => {
|
|
3404
|
+
const result = await clearChats(context, {
|
|
3405
|
+
account: String(flags.account),
|
|
3406
|
+
chat
|
|
3407
|
+
});
|
|
3408
|
+
writeResult(result, options, () => renderChatLists(result, options.color), streams);
|
|
3409
|
+
}));
|
|
3410
|
+
program.command("status").description("what is set up, whether each store can be read, and what the index holds").option("--account <name>", "only this account").option("--no-check", "do not open the WhatsApp store to test access; report only what is recorded").action(act(async (context, options, flags) => {
|
|
3411
|
+
const result = await whatsappStatus(context, {
|
|
3412
|
+
account: flags.account === void 0 ? void 0 : String(flags.account),
|
|
3413
|
+
check: flags.check !== false
|
|
3414
|
+
});
|
|
3415
|
+
writeResult(result, options, () => renderStatus(result, options.color), streams);
|
|
3416
|
+
}));
|
|
3417
|
+
accountOption(program.command("sync")).description("copy WhatsApp's store privately, check it, and rebuild the local index from the copy").action(act(async (context, options, flags) => {
|
|
3418
|
+
const result = await syncAccount(context, { account: String(flags.account) });
|
|
3419
|
+
writeResult(result, options, () => renderSync(result, options.color), streams);
|
|
3420
|
+
}));
|
|
3421
|
+
accountOption(program.command("chats")).description("chats, most recent first, as of the last sync; status updates only with --kind status").option("--limit <n>", "how many: 1 to 500", "50").addOption(new Option("--kind <kind>", "only one kind of chat").choices([...CHAT_KINDS])).action(act(async (context, options, flags) => {
|
|
3422
|
+
const result = await listChats(context, {
|
|
3423
|
+
account: String(flags.account),
|
|
3424
|
+
limit: flags.limit,
|
|
3425
|
+
kind: flags.kind === void 0 ? void 0 : String(flags.kind)
|
|
3426
|
+
});
|
|
3427
|
+
writeResult(result, options, () => renderChats(result, options.color), streams);
|
|
3428
|
+
}));
|
|
3429
|
+
accountOption(program.command("read <chat>")).description("one chat, newest first: by the id `chats` shows, or by phone number").option("--limit <n>", "how many messages: 1 to 200", "50").option("--before <id>", "older than this message: the `next` value of an earlier read").action(act(async (context, options, chat, flags) => {
|
|
3430
|
+
const result = await readChat(context, {
|
|
3431
|
+
account: String(flags.account),
|
|
3432
|
+
chat,
|
|
3433
|
+
limit: flags.limit,
|
|
3434
|
+
before: flags.before === void 0 ? void 0 : String(flags.before)
|
|
3435
|
+
});
|
|
3436
|
+
writeResult(result, options, () => renderHistory(result, options.color), streams);
|
|
3437
|
+
}));
|
|
3438
|
+
accountOption(program.command("search <query>")).description("words, in text, captions, file names, sender names and chat names, as of the last sync").option("--chat <chat>", "only in this chat").option("--sender <name>", "only from senders whose name contains this").addOption(new Option("--kind <kind>", "only in one kind of chat; status updates are searched only when asked for").choices([...CHAT_KINDS])).option("--limit <n>", "how many: 1 to 100", "20").action(act(async (context, options, query, flags) => {
|
|
3439
|
+
const result = await searchMessages(context, {
|
|
3440
|
+
account: String(flags.account),
|
|
3441
|
+
query,
|
|
3442
|
+
chat: flags.chat === void 0 ? void 0 : String(flags.chat),
|
|
3443
|
+
sender: flags.sender === void 0 ? void 0 : String(flags.sender),
|
|
3444
|
+
kind: flags.kind === void 0 ? void 0 : String(flags.kind),
|
|
3445
|
+
limit: flags.limit
|
|
3446
|
+
});
|
|
3447
|
+
writeResult(result, options, () => renderSearch(result, options.color), streams);
|
|
3448
|
+
}));
|
|
3449
|
+
program.command("draft <to> <text>").description("a message as a link that opens WhatsApp with it filled in — you press send; nothing is sent here. <to> is a phone number or an id `chats` shows").option("--account <name>", "the account the chat belongs to, as `organisation/whatsapp`; its allow and deny lists apply (without it, every account’s do)").option("--open", "open the link in WhatsApp now (a person only; an agent gives the link to the person)", false).action(act(async (context, options, to, text, flags) => {
|
|
3450
|
+
const result = await draftMessage(context, {
|
|
3451
|
+
account: flags.account === void 0 ? void 0 : String(flags.account),
|
|
3452
|
+
to,
|
|
3453
|
+
text
|
|
3454
|
+
});
|
|
3455
|
+
let opened = false;
|
|
3456
|
+
if (flags.open === true) {
|
|
3457
|
+
const marker = agentMarker(env);
|
|
3458
|
+
if (marker) throw new CommsError("APPROVAL_REQUIRED", "only a person opens a draft in WhatsApp", {
|
|
3459
|
+
hint: "Give the person the link from this draft (without --open); they click it and press send.",
|
|
3460
|
+
details: { marker }
|
|
3461
|
+
});
|
|
3462
|
+
if (!result.links) throw new CommsError("USAGE", result.reason ?? "no link can open this chat", { hint: "Copy the text and paste it into WhatsApp." });
|
|
3463
|
+
opened = open(result.links.app);
|
|
3464
|
+
}
|
|
3465
|
+
writeResult({
|
|
3466
|
+
...result,
|
|
3467
|
+
opened
|
|
3468
|
+
}, options, () => renderDraft(result, options.color, opened), streams);
|
|
3469
|
+
}));
|
|
3470
|
+
program.command("approve <approvalId>").description("approve a change at this terminal — registering or pruning this server — by reading it and typing the code back; WhatsApp never sends, so there is no message to approve").action(act(async (context, options, approvalId) => {
|
|
3471
|
+
const marker = agentMarker(env);
|
|
3472
|
+
if (marker) throw new CommsError("APPROVAL_REQUIRED", "only a person can approve a change, not an agent", {
|
|
3473
|
+
hint: `Ask the person to run \`agent-whatsapp approve ${approvalId}\` in their own terminal.`,
|
|
3474
|
+
details: { marker }
|
|
3475
|
+
});
|
|
3476
|
+
if (!canPrompt(env, streams, { json: options.json })) throw new CommsError("APPROVAL_REQUIRED", "approving a change needs an interactive terminal", { hint: `Run \`agent-whatsapp approve ${approvalId}\` directly in a terminal.` });
|
|
3477
|
+
const pending = await context.core.approvals.get(approvalId);
|
|
3478
|
+
if (!pending) throw new CommsError("NOT_FOUND", `no approval ${approvalId}`, { hint: "It may have expired, been used, or been cancelled. Prepare the change again." });
|
|
3479
|
+
if (approvalKind(pending) !== "change") throw new CommsError("USAGE", `approval ${approvalId} is for a send, and WhatsApp never sends`, { hint: `Approve it with the command that prepared it — ${sendApproveCommands()} — not this one.` });
|
|
3480
|
+
const outcome = await approveChangeAtTerminal(context.core, approvalId, env, {
|
|
3481
|
+
json: options.json,
|
|
3482
|
+
color: options.color
|
|
3483
|
+
}, streams);
|
|
3484
|
+
streams.stdout.write(outcome.state === "approved" ? "Approved. This command approves; the change is applied by the command that prepared it.\n" : "Cancelled. Nothing was changed.\n");
|
|
3485
|
+
}));
|
|
3486
|
+
const changeAt = (context, change, flags, command) => gatedChangeAtTerminal(context.core, change, {
|
|
3487
|
+
approvalId: flags.approval === void 0 ? void 0 : String(flags.approval),
|
|
3488
|
+
env,
|
|
3489
|
+
output: output(),
|
|
3490
|
+
command,
|
|
3491
|
+
approveCommand: "agent-whatsapp approve",
|
|
3492
|
+
streams
|
|
3493
|
+
});
|
|
3494
|
+
const mcp = program.command("mcp").description("run the MCP server on stdio, for a coding agent to connect to").option("--account <name>", "pin the server to one account; every tool then acts on it and no other").action(async (flags) => {
|
|
3495
|
+
ran = true;
|
|
3496
|
+
exitCode = await runCommand(output(), async () => {
|
|
3497
|
+
requireSupportedNode();
|
|
3498
|
+
const { startWhatsAppStdioServer } = await import("./stdio-entry-m_AQ55DZ.mjs");
|
|
3499
|
+
await startWhatsAppStdioServer({
|
|
3500
|
+
env,
|
|
3501
|
+
...flags.account ? { account: String(flags.account) } : {}
|
|
3502
|
+
});
|
|
3503
|
+
}, streams);
|
|
3504
|
+
});
|
|
3505
|
+
mcp.command("install").description("register this server with an MCP client, and prove it starts — a change the person approves").addOption(new Option("--client <client>", "which client to register with").choices([
|
|
3506
|
+
"claude-code",
|
|
3507
|
+
"claude-desktop",
|
|
3508
|
+
"codex",
|
|
3509
|
+
"cursor",
|
|
3510
|
+
"gemini",
|
|
3511
|
+
"vscode",
|
|
3512
|
+
"json"
|
|
3513
|
+
])).option("--name <name>", "the name the client will show: 1 to 64 letters, digits, dots, underscores or hyphens", "whatsapp").option("--account <name>", "pin the server to one account").addOption(new Option("--launcher <launcher>", "how the server is started").choices([
|
|
3514
|
+
"managed",
|
|
3515
|
+
"npx",
|
|
3516
|
+
"local"
|
|
3517
|
+
])).option("--no-verify", "do not start the server to check the entry works").option("--force", "replace this server's own earlier entry — this is how you upgrade", false).option("--print", "only print what would be written", false).option("--approval <approvalId>", "register the server this approval was given for").action(act(async (context, options, flags) => {
|
|
3518
|
+
if (!flags.client) throw new CommsError("USAGE", "name the client with --client", { hint: "For example: `agent-whatsapp mcp install --client claude-code --account personal/whatsapp`." });
|
|
3519
|
+
const pinned = flags.account ?? mcp.opts().account;
|
|
3520
|
+
const launcher = flags.launcher;
|
|
3521
|
+
const name = flags.name;
|
|
3522
|
+
await context.migration();
|
|
3523
|
+
const again = [
|
|
3524
|
+
"agent-whatsapp",
|
|
3525
|
+
"mcp",
|
|
3526
|
+
"install",
|
|
3527
|
+
"--client",
|
|
3528
|
+
String(flags.client),
|
|
3529
|
+
...name !== void 0 && name !== "whatsapp" ? ["--name", name] : [],
|
|
3530
|
+
...pinned !== void 0 ? ["--account", pinned] : [],
|
|
3531
|
+
...launcher !== void 0 ? ["--launcher", launcher] : [],
|
|
3532
|
+
...flags.verify === false ? ["--no-verify"] : [],
|
|
3533
|
+
...flags.force === true ? ["--force"] : []
|
|
3534
|
+
].join(" ");
|
|
3535
|
+
const result = await changeAt(context, serverInstallChange(context.core, env, {
|
|
3536
|
+
channel: "whatsapp",
|
|
3537
|
+
client: flags.client,
|
|
3538
|
+
name,
|
|
3539
|
+
account: pinned,
|
|
3540
|
+
launcher,
|
|
3541
|
+
noVerify: flags.verify === false,
|
|
3542
|
+
print: flags.print === true,
|
|
3543
|
+
force: flags.force === true
|
|
3544
|
+
}, WHATSAPP_MCP), flags, again);
|
|
3545
|
+
const status = installExitStatus(result);
|
|
3546
|
+
if (status !== EXIT_CODES.OK) softExit = status;
|
|
3547
|
+
writeResult(result, output(), () => renderInstall(result, options.color), streams);
|
|
3548
|
+
}));
|
|
3549
|
+
mcp.command("prune").description("remove managed runtimes that no client config it can read names, no printed entry names, and no process runs").option("--dry-run", "only say what would be removed", false).option("--include-printed", "also remove runtimes kept only because an entry for them was printed (--client json, --print), once those entries are gone", false).option("--approval <approvalId>", "remove the runtimes this approval was given for").action(act(async (context, options, flags) => {
|
|
3550
|
+
const result = await changeAt(context, serverPruneChange(context.core, env, {
|
|
3551
|
+
channel: "whatsapp",
|
|
3552
|
+
dryRun: flags.dryRun === true,
|
|
3553
|
+
includePrinted: flags.includePrinted === true
|
|
3554
|
+
}, WHATSAPP_MCP), flags, `agent-whatsapp mcp prune${flags.includePrinted === true ? " --include-printed" : ""}`);
|
|
3555
|
+
writeResult(result, output(), () => renderPrune(result, options.color), streams);
|
|
3556
|
+
}));
|
|
3557
|
+
try {
|
|
3558
|
+
await program.parseAsync([...argv], { from: "user" });
|
|
3559
|
+
} catch (error) {
|
|
3560
|
+
if (error instanceof CommanderError) {
|
|
3561
|
+
if ([
|
|
3562
|
+
"commander.helpDisplayed",
|
|
3563
|
+
"commander.help",
|
|
3564
|
+
"commander.version"
|
|
3565
|
+
].includes(error.code)) return 0;
|
|
3566
|
+
const message = error.message.replace(/^error: /, "");
|
|
3567
|
+
return runCommand(output(), async () => {
|
|
3568
|
+
throw new CommsError("USAGE", message, { hint: "Run `agent-whatsapp --help` to see the commands." });
|
|
3569
|
+
}, streams);
|
|
3570
|
+
}
|
|
3571
|
+
throw error;
|
|
3572
|
+
}
|
|
3573
|
+
if (!ran) {
|
|
3574
|
+
streams.stderr.write(`${paint(output().color, "dim", "Nothing to do. Try `agent-whatsapp --help`.")}\n`);
|
|
3575
|
+
return 64;
|
|
3576
|
+
}
|
|
3577
|
+
return exitCode;
|
|
3578
|
+
}
|
|
3579
|
+
//#endregion
|
|
3580
|
+
//#region src/cli.ts
|
|
3581
|
+
const code = await run(process.argv.slice(2));
|
|
3582
|
+
process.exitCode = code;
|
|
3583
|
+
//#endregion
|
|
3584
|
+
export {};
|