vde-open 0.0.0 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +124 -28
- package/THIRD_PARTY_NOTICES.md +3433 -0
- package/dist/cli.js +4194 -0
- package/dist/daemon.js +34 -0
- package/dist/heap-Dev_gSQn.js +12 -0
- package/dist/main-lxBamyBU.js +13257 -0
- package/dist/render-yCayIbhf.js +14769 -0
- package/dist/rolldown-runtime-DC62tzP2.js +33 -0
- package/dist/search-index-C0szMSlZ.js +8797 -0
- package/dist/web/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
- package/dist/web/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
- package/dist/web/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
- package/dist/web/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
- package/dist/web/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
- package/dist/web/assets/index-BYu5_12H.css +2 -0
- package/dist/web/assets/index-CLggJFeG.js +95 -0
- package/dist/web/assets/markdown.worker-BhrAVXtB.js +13 -0
- package/dist/web/index.html +13 -0
- package/dist/workers/parse-worker.js +30 -0
- package/dist/workers/search-worker.js +70 -0
- package/docs/agent-usage.md +97 -0
- package/package.json +57 -7
- package/skills/vde-open/SKILL.md +108 -0
package/dist/cli.js
ADDED
|
@@ -0,0 +1,4194 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { C as decodeStateFile, D as daemonEntryPath, E as resolveStateRoot, O as referencedBlobs, S as renameWithRetry, T as resolveRuntimeLocation, a as DAEMON_LOCK_NAME, b as proofMatches, c as readIpcKey, d as inspectOwner, f as readCurrentLock, g as encodeFrame, h as FrameDecoder, i as requirePrivateDirectoryIfExists, k as version, l as readPointer, m as systemProcessProbe, n as ensurePrivateDirectory, o as POINTER_FILE, p as releaseLock, r as inspectPrivateDirectory, s as START_LOCK_NAME, t as startDaemon, u as acquireLock, v as computeProof, w as currentPathEnvironment, x as removeWithRetry, y as createNonce } from "./main-lxBamyBU.js";
|
|
3
|
+
import { A as successEnvelope, C as VdeError, D as ExitCode, E as isVdeError, O as envelopeSchema, T as isErrorCode, Y as LIMITS, k as errorEnvelope, w as exitCodeForError } from "./search-index-C0szMSlZ.js";
|
|
4
|
+
import fs, { fstatSync } from "node:fs";
|
|
5
|
+
import { lstat, readFile, readdir, stat as stat$1, writeFile } from "node:fs/promises";
|
|
6
|
+
import path, { join, resolve } from "node:path";
|
|
7
|
+
import { EventEmitter } from "node:events";
|
|
8
|
+
import childProcess, { spawn } from "node:child_process";
|
|
9
|
+
import process$1 from "node:process";
|
|
10
|
+
import { stripVTControlCharacters } from "node:util";
|
|
11
|
+
import { randomUUID } from "node:crypto";
|
|
12
|
+
import { connect } from "node:net";
|
|
13
|
+
import { setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
14
|
+
//#region ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/error.js
|
|
15
|
+
/**
|
|
16
|
+
* CommanderError class
|
|
17
|
+
*/
|
|
18
|
+
var CommanderError = class extends Error {
|
|
19
|
+
/**
|
|
20
|
+
* Constructs the CommanderError class
|
|
21
|
+
* @param {number} exitCode suggested exit code which could be used with process.exit
|
|
22
|
+
* @param {string} code an id string representing the error
|
|
23
|
+
* @param {string} message human-readable description of the error
|
|
24
|
+
*/
|
|
25
|
+
constructor(exitCode, code, message) {
|
|
26
|
+
super(message);
|
|
27
|
+
Error.captureStackTrace(this, this.constructor);
|
|
28
|
+
this.name = this.constructor.name;
|
|
29
|
+
this.code = code;
|
|
30
|
+
this.exitCode = exitCode;
|
|
31
|
+
this.nestedError = void 0;
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* InvalidArgumentError class
|
|
36
|
+
*/
|
|
37
|
+
var InvalidArgumentError = class extends CommanderError {
|
|
38
|
+
/**
|
|
39
|
+
* Constructs the InvalidArgumentError class
|
|
40
|
+
* @param {string} [message] explanation of why argument is invalid
|
|
41
|
+
*/
|
|
42
|
+
constructor(message) {
|
|
43
|
+
super(1, "commander.invalidArgument", message);
|
|
44
|
+
Error.captureStackTrace(this, this.constructor);
|
|
45
|
+
this.name = this.constructor.name;
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
//#endregion
|
|
49
|
+
//#region ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/argument.js
|
|
50
|
+
var Argument = class {
|
|
51
|
+
/**
|
|
52
|
+
* Initialize a new command argument with the given name and description.
|
|
53
|
+
* The default is that the argument is required, and you can explicitly
|
|
54
|
+
* indicate this with <> around the name. Put [] around the name for an optional argument.
|
|
55
|
+
*
|
|
56
|
+
* @param {string} name
|
|
57
|
+
* @param {string} [description]
|
|
58
|
+
*/
|
|
59
|
+
constructor(name, description) {
|
|
60
|
+
this.description = description || "";
|
|
61
|
+
this.variadic = false;
|
|
62
|
+
this.parseArg = void 0;
|
|
63
|
+
this.defaultValue = void 0;
|
|
64
|
+
this.defaultValueDescription = void 0;
|
|
65
|
+
this.argChoices = void 0;
|
|
66
|
+
switch (name[0]) {
|
|
67
|
+
case "<":
|
|
68
|
+
this.required = true;
|
|
69
|
+
this._name = name.slice(1, -1);
|
|
70
|
+
break;
|
|
71
|
+
case "[":
|
|
72
|
+
this.required = false;
|
|
73
|
+
this._name = name.slice(1, -1);
|
|
74
|
+
break;
|
|
75
|
+
default:
|
|
76
|
+
this.required = true;
|
|
77
|
+
this._name = name;
|
|
78
|
+
}
|
|
79
|
+
if (this._name.endsWith("...")) {
|
|
80
|
+
this.variadic = true;
|
|
81
|
+
this._name = this._name.slice(0, -3);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Return argument name.
|
|
86
|
+
*
|
|
87
|
+
* @return {string}
|
|
88
|
+
*/
|
|
89
|
+
name() {
|
|
90
|
+
return this._name;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* @package
|
|
94
|
+
*/
|
|
95
|
+
_collectValue(value, previous) {
|
|
96
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) return [value];
|
|
97
|
+
previous.push(value);
|
|
98
|
+
return previous;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Set the default value, and optionally supply the description to be displayed in the help.
|
|
102
|
+
*
|
|
103
|
+
* @param {*} value
|
|
104
|
+
* @param {string} [description]
|
|
105
|
+
* @return {Argument}
|
|
106
|
+
*/
|
|
107
|
+
default(value, description) {
|
|
108
|
+
this.defaultValue = value;
|
|
109
|
+
this.defaultValueDescription = description;
|
|
110
|
+
return this;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Set the custom handler for processing CLI command arguments into argument values.
|
|
114
|
+
*
|
|
115
|
+
* @param {Function} [fn]
|
|
116
|
+
* @return {Argument}
|
|
117
|
+
*/
|
|
118
|
+
argParser(fn) {
|
|
119
|
+
this.parseArg = fn;
|
|
120
|
+
return this;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Only allow argument value to be one of choices.
|
|
124
|
+
*
|
|
125
|
+
* @param {string[]} values
|
|
126
|
+
* @return {Argument}
|
|
127
|
+
*/
|
|
128
|
+
choices(values) {
|
|
129
|
+
this.argChoices = values.slice();
|
|
130
|
+
this.parseArg = (arg, previous) => {
|
|
131
|
+
if (!this.argChoices.includes(arg)) throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
|
|
132
|
+
if (this.variadic) return this._collectValue(arg, previous);
|
|
133
|
+
return arg;
|
|
134
|
+
};
|
|
135
|
+
return this;
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Make argument required.
|
|
139
|
+
*
|
|
140
|
+
* @returns {Argument}
|
|
141
|
+
*/
|
|
142
|
+
argRequired() {
|
|
143
|
+
this.required = true;
|
|
144
|
+
return this;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Make argument optional.
|
|
148
|
+
*
|
|
149
|
+
* @returns {Argument}
|
|
150
|
+
*/
|
|
151
|
+
argOptional() {
|
|
152
|
+
this.required = false;
|
|
153
|
+
return this;
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
/**
|
|
157
|
+
* Takes an argument and returns its human readable equivalent for help usage.
|
|
158
|
+
*
|
|
159
|
+
* @param {Argument} arg
|
|
160
|
+
* @return {string}
|
|
161
|
+
* @private
|
|
162
|
+
*/
|
|
163
|
+
function humanReadableArgName(arg) {
|
|
164
|
+
const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
|
|
165
|
+
return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
|
|
166
|
+
}
|
|
167
|
+
//#endregion
|
|
168
|
+
//#region ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/help.js
|
|
169
|
+
/**
|
|
170
|
+
* TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`
|
|
171
|
+
* https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types
|
|
172
|
+
* @typedef { import("./argument.js").Argument } Argument
|
|
173
|
+
* @typedef { import("./command.js").Command } Command
|
|
174
|
+
* @typedef { import("./option.js").Option } Option
|
|
175
|
+
*/
|
|
176
|
+
var Help = class {
|
|
177
|
+
constructor() {
|
|
178
|
+
this.helpWidth = void 0;
|
|
179
|
+
this.minWidthToWrap = 40;
|
|
180
|
+
this.sortSubcommands = false;
|
|
181
|
+
this.sortOptions = false;
|
|
182
|
+
this.showGlobalOptions = false;
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
|
|
186
|
+
* and just before calling `formatHelp()`.
|
|
187
|
+
*
|
|
188
|
+
* Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
|
|
189
|
+
*
|
|
190
|
+
* @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
|
|
191
|
+
*/
|
|
192
|
+
prepareContext(contextOptions) {
|
|
193
|
+
this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
|
|
197
|
+
*
|
|
198
|
+
* @param {Command} cmd
|
|
199
|
+
* @returns {Command[]}
|
|
200
|
+
*/
|
|
201
|
+
visibleCommands(cmd) {
|
|
202
|
+
const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);
|
|
203
|
+
const helpCommand = cmd._getHelpCommand();
|
|
204
|
+
if (helpCommand && !helpCommand._hidden) visibleCommands.push(helpCommand);
|
|
205
|
+
if (this.sortSubcommands) visibleCommands.sort((a, b) => {
|
|
206
|
+
return a.name().localeCompare(b.name());
|
|
207
|
+
});
|
|
208
|
+
return visibleCommands;
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Compare options for sort.
|
|
212
|
+
*
|
|
213
|
+
* @param {Option} a
|
|
214
|
+
* @param {Option} b
|
|
215
|
+
* @returns {number}
|
|
216
|
+
*/
|
|
217
|
+
compareOptions(a, b) {
|
|
218
|
+
const getSortKey = (option) => {
|
|
219
|
+
return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
|
|
220
|
+
};
|
|
221
|
+
return getSortKey(a).localeCompare(getSortKey(b));
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
|
|
225
|
+
*
|
|
226
|
+
* @param {Command} cmd
|
|
227
|
+
* @returns {Option[]}
|
|
228
|
+
*/
|
|
229
|
+
visibleOptions(cmd) {
|
|
230
|
+
const visibleOptions = cmd.options.filter((option) => !option.hidden);
|
|
231
|
+
const helpOption = cmd._getHelpOption();
|
|
232
|
+
if (helpOption && !helpOption.hidden) {
|
|
233
|
+
const removeShort = helpOption.short && cmd._findOption(helpOption.short);
|
|
234
|
+
const removeLong = helpOption.long && cmd._findOption(helpOption.long);
|
|
235
|
+
if (!removeShort && !removeLong) visibleOptions.push(helpOption);
|
|
236
|
+
else if (helpOption.long && !removeLong) visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
|
|
237
|
+
else if (helpOption.short && !removeShort) visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
|
|
238
|
+
}
|
|
239
|
+
if (this.sortOptions) visibleOptions.sort(this.compareOptions);
|
|
240
|
+
return visibleOptions;
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Get an array of the visible global options. (Not including help.)
|
|
244
|
+
*
|
|
245
|
+
* @param {Command} cmd
|
|
246
|
+
* @returns {Option[]}
|
|
247
|
+
*/
|
|
248
|
+
visibleGlobalOptions(cmd) {
|
|
249
|
+
if (!this.showGlobalOptions) return [];
|
|
250
|
+
const globalOptions = [];
|
|
251
|
+
for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
|
|
252
|
+
const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
|
|
253
|
+
globalOptions.push(...visibleOptions);
|
|
254
|
+
}
|
|
255
|
+
if (this.sortOptions) globalOptions.sort(this.compareOptions);
|
|
256
|
+
return globalOptions;
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Get an array of the arguments if any have a description.
|
|
260
|
+
*
|
|
261
|
+
* @param {Command} cmd
|
|
262
|
+
* @returns {Argument[]}
|
|
263
|
+
*/
|
|
264
|
+
visibleArguments(cmd) {
|
|
265
|
+
if (cmd._argsDescription) cmd.registeredArguments.forEach((argument) => {
|
|
266
|
+
argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
|
|
267
|
+
});
|
|
268
|
+
if (cmd.registeredArguments.find((argument) => argument.description)) return cmd.registeredArguments;
|
|
269
|
+
return [];
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* Get the command term to show in the list of subcommands.
|
|
273
|
+
*
|
|
274
|
+
* @param {Command} cmd
|
|
275
|
+
* @returns {string}
|
|
276
|
+
*/
|
|
277
|
+
subcommandTerm(cmd) {
|
|
278
|
+
const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
|
|
279
|
+
return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Get the option term to show in the list of options.
|
|
283
|
+
*
|
|
284
|
+
* @param {Option} option
|
|
285
|
+
* @returns {string}
|
|
286
|
+
*/
|
|
287
|
+
optionTerm(option) {
|
|
288
|
+
return option.flags;
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* Get the argument term to show in the list of arguments.
|
|
292
|
+
*
|
|
293
|
+
* @param {Argument} argument
|
|
294
|
+
* @returns {string}
|
|
295
|
+
*/
|
|
296
|
+
argumentTerm(argument) {
|
|
297
|
+
return argument.name();
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Get the longest command term length.
|
|
301
|
+
*
|
|
302
|
+
* @param {Command} cmd
|
|
303
|
+
* @param {Help} helper
|
|
304
|
+
* @returns {number}
|
|
305
|
+
*/
|
|
306
|
+
longestSubcommandTermLength(cmd, helper) {
|
|
307
|
+
return helper.visibleCommands(cmd).reduce((max, command) => {
|
|
308
|
+
return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
|
|
309
|
+
}, 0);
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Get the longest option term length.
|
|
313
|
+
*
|
|
314
|
+
* @param {Command} cmd
|
|
315
|
+
* @param {Help} helper
|
|
316
|
+
* @returns {number}
|
|
317
|
+
*/
|
|
318
|
+
longestOptionTermLength(cmd, helper) {
|
|
319
|
+
return helper.visibleOptions(cmd).reduce((max, option) => {
|
|
320
|
+
return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
|
|
321
|
+
}, 0);
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* Get the longest global option term length.
|
|
325
|
+
*
|
|
326
|
+
* @param {Command} cmd
|
|
327
|
+
* @param {Help} helper
|
|
328
|
+
* @returns {number}
|
|
329
|
+
*/
|
|
330
|
+
longestGlobalOptionTermLength(cmd, helper) {
|
|
331
|
+
return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
|
|
332
|
+
return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
|
|
333
|
+
}, 0);
|
|
334
|
+
}
|
|
335
|
+
/**
|
|
336
|
+
* Get the longest argument term length.
|
|
337
|
+
*
|
|
338
|
+
* @param {Command} cmd
|
|
339
|
+
* @param {Help} helper
|
|
340
|
+
* @returns {number}
|
|
341
|
+
*/
|
|
342
|
+
longestArgumentTermLength(cmd, helper) {
|
|
343
|
+
return helper.visibleArguments(cmd).reduce((max, argument) => {
|
|
344
|
+
return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
|
|
345
|
+
}, 0);
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* Get the command usage to be displayed at the top of the built-in help.
|
|
349
|
+
*
|
|
350
|
+
* @param {Command} cmd
|
|
351
|
+
* @returns {string}
|
|
352
|
+
*/
|
|
353
|
+
commandUsage(cmd) {
|
|
354
|
+
let cmdName = cmd._name;
|
|
355
|
+
if (cmd._aliases[0]) cmdName = cmdName + "|" + cmd._aliases[0];
|
|
356
|
+
let ancestorCmdNames = "";
|
|
357
|
+
for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
|
|
358
|
+
return ancestorCmdNames + cmdName + " " + cmd.usage();
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Get the description for the command.
|
|
362
|
+
*
|
|
363
|
+
* @param {Command} cmd
|
|
364
|
+
* @returns {string}
|
|
365
|
+
*/
|
|
366
|
+
commandDescription(cmd) {
|
|
367
|
+
return cmd.description();
|
|
368
|
+
}
|
|
369
|
+
/**
|
|
370
|
+
* Get the subcommand summary to show in the list of subcommands.
|
|
371
|
+
* (Fallback to description for backwards compatibility.)
|
|
372
|
+
*
|
|
373
|
+
* @param {Command} cmd
|
|
374
|
+
* @returns {string}
|
|
375
|
+
*/
|
|
376
|
+
subcommandDescription(cmd) {
|
|
377
|
+
return cmd.summary() || cmd.description();
|
|
378
|
+
}
|
|
379
|
+
/**
|
|
380
|
+
* Get the option description to show in the list of options.
|
|
381
|
+
*
|
|
382
|
+
* @param {Option} option
|
|
383
|
+
* @return {string}
|
|
384
|
+
*/
|
|
385
|
+
optionDescription(option) {
|
|
386
|
+
const extraInfo = [];
|
|
387
|
+
if (option.argChoices) extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
|
|
388
|
+
if (option.defaultValue !== void 0) {
|
|
389
|
+
if (option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean") extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
|
|
390
|
+
}
|
|
391
|
+
if (option.presetArg !== void 0 && option.optional) extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
|
|
392
|
+
if (option.envVar !== void 0) extraInfo.push(`env: ${option.envVar}`);
|
|
393
|
+
if (extraInfo.length > 0) {
|
|
394
|
+
const extraDescription = `(${extraInfo.join(", ")})`;
|
|
395
|
+
if (option.description) return `${option.description} ${extraDescription}`;
|
|
396
|
+
return extraDescription;
|
|
397
|
+
}
|
|
398
|
+
return option.description;
|
|
399
|
+
}
|
|
400
|
+
/**
|
|
401
|
+
* Get the argument description to show in the list of arguments.
|
|
402
|
+
*
|
|
403
|
+
* @param {Argument} argument
|
|
404
|
+
* @return {string}
|
|
405
|
+
*/
|
|
406
|
+
argumentDescription(argument) {
|
|
407
|
+
const extraInfo = [];
|
|
408
|
+
if (argument.argChoices) extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
|
|
409
|
+
if (argument.defaultValue !== void 0) extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
|
|
410
|
+
if (extraInfo.length > 0) {
|
|
411
|
+
const extraDescription = `(${extraInfo.join(", ")})`;
|
|
412
|
+
if (argument.description) return `${argument.description} ${extraDescription}`;
|
|
413
|
+
return extraDescription;
|
|
414
|
+
}
|
|
415
|
+
return argument.description;
|
|
416
|
+
}
|
|
417
|
+
/**
|
|
418
|
+
* Format a list of items, given a heading and an array of formatted items.
|
|
419
|
+
*
|
|
420
|
+
* @param {string} heading
|
|
421
|
+
* @param {string[]} items
|
|
422
|
+
* @param {Help} helper
|
|
423
|
+
* @returns string[]
|
|
424
|
+
*/
|
|
425
|
+
formatItemList(heading, items, helper) {
|
|
426
|
+
if (items.length === 0) return [];
|
|
427
|
+
return [
|
|
428
|
+
helper.styleTitle(heading),
|
|
429
|
+
...items,
|
|
430
|
+
""
|
|
431
|
+
];
|
|
432
|
+
}
|
|
433
|
+
/**
|
|
434
|
+
* Group items by their help group heading.
|
|
435
|
+
*
|
|
436
|
+
* @param {Command[] | Option[]} unsortedItems
|
|
437
|
+
* @param {Command[] | Option[]} visibleItems
|
|
438
|
+
* @param {Function} getGroup
|
|
439
|
+
* @returns {Map<string, Command[] | Option[]>}
|
|
440
|
+
*/
|
|
441
|
+
groupItems(unsortedItems, visibleItems, getGroup) {
|
|
442
|
+
const result = /* @__PURE__ */ new Map();
|
|
443
|
+
unsortedItems.forEach((item) => {
|
|
444
|
+
const group = getGroup(item);
|
|
445
|
+
if (!result.has(group)) result.set(group, []);
|
|
446
|
+
});
|
|
447
|
+
visibleItems.forEach((item) => {
|
|
448
|
+
const group = getGroup(item);
|
|
449
|
+
if (!result.has(group)) result.set(group, []);
|
|
450
|
+
result.get(group).push(item);
|
|
451
|
+
});
|
|
452
|
+
return result;
|
|
453
|
+
}
|
|
454
|
+
/**
|
|
455
|
+
* Generate the built-in help text.
|
|
456
|
+
*
|
|
457
|
+
* @param {Command} cmd
|
|
458
|
+
* @param {Help} helper
|
|
459
|
+
* @returns {string}
|
|
460
|
+
*/
|
|
461
|
+
formatHelp(cmd, helper) {
|
|
462
|
+
const termWidth = helper.padWidth(cmd, helper);
|
|
463
|
+
const helpWidth = helper.helpWidth ?? 80;
|
|
464
|
+
function callFormatItem(term, description) {
|
|
465
|
+
return helper.formatItem(term, termWidth, description, helper);
|
|
466
|
+
}
|
|
467
|
+
let output = [`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`, ""];
|
|
468
|
+
const commandDescription = helper.commandDescription(cmd);
|
|
469
|
+
if (commandDescription.length > 0) output = output.concat([helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth), ""]);
|
|
470
|
+
const argumentList = helper.visibleArguments(cmd).map((argument) => {
|
|
471
|
+
return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
|
|
472
|
+
});
|
|
473
|
+
output = output.concat(this.formatItemList("Arguments:", argumentList, helper));
|
|
474
|
+
this.groupItems(cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? "Options:").forEach((options, group) => {
|
|
475
|
+
const optionList = options.map((option) => {
|
|
476
|
+
return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
|
|
477
|
+
});
|
|
478
|
+
output = output.concat(this.formatItemList(group, optionList, helper));
|
|
479
|
+
});
|
|
480
|
+
if (helper.showGlobalOptions) {
|
|
481
|
+
const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
|
|
482
|
+
return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
|
|
483
|
+
});
|
|
484
|
+
output = output.concat(this.formatItemList("Global Options:", globalOptionList, helper));
|
|
485
|
+
}
|
|
486
|
+
this.groupItems(cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || "Commands:").forEach((commands, group) => {
|
|
487
|
+
const commandList = commands.map((sub) => {
|
|
488
|
+
return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)));
|
|
489
|
+
});
|
|
490
|
+
output = output.concat(this.formatItemList(group, commandList, helper));
|
|
491
|
+
});
|
|
492
|
+
return output.join("\n");
|
|
493
|
+
}
|
|
494
|
+
/**
|
|
495
|
+
* Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
|
|
496
|
+
*
|
|
497
|
+
* @param {string} str
|
|
498
|
+
* @returns {number}
|
|
499
|
+
*/
|
|
500
|
+
displayWidth(str) {
|
|
501
|
+
return stripVTControlCharacters(str).length;
|
|
502
|
+
}
|
|
503
|
+
/**
|
|
504
|
+
* Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
|
|
505
|
+
*
|
|
506
|
+
* @param {string} str
|
|
507
|
+
* @returns {string}
|
|
508
|
+
*/
|
|
509
|
+
styleTitle(str) {
|
|
510
|
+
return str;
|
|
511
|
+
}
|
|
512
|
+
styleUsage(str) {
|
|
513
|
+
return str.split(" ").map((word) => {
|
|
514
|
+
if (word === "[options]") return this.styleOptionText(word);
|
|
515
|
+
if (word === "[command]") return this.styleSubcommandText(word);
|
|
516
|
+
if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
|
|
517
|
+
return this.styleCommandText(word);
|
|
518
|
+
}).join(" ");
|
|
519
|
+
}
|
|
520
|
+
styleCommandDescription(str) {
|
|
521
|
+
return this.styleDescriptionText(str);
|
|
522
|
+
}
|
|
523
|
+
styleOptionDescription(str) {
|
|
524
|
+
return this.styleDescriptionText(str);
|
|
525
|
+
}
|
|
526
|
+
styleSubcommandDescription(str) {
|
|
527
|
+
return this.styleDescriptionText(str);
|
|
528
|
+
}
|
|
529
|
+
styleArgumentDescription(str) {
|
|
530
|
+
return this.styleDescriptionText(str);
|
|
531
|
+
}
|
|
532
|
+
styleDescriptionText(str) {
|
|
533
|
+
return str;
|
|
534
|
+
}
|
|
535
|
+
styleOptionTerm(str) {
|
|
536
|
+
return this.styleOptionText(str);
|
|
537
|
+
}
|
|
538
|
+
styleSubcommandTerm(str) {
|
|
539
|
+
return str.split(" ").map((word) => {
|
|
540
|
+
if (word === "[options]") return this.styleOptionText(word);
|
|
541
|
+
if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
|
|
542
|
+
return this.styleSubcommandText(word);
|
|
543
|
+
}).join(" ");
|
|
544
|
+
}
|
|
545
|
+
styleArgumentTerm(str) {
|
|
546
|
+
return this.styleArgumentText(str);
|
|
547
|
+
}
|
|
548
|
+
styleOptionText(str) {
|
|
549
|
+
return str;
|
|
550
|
+
}
|
|
551
|
+
styleArgumentText(str) {
|
|
552
|
+
return str;
|
|
553
|
+
}
|
|
554
|
+
styleSubcommandText(str) {
|
|
555
|
+
return str;
|
|
556
|
+
}
|
|
557
|
+
styleCommandText(str) {
|
|
558
|
+
return str;
|
|
559
|
+
}
|
|
560
|
+
/**
|
|
561
|
+
* Calculate the pad width from the maximum term length.
|
|
562
|
+
*
|
|
563
|
+
* @param {Command} cmd
|
|
564
|
+
* @param {Help} helper
|
|
565
|
+
* @returns {number}
|
|
566
|
+
*/
|
|
567
|
+
padWidth(cmd, helper) {
|
|
568
|
+
return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
|
|
569
|
+
}
|
|
570
|
+
/**
|
|
571
|
+
* Detect manually wrapped and indented strings by checking for line break followed by whitespace.
|
|
572
|
+
*
|
|
573
|
+
* @param {string} str
|
|
574
|
+
* @returns {boolean}
|
|
575
|
+
*/
|
|
576
|
+
preformatted(str) {
|
|
577
|
+
return /\n[^\S\r\n]/.test(str);
|
|
578
|
+
}
|
|
579
|
+
/**
|
|
580
|
+
* Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
|
|
581
|
+
*
|
|
582
|
+
* So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
|
|
583
|
+
* TTT DDD DDDD
|
|
584
|
+
* DD DDD
|
|
585
|
+
*
|
|
586
|
+
* @param {string} term
|
|
587
|
+
* @param {number} termWidth
|
|
588
|
+
* @param {string} description
|
|
589
|
+
* @param {Help} helper
|
|
590
|
+
* @returns {string}
|
|
591
|
+
*/
|
|
592
|
+
formatItem(term, termWidth, description, helper) {
|
|
593
|
+
const itemIndent = 2;
|
|
594
|
+
const itemIndentStr = " ".repeat(itemIndent);
|
|
595
|
+
if (!description) return itemIndentStr + term;
|
|
596
|
+
const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
|
|
597
|
+
const spacerWidth = 2;
|
|
598
|
+
const remainingWidth = (this.helpWidth ?? 80) - termWidth - spacerWidth - itemIndent;
|
|
599
|
+
let formattedDescription;
|
|
600
|
+
if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) formattedDescription = description;
|
|
601
|
+
else formattedDescription = helper.boxWrap(description, remainingWidth).replace(/\n/g, "\n" + " ".repeat(termWidth + spacerWidth));
|
|
602
|
+
return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `\n${itemIndentStr}`);
|
|
603
|
+
}
|
|
604
|
+
/**
|
|
605
|
+
* Wrap a string at whitespace, preserving existing line breaks.
|
|
606
|
+
* Wrapping is skipped if the width is less than `minWidthToWrap`.
|
|
607
|
+
*
|
|
608
|
+
* @param {string} str
|
|
609
|
+
* @param {number} width
|
|
610
|
+
* @returns {string}
|
|
611
|
+
*/
|
|
612
|
+
boxWrap(str, width) {
|
|
613
|
+
if (width < this.minWidthToWrap) return str;
|
|
614
|
+
const rawLines = str.split(/\r\n|\n/);
|
|
615
|
+
const chunkPattern = /[\s]*[^\s]+/g;
|
|
616
|
+
const wrappedLines = [];
|
|
617
|
+
rawLines.forEach((line) => {
|
|
618
|
+
const chunks = line.match(chunkPattern);
|
|
619
|
+
if (chunks === null) {
|
|
620
|
+
wrappedLines.push("");
|
|
621
|
+
return;
|
|
622
|
+
}
|
|
623
|
+
let sumChunks = [chunks.shift()];
|
|
624
|
+
let sumWidth = this.displayWidth(sumChunks[0]);
|
|
625
|
+
chunks.forEach((chunk) => {
|
|
626
|
+
const visibleWidth = this.displayWidth(chunk);
|
|
627
|
+
if (sumWidth + visibleWidth <= width) {
|
|
628
|
+
sumChunks.push(chunk);
|
|
629
|
+
sumWidth += visibleWidth;
|
|
630
|
+
return;
|
|
631
|
+
}
|
|
632
|
+
wrappedLines.push(sumChunks.join(""));
|
|
633
|
+
const nextChunk = chunk.trimStart();
|
|
634
|
+
sumChunks = [nextChunk];
|
|
635
|
+
sumWidth = this.displayWidth(nextChunk);
|
|
636
|
+
});
|
|
637
|
+
wrappedLines.push(sumChunks.join(""));
|
|
638
|
+
});
|
|
639
|
+
return wrappedLines.join("\n");
|
|
640
|
+
}
|
|
641
|
+
};
|
|
642
|
+
//#endregion
|
|
643
|
+
//#region ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/option.js
|
|
644
|
+
var Option = class {
|
|
645
|
+
/**
|
|
646
|
+
* Initialize a new `Option` with the given `flags` and `description`.
|
|
647
|
+
*
|
|
648
|
+
* @param {string} flags
|
|
649
|
+
* @param {string} [description]
|
|
650
|
+
*/
|
|
651
|
+
constructor(flags, description) {
|
|
652
|
+
this.flags = flags;
|
|
653
|
+
this.description = description || "";
|
|
654
|
+
this.required = flags.includes("<");
|
|
655
|
+
this.optional = flags.includes("[");
|
|
656
|
+
this.variadic = /\w\.\.\.[>\]]$/.test(flags);
|
|
657
|
+
this.mandatory = false;
|
|
658
|
+
const optionFlags = splitOptionFlags(flags);
|
|
659
|
+
this.short = optionFlags.shortFlag;
|
|
660
|
+
this.long = optionFlags.longFlag;
|
|
661
|
+
this.negate = false;
|
|
662
|
+
if (this.long) this.negate = this.long.startsWith("--no-");
|
|
663
|
+
this.defaultValue = void 0;
|
|
664
|
+
this.defaultValueDescription = void 0;
|
|
665
|
+
this.presetArg = void 0;
|
|
666
|
+
this.envVar = void 0;
|
|
667
|
+
this.parseArg = void 0;
|
|
668
|
+
this.hidden = false;
|
|
669
|
+
this.argChoices = void 0;
|
|
670
|
+
this.conflictsWith = [];
|
|
671
|
+
this.implied = void 0;
|
|
672
|
+
this.helpGroupHeading = void 0;
|
|
673
|
+
}
|
|
674
|
+
/**
|
|
675
|
+
* Set the default value, and optionally supply the description to be displayed in the help.
|
|
676
|
+
*
|
|
677
|
+
* @param {*} value
|
|
678
|
+
* @param {string} [description]
|
|
679
|
+
* @return {Option}
|
|
680
|
+
*/
|
|
681
|
+
default(value, description) {
|
|
682
|
+
this.defaultValue = value;
|
|
683
|
+
this.defaultValueDescription = description;
|
|
684
|
+
return this;
|
|
685
|
+
}
|
|
686
|
+
/**
|
|
687
|
+
* Preset to use when option used without option-argument, especially optional but also boolean and negated.
|
|
688
|
+
* The custom processing (parseArg) is called.
|
|
689
|
+
*
|
|
690
|
+
* @example
|
|
691
|
+
* new Option('--color').default('GREYSCALE').preset('RGB');
|
|
692
|
+
* new Option('--donate [amount]').preset('20').argParser(parseFloat);
|
|
693
|
+
*
|
|
694
|
+
* @param {*} arg
|
|
695
|
+
* @return {Option}
|
|
696
|
+
*/
|
|
697
|
+
preset(arg) {
|
|
698
|
+
this.presetArg = arg;
|
|
699
|
+
return this;
|
|
700
|
+
}
|
|
701
|
+
/**
|
|
702
|
+
* Add option name(s) that conflict with this option.
|
|
703
|
+
* An error will be displayed if conflicting options are found during parsing.
|
|
704
|
+
*
|
|
705
|
+
* @example
|
|
706
|
+
* new Option('--rgb').conflicts('cmyk');
|
|
707
|
+
* new Option('--js').conflicts(['ts', 'jsx']);
|
|
708
|
+
*
|
|
709
|
+
* @param {(string | string[])} names
|
|
710
|
+
* @return {Option}
|
|
711
|
+
*/
|
|
712
|
+
conflicts(names) {
|
|
713
|
+
this.conflictsWith = this.conflictsWith.concat(names);
|
|
714
|
+
return this;
|
|
715
|
+
}
|
|
716
|
+
/**
|
|
717
|
+
* Specify implied option values for when this option is set and the implied options are not.
|
|
718
|
+
*
|
|
719
|
+
* The custom processing (parseArg) is not called on the implied values.
|
|
720
|
+
*
|
|
721
|
+
* @example
|
|
722
|
+
* program
|
|
723
|
+
* .addOption(new Option('--log', 'write logging information to file'))
|
|
724
|
+
* .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
|
|
725
|
+
*
|
|
726
|
+
* @param {object} impliedOptionValues
|
|
727
|
+
* @return {Option}
|
|
728
|
+
*/
|
|
729
|
+
implies(impliedOptionValues) {
|
|
730
|
+
let newImplied = impliedOptionValues;
|
|
731
|
+
if (typeof impliedOptionValues === "string") newImplied = { [impliedOptionValues]: true };
|
|
732
|
+
this.implied = Object.assign(this.implied || {}, newImplied);
|
|
733
|
+
return this;
|
|
734
|
+
}
|
|
735
|
+
/**
|
|
736
|
+
* Set environment variable to check for option value.
|
|
737
|
+
*
|
|
738
|
+
* An environment variable is only used if when processed the current option value is
|
|
739
|
+
* undefined, or the source of the current value is 'default' or 'config' or 'env'.
|
|
740
|
+
*
|
|
741
|
+
* @param {string} name
|
|
742
|
+
* @return {Option}
|
|
743
|
+
*/
|
|
744
|
+
env(name) {
|
|
745
|
+
this.envVar = name;
|
|
746
|
+
return this;
|
|
747
|
+
}
|
|
748
|
+
/**
|
|
749
|
+
* Set the custom handler for processing CLI option arguments into option values.
|
|
750
|
+
*
|
|
751
|
+
* @param {Function} [fn]
|
|
752
|
+
* @return {Option}
|
|
753
|
+
*/
|
|
754
|
+
argParser(fn) {
|
|
755
|
+
this.parseArg = fn;
|
|
756
|
+
return this;
|
|
757
|
+
}
|
|
758
|
+
/**
|
|
759
|
+
* Whether the option is mandatory and must have a value after parsing.
|
|
760
|
+
*
|
|
761
|
+
* @param {boolean} [mandatory=true]
|
|
762
|
+
* @return {Option}
|
|
763
|
+
*/
|
|
764
|
+
makeOptionMandatory(mandatory = true) {
|
|
765
|
+
this.mandatory = !!mandatory;
|
|
766
|
+
return this;
|
|
767
|
+
}
|
|
768
|
+
/**
|
|
769
|
+
* Hide option in help.
|
|
770
|
+
*
|
|
771
|
+
* @param {boolean} [hide=true]
|
|
772
|
+
* @return {Option}
|
|
773
|
+
*/
|
|
774
|
+
hideHelp(hide = true) {
|
|
775
|
+
this.hidden = !!hide;
|
|
776
|
+
return this;
|
|
777
|
+
}
|
|
778
|
+
/**
|
|
779
|
+
* @package
|
|
780
|
+
*/
|
|
781
|
+
_collectValue(value, previous) {
|
|
782
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) return [value];
|
|
783
|
+
previous.push(value);
|
|
784
|
+
return previous;
|
|
785
|
+
}
|
|
786
|
+
/**
|
|
787
|
+
* Only allow option value to be one of choices.
|
|
788
|
+
*
|
|
789
|
+
* @param {string[]} values
|
|
790
|
+
* @return {Option}
|
|
791
|
+
*/
|
|
792
|
+
choices(values) {
|
|
793
|
+
this.argChoices = values.slice();
|
|
794
|
+
this.parseArg = (arg, previous) => {
|
|
795
|
+
if (!this.argChoices.includes(arg)) throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
|
|
796
|
+
if (this.variadic) return this._collectValue(arg, previous);
|
|
797
|
+
return arg;
|
|
798
|
+
};
|
|
799
|
+
return this;
|
|
800
|
+
}
|
|
801
|
+
/**
|
|
802
|
+
* Return option name.
|
|
803
|
+
*
|
|
804
|
+
* @return {string}
|
|
805
|
+
*/
|
|
806
|
+
name() {
|
|
807
|
+
if (this.long) return this.long.replace(/^--/, "");
|
|
808
|
+
return this.short.replace(/^-/, "");
|
|
809
|
+
}
|
|
810
|
+
/**
|
|
811
|
+
* Return option name, in a camelcase format that can be used
|
|
812
|
+
* as an object attribute key.
|
|
813
|
+
*
|
|
814
|
+
* @return {string}
|
|
815
|
+
*/
|
|
816
|
+
attributeName() {
|
|
817
|
+
if (this.negate) return camelcase(this.name().replace(/^no-/, ""));
|
|
818
|
+
return camelcase(this.name());
|
|
819
|
+
}
|
|
820
|
+
/**
|
|
821
|
+
* Set the help group heading.
|
|
822
|
+
*
|
|
823
|
+
* @param {string} heading
|
|
824
|
+
* @return {Option}
|
|
825
|
+
*/
|
|
826
|
+
helpGroup(heading) {
|
|
827
|
+
this.helpGroupHeading = heading;
|
|
828
|
+
return this;
|
|
829
|
+
}
|
|
830
|
+
/**
|
|
831
|
+
* Check if `arg` matches the short or long flag.
|
|
832
|
+
*
|
|
833
|
+
* @param {string} arg
|
|
834
|
+
* @return {boolean}
|
|
835
|
+
* @package
|
|
836
|
+
*/
|
|
837
|
+
is(arg) {
|
|
838
|
+
return this.short === arg || this.long === arg;
|
|
839
|
+
}
|
|
840
|
+
/**
|
|
841
|
+
* Return whether a boolean option.
|
|
842
|
+
*
|
|
843
|
+
* Options are one of boolean, negated, required argument, or optional argument.
|
|
844
|
+
*
|
|
845
|
+
* @return {boolean}
|
|
846
|
+
* @package
|
|
847
|
+
*/
|
|
848
|
+
isBoolean() {
|
|
849
|
+
return !this.required && !this.optional && !this.negate;
|
|
850
|
+
}
|
|
851
|
+
};
|
|
852
|
+
/**
|
|
853
|
+
* This class is to make it easier to work with dual options, without changing the existing
|
|
854
|
+
* implementation. We support separate dual options for separate positive and negative options,
|
|
855
|
+
* like `--build` and `--no-build`, which share a single option value. This works nicely for some
|
|
856
|
+
* use cases, but is tricky for others where we want separate behaviours despite
|
|
857
|
+
* the single shared option value.
|
|
858
|
+
*/
|
|
859
|
+
var DualOptions = class {
|
|
860
|
+
/**
|
|
861
|
+
* @param {Option[]} options
|
|
862
|
+
*/
|
|
863
|
+
constructor(options) {
|
|
864
|
+
this.positiveOptions = /* @__PURE__ */ new Map();
|
|
865
|
+
this.negativeOptions = /* @__PURE__ */ new Map();
|
|
866
|
+
this.dualOptions = /* @__PURE__ */ new Set();
|
|
867
|
+
options.forEach((option) => {
|
|
868
|
+
if (option.negate) this.negativeOptions.set(option.attributeName(), option);
|
|
869
|
+
else this.positiveOptions.set(option.attributeName(), option);
|
|
870
|
+
});
|
|
871
|
+
this.negativeOptions.forEach((value, key) => {
|
|
872
|
+
if (this.positiveOptions.has(key)) this.dualOptions.add(key);
|
|
873
|
+
});
|
|
874
|
+
}
|
|
875
|
+
/**
|
|
876
|
+
* Did the value come from the option, and not from possible matching dual option?
|
|
877
|
+
*
|
|
878
|
+
* @param {*} value
|
|
879
|
+
* @param {Option} option
|
|
880
|
+
* @returns {boolean}
|
|
881
|
+
*/
|
|
882
|
+
valueFromOption(value, option) {
|
|
883
|
+
const optionKey = option.attributeName();
|
|
884
|
+
if (!this.dualOptions.has(optionKey)) return true;
|
|
885
|
+
const preset = this.negativeOptions.get(optionKey).presetArg;
|
|
886
|
+
const negativeValue = preset !== void 0 ? preset : false;
|
|
887
|
+
return option.negate === (negativeValue === value);
|
|
888
|
+
}
|
|
889
|
+
};
|
|
890
|
+
/**
|
|
891
|
+
* Convert string from kebab-case to camelCase.
|
|
892
|
+
*
|
|
893
|
+
* @param {string} str
|
|
894
|
+
* @return {string}
|
|
895
|
+
* @private
|
|
896
|
+
*/
|
|
897
|
+
function camelcase(str) {
|
|
898
|
+
return str.split("-").reduce((str, word) => {
|
|
899
|
+
return str + word[0].toUpperCase() + word.slice(1);
|
|
900
|
+
});
|
|
901
|
+
}
|
|
902
|
+
/**
|
|
903
|
+
* Split the short and long flag out of something like '-m,--mixed <value>'
|
|
904
|
+
*
|
|
905
|
+
* @private
|
|
906
|
+
*/
|
|
907
|
+
function splitOptionFlags(flags) {
|
|
908
|
+
let shortFlag;
|
|
909
|
+
let longFlag;
|
|
910
|
+
const shortFlagExp = /^-[^-]$/;
|
|
911
|
+
const longFlagExp = /^--[^-]/;
|
|
912
|
+
const flagParts = flags.split(/[ |,]+/).concat("guard");
|
|
913
|
+
if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
|
|
914
|
+
if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
|
|
915
|
+
if (!shortFlag && shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
|
|
916
|
+
if (!shortFlag && longFlagExp.test(flagParts[0])) {
|
|
917
|
+
shortFlag = longFlag;
|
|
918
|
+
longFlag = flagParts.shift();
|
|
919
|
+
}
|
|
920
|
+
if (flagParts[0].startsWith("-")) {
|
|
921
|
+
const unsupportedFlag = flagParts[0];
|
|
922
|
+
const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
|
|
923
|
+
if (/^-[^-][^-]/.test(unsupportedFlag)) throw new Error(`${baseError}
|
|
924
|
+
- a short flag is a single dash and a single character
|
|
925
|
+
- either use a single dash and a single character (for a short flag)
|
|
926
|
+
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
|
|
927
|
+
if (shortFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
|
|
928
|
+
- too many short flags`);
|
|
929
|
+
if (longFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
|
|
930
|
+
- too many long flags`);
|
|
931
|
+
throw new Error(`${baseError}
|
|
932
|
+
- unrecognised flag format`);
|
|
933
|
+
}
|
|
934
|
+
if (shortFlag === void 0 && longFlag === void 0) throw new Error(`option creation failed due to no flags found in '${flags}'.`);
|
|
935
|
+
return {
|
|
936
|
+
shortFlag,
|
|
937
|
+
longFlag
|
|
938
|
+
};
|
|
939
|
+
}
|
|
940
|
+
//#endregion
|
|
941
|
+
//#region ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/suggestSimilar.js
|
|
942
|
+
const maxDistance = 3;
|
|
943
|
+
function editDistance(a, b) {
|
|
944
|
+
if (Math.abs(a.length - b.length) > maxDistance) return Math.max(a.length, b.length);
|
|
945
|
+
const d = [];
|
|
946
|
+
for (let i = 0; i <= a.length; i++) d[i] = [i];
|
|
947
|
+
for (let j = 0; j <= b.length; j++) d[0][j] = j;
|
|
948
|
+
for (let j = 1; j <= b.length; j++) for (let i = 1; i <= a.length; i++) {
|
|
949
|
+
let cost;
|
|
950
|
+
if (a[i - 1] === b[j - 1]) cost = 0;
|
|
951
|
+
else cost = 1;
|
|
952
|
+
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
|
|
953
|
+
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);
|
|
954
|
+
}
|
|
955
|
+
return d[a.length][b.length];
|
|
956
|
+
}
|
|
957
|
+
/**
|
|
958
|
+
* Find close matches, restricted to same number of edits.
|
|
959
|
+
*
|
|
960
|
+
* @param {string} word
|
|
961
|
+
* @param {string[]} candidates
|
|
962
|
+
* @returns {string}
|
|
963
|
+
*/
|
|
964
|
+
function suggestSimilar(word, candidates) {
|
|
965
|
+
if (!candidates || candidates.length === 0) return "";
|
|
966
|
+
candidates = Array.from(new Set(candidates));
|
|
967
|
+
const searchingOptions = word.startsWith("--");
|
|
968
|
+
if (searchingOptions) {
|
|
969
|
+
word = word.slice(2);
|
|
970
|
+
candidates = candidates.map((candidate) => candidate.slice(2));
|
|
971
|
+
}
|
|
972
|
+
let similar = [];
|
|
973
|
+
let bestDistance = maxDistance;
|
|
974
|
+
const minSimilarity = .4;
|
|
975
|
+
candidates.forEach((candidate) => {
|
|
976
|
+
if (candidate.length <= 1) return;
|
|
977
|
+
const distance = editDistance(word, candidate);
|
|
978
|
+
const length = Math.max(word.length, candidate.length);
|
|
979
|
+
if ((length - distance) / length > minSimilarity) {
|
|
980
|
+
if (distance < bestDistance) {
|
|
981
|
+
bestDistance = distance;
|
|
982
|
+
similar = [candidate];
|
|
983
|
+
} else if (distance === bestDistance) similar.push(candidate);
|
|
984
|
+
}
|
|
985
|
+
});
|
|
986
|
+
similar.sort((a, b) => a.localeCompare(b));
|
|
987
|
+
if (searchingOptions) similar = similar.map((candidate) => `--${candidate}`);
|
|
988
|
+
if (similar.length > 1) return `\n(Did you mean one of ${similar.join(", ")}?)`;
|
|
989
|
+
if (similar.length === 1) return `\n(Did you mean ${similar[0]}?)`;
|
|
990
|
+
return "";
|
|
991
|
+
}
|
|
992
|
+
//#endregion
|
|
993
|
+
//#region ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/command.js
|
|
994
|
+
var Command = class Command extends EventEmitter {
|
|
995
|
+
/**
|
|
996
|
+
* Initialize a new `Command`.
|
|
997
|
+
*
|
|
998
|
+
* @param {string} [name]
|
|
999
|
+
*/
|
|
1000
|
+
constructor(name) {
|
|
1001
|
+
super();
|
|
1002
|
+
/** @type {Command[]} */
|
|
1003
|
+
this.commands = [];
|
|
1004
|
+
/** @type {Option[]} */
|
|
1005
|
+
this.options = [];
|
|
1006
|
+
this.parent = null;
|
|
1007
|
+
this._allowUnknownOption = false;
|
|
1008
|
+
this._allowExcessArguments = false;
|
|
1009
|
+
/** @type {Argument[]} */
|
|
1010
|
+
this.registeredArguments = [];
|
|
1011
|
+
this._args = this.registeredArguments;
|
|
1012
|
+
/** @type {string[]} */
|
|
1013
|
+
this.args = [];
|
|
1014
|
+
this.rawArgs = [];
|
|
1015
|
+
this.processedArgs = [];
|
|
1016
|
+
this._scriptPath = null;
|
|
1017
|
+
this._name = name || "";
|
|
1018
|
+
this._optionValues = {};
|
|
1019
|
+
this._optionValueSources = {};
|
|
1020
|
+
this._storeOptionsAsProperties = false;
|
|
1021
|
+
this._actionHandler = null;
|
|
1022
|
+
this._executableHandler = false;
|
|
1023
|
+
this._executableFile = null;
|
|
1024
|
+
this._executableDir = null;
|
|
1025
|
+
this._defaultCommandName = null;
|
|
1026
|
+
this._exitCallback = null;
|
|
1027
|
+
this._aliases = [];
|
|
1028
|
+
this._combineFlagAndOptionalValue = true;
|
|
1029
|
+
this._description = "";
|
|
1030
|
+
this._summary = "";
|
|
1031
|
+
this._argsDescription = void 0;
|
|
1032
|
+
this._enablePositionalOptions = false;
|
|
1033
|
+
this._passThroughOptions = false;
|
|
1034
|
+
this._lifeCycleHooks = {};
|
|
1035
|
+
/** @type {(boolean | string)} */
|
|
1036
|
+
this._showHelpAfterError = false;
|
|
1037
|
+
this._showSuggestionAfterError = true;
|
|
1038
|
+
this._savedState = null;
|
|
1039
|
+
this._outputConfiguration = {
|
|
1040
|
+
writeOut: (str) => process$1.stdout.write(str),
|
|
1041
|
+
writeErr: (str) => process$1.stderr.write(str),
|
|
1042
|
+
outputError: (str, write) => write(str),
|
|
1043
|
+
getOutHelpWidth: () => process$1.stdout.isTTY ? process$1.stdout.columns : void 0,
|
|
1044
|
+
getErrHelpWidth: () => process$1.stderr.isTTY ? process$1.stderr.columns : void 0,
|
|
1045
|
+
getOutHasColors: () => useColor() ?? (process$1.stdout.isTTY && process$1.stdout.hasColors?.()),
|
|
1046
|
+
getErrHasColors: () => useColor() ?? (process$1.stderr.isTTY && process$1.stderr.hasColors?.()),
|
|
1047
|
+
stripColor: (str) => stripVTControlCharacters(str)
|
|
1048
|
+
};
|
|
1049
|
+
this._hidden = false;
|
|
1050
|
+
/** @type {(Option | null | undefined)} */
|
|
1051
|
+
this._helpOption = void 0;
|
|
1052
|
+
this._addImplicitHelpCommand = void 0;
|
|
1053
|
+
/** @type {Command} */
|
|
1054
|
+
this._helpCommand = void 0;
|
|
1055
|
+
this._helpConfiguration = {};
|
|
1056
|
+
/** @type {string | undefined} */
|
|
1057
|
+
this._helpGroupHeading = void 0;
|
|
1058
|
+
/** @type {string | undefined} */
|
|
1059
|
+
this._defaultCommandGroup = void 0;
|
|
1060
|
+
/** @type {string | undefined} */
|
|
1061
|
+
this._defaultOptionGroup = void 0;
|
|
1062
|
+
}
|
|
1063
|
+
/**
|
|
1064
|
+
* Copy settings that are useful to have in common across root command and subcommands.
|
|
1065
|
+
*
|
|
1066
|
+
* (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
|
|
1067
|
+
*
|
|
1068
|
+
* @param {Command} sourceCommand
|
|
1069
|
+
* @return {Command} `this` command for chaining
|
|
1070
|
+
*/
|
|
1071
|
+
copyInheritedSettings(sourceCommand) {
|
|
1072
|
+
this._outputConfiguration = sourceCommand._outputConfiguration;
|
|
1073
|
+
this._helpOption = sourceCommand._helpOption;
|
|
1074
|
+
this._helpCommand = sourceCommand._helpCommand;
|
|
1075
|
+
this._helpConfiguration = sourceCommand._helpConfiguration;
|
|
1076
|
+
this._exitCallback = sourceCommand._exitCallback;
|
|
1077
|
+
this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
|
|
1078
|
+
this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
|
|
1079
|
+
this._allowExcessArguments = sourceCommand._allowExcessArguments;
|
|
1080
|
+
this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
|
|
1081
|
+
this._showHelpAfterError = sourceCommand._showHelpAfterError;
|
|
1082
|
+
this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
|
|
1083
|
+
return this;
|
|
1084
|
+
}
|
|
1085
|
+
/**
|
|
1086
|
+
* @returns {Command[]}
|
|
1087
|
+
* @private
|
|
1088
|
+
*/
|
|
1089
|
+
_getCommandAndAncestors() {
|
|
1090
|
+
const result = [];
|
|
1091
|
+
for (let command = this; command; command = command.parent) result.push(command);
|
|
1092
|
+
return result;
|
|
1093
|
+
}
|
|
1094
|
+
/**
|
|
1095
|
+
* Define a command.
|
|
1096
|
+
*
|
|
1097
|
+
* There are two styles of command: pay attention to where to put the description.
|
|
1098
|
+
*
|
|
1099
|
+
* @example
|
|
1100
|
+
* // Command implemented using action handler (description is supplied separately to `.command`)
|
|
1101
|
+
* program
|
|
1102
|
+
* .command('clone <source> [destination]')
|
|
1103
|
+
* .description('clone a repository into a newly created directory')
|
|
1104
|
+
* .action((source, destination) => {
|
|
1105
|
+
* console.log('clone command called');
|
|
1106
|
+
* });
|
|
1107
|
+
*
|
|
1108
|
+
* // Command implemented using separate executable file (description is second parameter to `.command`)
|
|
1109
|
+
* program
|
|
1110
|
+
* .command('start <service>', 'start named service')
|
|
1111
|
+
* .command('stop [service]', 'stop named service, or all if no name supplied');
|
|
1112
|
+
*
|
|
1113
|
+
* @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
|
|
1114
|
+
* @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
|
|
1115
|
+
* @param {object} [execOpts] - configuration options (for executable)
|
|
1116
|
+
* @return {Command} returns new command for action handler, or `this` for executable command
|
|
1117
|
+
*/
|
|
1118
|
+
command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
|
|
1119
|
+
let desc = actionOptsOrExecDesc;
|
|
1120
|
+
let opts = execOpts;
|
|
1121
|
+
if (typeof desc === "object" && desc !== null) {
|
|
1122
|
+
opts = desc;
|
|
1123
|
+
desc = null;
|
|
1124
|
+
}
|
|
1125
|
+
opts = opts || {};
|
|
1126
|
+
const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
|
|
1127
|
+
const cmd = this.createCommand(name);
|
|
1128
|
+
if (desc) {
|
|
1129
|
+
cmd.description(desc);
|
|
1130
|
+
cmd._executableHandler = true;
|
|
1131
|
+
}
|
|
1132
|
+
if (opts.isDefault) this._defaultCommandName = cmd._name;
|
|
1133
|
+
cmd._hidden = !!(opts.noHelp || opts.hidden);
|
|
1134
|
+
cmd._executableFile = opts.executableFile || null;
|
|
1135
|
+
if (args) cmd.arguments(args);
|
|
1136
|
+
this._registerCommand(cmd);
|
|
1137
|
+
cmd.parent = this;
|
|
1138
|
+
cmd.copyInheritedSettings(this);
|
|
1139
|
+
if (desc) return this;
|
|
1140
|
+
return cmd;
|
|
1141
|
+
}
|
|
1142
|
+
/**
|
|
1143
|
+
* Factory routine to create a new unattached command.
|
|
1144
|
+
*
|
|
1145
|
+
* See .command() for creating an attached subcommand, which uses this routine to
|
|
1146
|
+
* create the command. You can override createCommand to customise subcommands.
|
|
1147
|
+
*
|
|
1148
|
+
* @param {string} [name]
|
|
1149
|
+
* @return {Command} new command
|
|
1150
|
+
*/
|
|
1151
|
+
createCommand(name) {
|
|
1152
|
+
return new Command(name);
|
|
1153
|
+
}
|
|
1154
|
+
/**
|
|
1155
|
+
* You can customise the help with a subclass of Help by overriding createHelp,
|
|
1156
|
+
* or by overriding Help properties using configureHelp().
|
|
1157
|
+
*
|
|
1158
|
+
* @return {Help}
|
|
1159
|
+
*/
|
|
1160
|
+
createHelp() {
|
|
1161
|
+
return Object.assign(new Help(), this.configureHelp());
|
|
1162
|
+
}
|
|
1163
|
+
/**
|
|
1164
|
+
* You can customise the help by overriding Help properties using configureHelp(),
|
|
1165
|
+
* or with a subclass of Help by overriding createHelp().
|
|
1166
|
+
*
|
|
1167
|
+
* @param {object} [configuration] - configuration options
|
|
1168
|
+
* @return {(Command | object)} `this` command for chaining, or stored configuration
|
|
1169
|
+
*/
|
|
1170
|
+
configureHelp(configuration) {
|
|
1171
|
+
if (configuration === void 0) return this._helpConfiguration;
|
|
1172
|
+
this._helpConfiguration = configuration;
|
|
1173
|
+
return this;
|
|
1174
|
+
}
|
|
1175
|
+
/**
|
|
1176
|
+
* The default output goes to stdout and stderr. You can customise this for special
|
|
1177
|
+
* applications. You can also customise the display of errors by overriding outputError.
|
|
1178
|
+
*
|
|
1179
|
+
* The configuration properties are all functions:
|
|
1180
|
+
*
|
|
1181
|
+
* // change how output being written, defaults to stdout and stderr
|
|
1182
|
+
* writeOut(str)
|
|
1183
|
+
* writeErr(str)
|
|
1184
|
+
* // change how output being written for errors, defaults to writeErr
|
|
1185
|
+
* outputError(str, write) // used for displaying errors and not used for displaying help
|
|
1186
|
+
* // specify width for wrapping help
|
|
1187
|
+
* getOutHelpWidth()
|
|
1188
|
+
* getErrHelpWidth()
|
|
1189
|
+
* // color support, currently only used with Help
|
|
1190
|
+
* getOutHasColors()
|
|
1191
|
+
* getErrHasColors()
|
|
1192
|
+
* stripColor() // used to remove ANSI escape codes if output does not have colors
|
|
1193
|
+
*
|
|
1194
|
+
* @param {object} [configuration] - configuration options
|
|
1195
|
+
* @return {(Command | object)} `this` command for chaining, or stored configuration
|
|
1196
|
+
*/
|
|
1197
|
+
configureOutput(configuration) {
|
|
1198
|
+
if (configuration === void 0) return this._outputConfiguration;
|
|
1199
|
+
this._outputConfiguration = {
|
|
1200
|
+
...this._outputConfiguration,
|
|
1201
|
+
...configuration
|
|
1202
|
+
};
|
|
1203
|
+
return this;
|
|
1204
|
+
}
|
|
1205
|
+
/**
|
|
1206
|
+
* Display the help or a custom message after an error occurs.
|
|
1207
|
+
*
|
|
1208
|
+
* @param {(boolean|string)} [displayHelp]
|
|
1209
|
+
* @return {Command} `this` command for chaining
|
|
1210
|
+
*/
|
|
1211
|
+
showHelpAfterError(displayHelp = true) {
|
|
1212
|
+
if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
|
|
1213
|
+
this._showHelpAfterError = displayHelp;
|
|
1214
|
+
return this;
|
|
1215
|
+
}
|
|
1216
|
+
/**
|
|
1217
|
+
* Display suggestion of similar commands for unknown commands, or options for unknown options.
|
|
1218
|
+
*
|
|
1219
|
+
* @param {boolean} [displaySuggestion]
|
|
1220
|
+
* @return {Command} `this` command for chaining
|
|
1221
|
+
*/
|
|
1222
|
+
showSuggestionAfterError(displaySuggestion = true) {
|
|
1223
|
+
this._showSuggestionAfterError = !!displaySuggestion;
|
|
1224
|
+
return this;
|
|
1225
|
+
}
|
|
1226
|
+
/**
|
|
1227
|
+
* Add a prepared subcommand.
|
|
1228
|
+
*
|
|
1229
|
+
* See .command() for creating an attached subcommand which inherits settings from its parent.
|
|
1230
|
+
*
|
|
1231
|
+
* @param {Command} cmd - new subcommand
|
|
1232
|
+
* @param {object} [opts] - configuration options
|
|
1233
|
+
* @return {Command} `this` command for chaining
|
|
1234
|
+
*/
|
|
1235
|
+
addCommand(cmd, opts) {
|
|
1236
|
+
if (!cmd._name) throw new Error(`Command passed to .addCommand() must have a name
|
|
1237
|
+
- specify the name in Command constructor or using .name()`);
|
|
1238
|
+
opts = opts || {};
|
|
1239
|
+
if (opts.isDefault) this._defaultCommandName = cmd._name;
|
|
1240
|
+
if (opts.noHelp || opts.hidden) cmd._hidden = true;
|
|
1241
|
+
this._registerCommand(cmd);
|
|
1242
|
+
cmd.parent = this;
|
|
1243
|
+
cmd._checkForBrokenPassThrough();
|
|
1244
|
+
return this;
|
|
1245
|
+
}
|
|
1246
|
+
/**
|
|
1247
|
+
* Factory routine to create a new unattached argument.
|
|
1248
|
+
*
|
|
1249
|
+
* See .argument() for creating an attached argument, which uses this routine to
|
|
1250
|
+
* create the argument. You can override createArgument to return a custom argument.
|
|
1251
|
+
*
|
|
1252
|
+
* @param {string} name
|
|
1253
|
+
* @param {string} [description]
|
|
1254
|
+
* @return {Argument} new argument
|
|
1255
|
+
*/
|
|
1256
|
+
createArgument(name, description) {
|
|
1257
|
+
return new Argument(name, description);
|
|
1258
|
+
}
|
|
1259
|
+
/**
|
|
1260
|
+
* Define argument syntax for command.
|
|
1261
|
+
*
|
|
1262
|
+
* The default is that the argument is required, and you can explicitly
|
|
1263
|
+
* indicate this with <> around the name. Put [] around the name for an optional argument.
|
|
1264
|
+
*
|
|
1265
|
+
* @example
|
|
1266
|
+
* program.argument('<input-file>');
|
|
1267
|
+
* program.argument('[output-file]');
|
|
1268
|
+
*
|
|
1269
|
+
* @param {string} name
|
|
1270
|
+
* @param {string} [description]
|
|
1271
|
+
* @param {(Function|*)} [parseArg] - custom argument processing function or default value
|
|
1272
|
+
* @param {*} [defaultValue]
|
|
1273
|
+
* @return {Command} `this` command for chaining
|
|
1274
|
+
*/
|
|
1275
|
+
argument(name, description, parseArg, defaultValue) {
|
|
1276
|
+
const argument = this.createArgument(name, description);
|
|
1277
|
+
if (typeof parseArg === "function") argument.default(defaultValue).argParser(parseArg);
|
|
1278
|
+
else argument.default(parseArg);
|
|
1279
|
+
this.addArgument(argument);
|
|
1280
|
+
return this;
|
|
1281
|
+
}
|
|
1282
|
+
/**
|
|
1283
|
+
* Define argument syntax for command, adding multiple at once (without descriptions).
|
|
1284
|
+
*
|
|
1285
|
+
* See also .argument().
|
|
1286
|
+
*
|
|
1287
|
+
* @example
|
|
1288
|
+
* program.arguments('<cmd> [env]');
|
|
1289
|
+
*
|
|
1290
|
+
* @param {string} names
|
|
1291
|
+
* @return {Command} `this` command for chaining
|
|
1292
|
+
*/
|
|
1293
|
+
arguments(names) {
|
|
1294
|
+
names.trim().split(/ +/).forEach((detail) => {
|
|
1295
|
+
this.argument(detail);
|
|
1296
|
+
});
|
|
1297
|
+
return this;
|
|
1298
|
+
}
|
|
1299
|
+
/**
|
|
1300
|
+
* Define argument syntax for command, adding a prepared argument.
|
|
1301
|
+
*
|
|
1302
|
+
* @param {Argument} argument
|
|
1303
|
+
* @return {Command} `this` command for chaining
|
|
1304
|
+
*/
|
|
1305
|
+
addArgument(argument) {
|
|
1306
|
+
const previousArgument = this.registeredArguments.slice(-1)[0];
|
|
1307
|
+
if (previousArgument?.variadic) throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
|
|
1308
|
+
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()}'`);
|
|
1309
|
+
this.registeredArguments.push(argument);
|
|
1310
|
+
return this;
|
|
1311
|
+
}
|
|
1312
|
+
/**
|
|
1313
|
+
* Customise or override default help command. By default a help command is automatically added if your command has subcommands.
|
|
1314
|
+
*
|
|
1315
|
+
* @example
|
|
1316
|
+
* program.helpCommand('help [cmd]');
|
|
1317
|
+
* program.helpCommand('help [cmd]', 'show help');
|
|
1318
|
+
* program.helpCommand(false); // suppress default help command
|
|
1319
|
+
* program.helpCommand(true); // add help command even if no subcommands
|
|
1320
|
+
*
|
|
1321
|
+
* @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
|
|
1322
|
+
* @param {string} [description] - custom description
|
|
1323
|
+
* @return {Command} `this` command for chaining
|
|
1324
|
+
*/
|
|
1325
|
+
helpCommand(enableOrNameAndArgs, description) {
|
|
1326
|
+
if (typeof enableOrNameAndArgs === "boolean") {
|
|
1327
|
+
this._addImplicitHelpCommand = enableOrNameAndArgs;
|
|
1328
|
+
if (enableOrNameAndArgs && this._defaultCommandGroup) this._initCommandGroup(this._getHelpCommand());
|
|
1329
|
+
return this;
|
|
1330
|
+
}
|
|
1331
|
+
const [, helpName, helpArgs] = (enableOrNameAndArgs ?? "help [command]").match(/([^ ]+) *(.*)/);
|
|
1332
|
+
const helpDescription = description ?? "display help for command";
|
|
1333
|
+
const helpCommand = this.createCommand(helpName);
|
|
1334
|
+
helpCommand.helpOption(false);
|
|
1335
|
+
if (helpArgs) helpCommand.arguments(helpArgs);
|
|
1336
|
+
if (helpDescription) helpCommand.description(helpDescription);
|
|
1337
|
+
this._addImplicitHelpCommand = true;
|
|
1338
|
+
this._helpCommand = helpCommand;
|
|
1339
|
+
if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
|
|
1340
|
+
return this;
|
|
1341
|
+
}
|
|
1342
|
+
/**
|
|
1343
|
+
* Add prepared custom help command.
|
|
1344
|
+
*
|
|
1345
|
+
* @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
|
|
1346
|
+
* @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
|
|
1347
|
+
* @return {Command} `this` command for chaining
|
|
1348
|
+
*/
|
|
1349
|
+
addHelpCommand(helpCommand, deprecatedDescription) {
|
|
1350
|
+
if (typeof helpCommand !== "object") {
|
|
1351
|
+
this.helpCommand(helpCommand, deprecatedDescription);
|
|
1352
|
+
return this;
|
|
1353
|
+
}
|
|
1354
|
+
this._addImplicitHelpCommand = true;
|
|
1355
|
+
this._helpCommand = helpCommand;
|
|
1356
|
+
this._initCommandGroup(helpCommand);
|
|
1357
|
+
return this;
|
|
1358
|
+
}
|
|
1359
|
+
/**
|
|
1360
|
+
* Lazy create help command.
|
|
1361
|
+
*
|
|
1362
|
+
* @return {(Command|null)}
|
|
1363
|
+
* @package
|
|
1364
|
+
*/
|
|
1365
|
+
_getHelpCommand() {
|
|
1366
|
+
if (this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"))) {
|
|
1367
|
+
if (this._helpCommand === void 0) this.helpCommand(void 0, void 0);
|
|
1368
|
+
return this._helpCommand;
|
|
1369
|
+
}
|
|
1370
|
+
return null;
|
|
1371
|
+
}
|
|
1372
|
+
/**
|
|
1373
|
+
* Add hook for life cycle event.
|
|
1374
|
+
*
|
|
1375
|
+
* @param {string} event
|
|
1376
|
+
* @param {Function} listener
|
|
1377
|
+
* @return {Command} `this` command for chaining
|
|
1378
|
+
*/
|
|
1379
|
+
hook(event, listener) {
|
|
1380
|
+
const allowedValues = [
|
|
1381
|
+
"preSubcommand",
|
|
1382
|
+
"preAction",
|
|
1383
|
+
"postAction"
|
|
1384
|
+
];
|
|
1385
|
+
if (!allowedValues.includes(event)) throw new Error(`Unexpected value for event passed to hook : '${event}'.
|
|
1386
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
1387
|
+
if (this._lifeCycleHooks[event]) this._lifeCycleHooks[event].push(listener);
|
|
1388
|
+
else this._lifeCycleHooks[event] = [listener];
|
|
1389
|
+
return this;
|
|
1390
|
+
}
|
|
1391
|
+
/**
|
|
1392
|
+
* Register callback to use as replacement for calling process.exit.
|
|
1393
|
+
*
|
|
1394
|
+
* @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
|
|
1395
|
+
* @return {Command} `this` command for chaining
|
|
1396
|
+
*/
|
|
1397
|
+
exitOverride(fn) {
|
|
1398
|
+
if (fn) this._exitCallback = fn;
|
|
1399
|
+
else this._exitCallback = (err) => {
|
|
1400
|
+
if (err.code !== "commander.executeSubCommandAsync") throw err;
|
|
1401
|
+
};
|
|
1402
|
+
return this;
|
|
1403
|
+
}
|
|
1404
|
+
/**
|
|
1405
|
+
* Call process.exit, and _exitCallback if defined.
|
|
1406
|
+
*
|
|
1407
|
+
* @param {number} exitCode exit code for using with process.exit
|
|
1408
|
+
* @param {string} code an id string representing the error
|
|
1409
|
+
* @param {string} message human-readable description of the error
|
|
1410
|
+
* @return never
|
|
1411
|
+
* @private
|
|
1412
|
+
*/
|
|
1413
|
+
_exit(exitCode, code, message) {
|
|
1414
|
+
if (this._exitCallback) this._exitCallback(new CommanderError(exitCode, code, message));
|
|
1415
|
+
process$1.exit(exitCode);
|
|
1416
|
+
}
|
|
1417
|
+
/**
|
|
1418
|
+
* Register callback `fn` for the command.
|
|
1419
|
+
*
|
|
1420
|
+
* @example
|
|
1421
|
+
* program
|
|
1422
|
+
* .command('serve')
|
|
1423
|
+
* .description('start service')
|
|
1424
|
+
* .action(function() {
|
|
1425
|
+
* // do work here
|
|
1426
|
+
* });
|
|
1427
|
+
*
|
|
1428
|
+
* @param {Function} fn
|
|
1429
|
+
* @return {Command} `this` command for chaining
|
|
1430
|
+
*/
|
|
1431
|
+
action(fn) {
|
|
1432
|
+
const listener = (args) => {
|
|
1433
|
+
const expectedArgsCount = this.registeredArguments.length;
|
|
1434
|
+
const actionArgs = args.slice(0, expectedArgsCount);
|
|
1435
|
+
if (this._storeOptionsAsProperties) actionArgs[expectedArgsCount] = this;
|
|
1436
|
+
else actionArgs[expectedArgsCount] = this.opts();
|
|
1437
|
+
actionArgs.push(this);
|
|
1438
|
+
return fn.apply(this, actionArgs);
|
|
1439
|
+
};
|
|
1440
|
+
this._actionHandler = listener;
|
|
1441
|
+
return this;
|
|
1442
|
+
}
|
|
1443
|
+
/**
|
|
1444
|
+
* Factory routine to create a new unattached option.
|
|
1445
|
+
*
|
|
1446
|
+
* See .option() for creating an attached option, which uses this routine to
|
|
1447
|
+
* create the option. You can override createOption to return a custom option.
|
|
1448
|
+
*
|
|
1449
|
+
* @param {string} flags
|
|
1450
|
+
* @param {string} [description]
|
|
1451
|
+
* @return {Option} new option
|
|
1452
|
+
*/
|
|
1453
|
+
createOption(flags, description) {
|
|
1454
|
+
return new Option(flags, description);
|
|
1455
|
+
}
|
|
1456
|
+
/**
|
|
1457
|
+
* Wrap parseArgs to catch 'commander.invalidArgument'.
|
|
1458
|
+
*
|
|
1459
|
+
* @param {(Option | Argument)} target
|
|
1460
|
+
* @param {string} value
|
|
1461
|
+
* @param {*} previous
|
|
1462
|
+
* @param {string} invalidArgumentMessage
|
|
1463
|
+
* @private
|
|
1464
|
+
*/
|
|
1465
|
+
_callParseArg(target, value, previous, invalidArgumentMessage) {
|
|
1466
|
+
try {
|
|
1467
|
+
return target.parseArg(value, previous);
|
|
1468
|
+
} catch (err) {
|
|
1469
|
+
if (err.code === "commander.invalidArgument") {
|
|
1470
|
+
const message = `${invalidArgumentMessage} ${err.message}`;
|
|
1471
|
+
this.error(message, {
|
|
1472
|
+
exitCode: err.exitCode,
|
|
1473
|
+
code: err.code
|
|
1474
|
+
});
|
|
1475
|
+
}
|
|
1476
|
+
throw err;
|
|
1477
|
+
}
|
|
1478
|
+
}
|
|
1479
|
+
/**
|
|
1480
|
+
* Check for option flag conflicts.
|
|
1481
|
+
* Register option if no conflicts found, or throw on conflict.
|
|
1482
|
+
*
|
|
1483
|
+
* @param {Option} option
|
|
1484
|
+
* @private
|
|
1485
|
+
*/
|
|
1486
|
+
_registerOption(option) {
|
|
1487
|
+
const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
|
|
1488
|
+
if (matchingOption) {
|
|
1489
|
+
const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
|
|
1490
|
+
throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
|
|
1491
|
+
- already used by option '${matchingOption.flags}'`);
|
|
1492
|
+
}
|
|
1493
|
+
this._initOptionGroup(option);
|
|
1494
|
+
this.options.push(option);
|
|
1495
|
+
}
|
|
1496
|
+
/**
|
|
1497
|
+
* Check for command name and alias conflicts with existing commands.
|
|
1498
|
+
* Register command if no conflicts found, or throw on conflict.
|
|
1499
|
+
*
|
|
1500
|
+
* @param {Command} command
|
|
1501
|
+
* @private
|
|
1502
|
+
*/
|
|
1503
|
+
_registerCommand(command) {
|
|
1504
|
+
const knownBy = (cmd) => {
|
|
1505
|
+
return [cmd.name()].concat(cmd.aliases());
|
|
1506
|
+
};
|
|
1507
|
+
const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
|
|
1508
|
+
if (alreadyUsed) {
|
|
1509
|
+
const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
|
|
1510
|
+
const newCmd = knownBy(command).join("|");
|
|
1511
|
+
throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
|
|
1512
|
+
}
|
|
1513
|
+
this._initCommandGroup(command);
|
|
1514
|
+
this.commands.push(command);
|
|
1515
|
+
}
|
|
1516
|
+
/**
|
|
1517
|
+
* Add an option.
|
|
1518
|
+
*
|
|
1519
|
+
* @param {Option} option
|
|
1520
|
+
* @return {Command} `this` command for chaining
|
|
1521
|
+
*/
|
|
1522
|
+
addOption(option) {
|
|
1523
|
+
this._registerOption(option);
|
|
1524
|
+
const oname = option.name();
|
|
1525
|
+
const name = option.attributeName();
|
|
1526
|
+
if (option.defaultValue !== void 0) this.setOptionValueWithSource(name, option.defaultValue, "default");
|
|
1527
|
+
const handleOptionValue = (val, invalidValueMessage, valueSource) => {
|
|
1528
|
+
if (val == null && option.presetArg !== void 0) val = option.presetArg;
|
|
1529
|
+
const oldValue = this.getOptionValue(name);
|
|
1530
|
+
if (val !== null && option.parseArg) val = this._callParseArg(option, val, oldValue, invalidValueMessage);
|
|
1531
|
+
else if (val !== null && option.variadic) val = option._collectValue(val, oldValue);
|
|
1532
|
+
if (val == null) {
|
|
1533
|
+
if (option.negate) val = false;
|
|
1534
|
+
else if (option.isBoolean() || option.optional) val = true;
|
|
1535
|
+
else val = "";
|
|
1536
|
+
}
|
|
1537
|
+
this.setOptionValueWithSource(name, val, valueSource);
|
|
1538
|
+
};
|
|
1539
|
+
this.on("option:" + oname, (val) => {
|
|
1540
|
+
const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
|
|
1541
|
+
handleOptionValue(val, invalidValueMessage, "cli");
|
|
1542
|
+
});
|
|
1543
|
+
if (option.envVar) this.on("optionEnv:" + oname, (val) => {
|
|
1544
|
+
const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
|
|
1545
|
+
handleOptionValue(val, invalidValueMessage, "env");
|
|
1546
|
+
});
|
|
1547
|
+
return this;
|
|
1548
|
+
}
|
|
1549
|
+
/**
|
|
1550
|
+
* Internal implementation shared by .option() and .requiredOption()
|
|
1551
|
+
*
|
|
1552
|
+
* @return {Command} `this` command for chaining
|
|
1553
|
+
* @private
|
|
1554
|
+
*/
|
|
1555
|
+
_optionEx(config, flags, description, fn, defaultValue) {
|
|
1556
|
+
if (typeof flags === "object" && flags instanceof Option) throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
|
|
1557
|
+
const option = this.createOption(flags, description);
|
|
1558
|
+
option.makeOptionMandatory(!!config.mandatory);
|
|
1559
|
+
if (typeof fn === "function") option.default(defaultValue).argParser(fn);
|
|
1560
|
+
else if (fn instanceof RegExp) {
|
|
1561
|
+
const regex = fn;
|
|
1562
|
+
fn = (val, def) => {
|
|
1563
|
+
const m = regex.exec(val);
|
|
1564
|
+
return m ? m[0] : def;
|
|
1565
|
+
};
|
|
1566
|
+
option.default(defaultValue).argParser(fn);
|
|
1567
|
+
} else option.default(fn);
|
|
1568
|
+
return this.addOption(option);
|
|
1569
|
+
}
|
|
1570
|
+
/**
|
|
1571
|
+
* Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
|
|
1572
|
+
*
|
|
1573
|
+
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
|
|
1574
|
+
* option-argument is indicated by `<>` and an optional option-argument by `[]`.
|
|
1575
|
+
*
|
|
1576
|
+
* See the README for more details, and see also addOption() and requiredOption().
|
|
1577
|
+
*
|
|
1578
|
+
* @example
|
|
1579
|
+
* program
|
|
1580
|
+
* .option('-p, --pepper', 'add pepper')
|
|
1581
|
+
* .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
|
|
1582
|
+
* .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
|
|
1583
|
+
* .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
|
|
1584
|
+
*
|
|
1585
|
+
* @param {string} flags
|
|
1586
|
+
* @param {string} [description]
|
|
1587
|
+
* @param {(Function|*)} [parseArg] - custom option processing function or default value
|
|
1588
|
+
* @param {*} [defaultValue]
|
|
1589
|
+
* @return {Command} `this` command for chaining
|
|
1590
|
+
*/
|
|
1591
|
+
option(flags, description, parseArg, defaultValue) {
|
|
1592
|
+
return this._optionEx({}, flags, description, parseArg, defaultValue);
|
|
1593
|
+
}
|
|
1594
|
+
/**
|
|
1595
|
+
* Add a required option which must have a value after parsing. This usually means
|
|
1596
|
+
* the option must be specified on the command line. (Otherwise the same as .option().)
|
|
1597
|
+
*
|
|
1598
|
+
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
|
|
1599
|
+
*
|
|
1600
|
+
* @param {string} flags
|
|
1601
|
+
* @param {string} [description]
|
|
1602
|
+
* @param {(Function|*)} [parseArg] - custom option processing function or default value
|
|
1603
|
+
* @param {*} [defaultValue]
|
|
1604
|
+
* @return {Command} `this` command for chaining
|
|
1605
|
+
*/
|
|
1606
|
+
requiredOption(flags, description, parseArg, defaultValue) {
|
|
1607
|
+
return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
|
|
1608
|
+
}
|
|
1609
|
+
/**
|
|
1610
|
+
* Alter parsing of short flags with optional values.
|
|
1611
|
+
*
|
|
1612
|
+
* @example
|
|
1613
|
+
* // for `.option('-f,--flag [value]'):
|
|
1614
|
+
* program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
|
|
1615
|
+
* program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
|
|
1616
|
+
*
|
|
1617
|
+
* @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
|
|
1618
|
+
* @return {Command} `this` command for chaining
|
|
1619
|
+
*/
|
|
1620
|
+
combineFlagAndOptionalValue(combine = true) {
|
|
1621
|
+
this._combineFlagAndOptionalValue = !!combine;
|
|
1622
|
+
return this;
|
|
1623
|
+
}
|
|
1624
|
+
/**
|
|
1625
|
+
* Allow unknown options on the command line.
|
|
1626
|
+
*
|
|
1627
|
+
* @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
|
|
1628
|
+
* @return {Command} `this` command for chaining
|
|
1629
|
+
*/
|
|
1630
|
+
allowUnknownOption(allowUnknown = true) {
|
|
1631
|
+
this._allowUnknownOption = !!allowUnknown;
|
|
1632
|
+
return this;
|
|
1633
|
+
}
|
|
1634
|
+
/**
|
|
1635
|
+
* Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
|
|
1636
|
+
*
|
|
1637
|
+
* @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
|
|
1638
|
+
* @return {Command} `this` command for chaining
|
|
1639
|
+
*/
|
|
1640
|
+
allowExcessArguments(allowExcess = true) {
|
|
1641
|
+
this._allowExcessArguments = !!allowExcess;
|
|
1642
|
+
return this;
|
|
1643
|
+
}
|
|
1644
|
+
/**
|
|
1645
|
+
* Enable positional options. Positional means global options are specified before subcommands which lets
|
|
1646
|
+
* subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
|
|
1647
|
+
* The default behaviour is non-positional and global options may appear anywhere on the command line.
|
|
1648
|
+
*
|
|
1649
|
+
* @param {boolean} [positional]
|
|
1650
|
+
* @return {Command} `this` command for chaining
|
|
1651
|
+
*/
|
|
1652
|
+
enablePositionalOptions(positional = true) {
|
|
1653
|
+
this._enablePositionalOptions = !!positional;
|
|
1654
|
+
return this;
|
|
1655
|
+
}
|
|
1656
|
+
/**
|
|
1657
|
+
* Pass through options that come after command-arguments rather than treat them as command-options,
|
|
1658
|
+
* so actual command-options come before command-arguments. Turning this on for a subcommand requires
|
|
1659
|
+
* positional options to have been enabled on the program (parent commands).
|
|
1660
|
+
* The default behaviour is non-positional and options may appear before or after command-arguments.
|
|
1661
|
+
*
|
|
1662
|
+
* @param {boolean} [passThrough] for unknown options.
|
|
1663
|
+
* @return {Command} `this` command for chaining
|
|
1664
|
+
*/
|
|
1665
|
+
passThroughOptions(passThrough = true) {
|
|
1666
|
+
this._passThroughOptions = !!passThrough;
|
|
1667
|
+
this._checkForBrokenPassThrough();
|
|
1668
|
+
return this;
|
|
1669
|
+
}
|
|
1670
|
+
/**
|
|
1671
|
+
* @private
|
|
1672
|
+
*/
|
|
1673
|
+
_checkForBrokenPassThrough() {
|
|
1674
|
+
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)`);
|
|
1675
|
+
}
|
|
1676
|
+
/**
|
|
1677
|
+
* Whether to store option values as properties on command object,
|
|
1678
|
+
* or store separately (specify false). In both cases the option values can be accessed using .opts().
|
|
1679
|
+
*
|
|
1680
|
+
* @param {boolean} [storeAsProperties=true]
|
|
1681
|
+
* @return {Command} `this` command for chaining
|
|
1682
|
+
*/
|
|
1683
|
+
storeOptionsAsProperties(storeAsProperties = true) {
|
|
1684
|
+
if (this.options.length) throw new Error("call .storeOptionsAsProperties() before adding options");
|
|
1685
|
+
if (Object.keys(this._optionValues).length) throw new Error("call .storeOptionsAsProperties() before setting option values");
|
|
1686
|
+
this._storeOptionsAsProperties = !!storeAsProperties;
|
|
1687
|
+
return this;
|
|
1688
|
+
}
|
|
1689
|
+
/**
|
|
1690
|
+
* Retrieve option value.
|
|
1691
|
+
*
|
|
1692
|
+
* @param {string} key
|
|
1693
|
+
* @return {object} value
|
|
1694
|
+
*/
|
|
1695
|
+
getOptionValue(key) {
|
|
1696
|
+
if (this._storeOptionsAsProperties) return this[key];
|
|
1697
|
+
return this._optionValues[key];
|
|
1698
|
+
}
|
|
1699
|
+
/**
|
|
1700
|
+
* Store option value.
|
|
1701
|
+
*
|
|
1702
|
+
* @param {string} key
|
|
1703
|
+
* @param {object} value
|
|
1704
|
+
* @return {Command} `this` command for chaining
|
|
1705
|
+
*/
|
|
1706
|
+
setOptionValue(key, value) {
|
|
1707
|
+
return this.setOptionValueWithSource(key, value, void 0);
|
|
1708
|
+
}
|
|
1709
|
+
/**
|
|
1710
|
+
* Store option value and where the value came from.
|
|
1711
|
+
*
|
|
1712
|
+
* @param {string} key
|
|
1713
|
+
* @param {object} value
|
|
1714
|
+
* @param {string} source - expected values are default/config/env/cli/implied
|
|
1715
|
+
* @return {Command} `this` command for chaining
|
|
1716
|
+
*/
|
|
1717
|
+
setOptionValueWithSource(key, value, source) {
|
|
1718
|
+
if (this._storeOptionsAsProperties) this[key] = value;
|
|
1719
|
+
else this._optionValues[key] = value;
|
|
1720
|
+
this._optionValueSources[key] = source;
|
|
1721
|
+
return this;
|
|
1722
|
+
}
|
|
1723
|
+
/**
|
|
1724
|
+
* Get source of option value.
|
|
1725
|
+
* Expected values are default | config | env | cli | implied
|
|
1726
|
+
*
|
|
1727
|
+
* @param {string} key
|
|
1728
|
+
* @return {string}
|
|
1729
|
+
*/
|
|
1730
|
+
getOptionValueSource(key) {
|
|
1731
|
+
return this._optionValueSources[key];
|
|
1732
|
+
}
|
|
1733
|
+
/**
|
|
1734
|
+
* Get source of option value. See also .optsWithGlobals().
|
|
1735
|
+
* Expected values are default | config | env | cli | implied
|
|
1736
|
+
*
|
|
1737
|
+
* @param {string} key
|
|
1738
|
+
* @return {string}
|
|
1739
|
+
*/
|
|
1740
|
+
getOptionValueSourceWithGlobals(key) {
|
|
1741
|
+
let source;
|
|
1742
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
1743
|
+
if (cmd.getOptionValueSource(key) !== void 0) source = cmd.getOptionValueSource(key);
|
|
1744
|
+
});
|
|
1745
|
+
return source;
|
|
1746
|
+
}
|
|
1747
|
+
/**
|
|
1748
|
+
* Get user arguments from implied or explicit arguments.
|
|
1749
|
+
* Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
|
|
1750
|
+
*
|
|
1751
|
+
* @private
|
|
1752
|
+
*/
|
|
1753
|
+
_prepareUserArgs(argv, parseOptions) {
|
|
1754
|
+
if (argv !== void 0 && !Array.isArray(argv)) throw new Error("first parameter to parse must be array or undefined");
|
|
1755
|
+
parseOptions = parseOptions || {};
|
|
1756
|
+
if (argv === void 0 && parseOptions.from === void 0) {
|
|
1757
|
+
if (process$1.versions?.electron) parseOptions.from = "electron";
|
|
1758
|
+
const execArgv = process$1.execArgv ?? [];
|
|
1759
|
+
if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) parseOptions.from = "eval";
|
|
1760
|
+
}
|
|
1761
|
+
if (argv === void 0) argv = process$1.argv;
|
|
1762
|
+
this.rawArgs = argv.slice();
|
|
1763
|
+
let userArgs;
|
|
1764
|
+
switch (parseOptions.from) {
|
|
1765
|
+
case void 0:
|
|
1766
|
+
case "node":
|
|
1767
|
+
this._scriptPath = argv[1];
|
|
1768
|
+
userArgs = argv.slice(2);
|
|
1769
|
+
break;
|
|
1770
|
+
case "electron":
|
|
1771
|
+
if (process$1.defaultApp) {
|
|
1772
|
+
this._scriptPath = argv[1];
|
|
1773
|
+
userArgs = argv.slice(2);
|
|
1774
|
+
} else userArgs = argv.slice(1);
|
|
1775
|
+
break;
|
|
1776
|
+
case "user":
|
|
1777
|
+
userArgs = argv.slice(0);
|
|
1778
|
+
break;
|
|
1779
|
+
case "eval":
|
|
1780
|
+
userArgs = argv.slice(1);
|
|
1781
|
+
break;
|
|
1782
|
+
default: throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
|
|
1783
|
+
}
|
|
1784
|
+
if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);
|
|
1785
|
+
this._name = this._name || "program";
|
|
1786
|
+
return userArgs;
|
|
1787
|
+
}
|
|
1788
|
+
/**
|
|
1789
|
+
* Parse `argv`, setting options and invoking commands when defined.
|
|
1790
|
+
*
|
|
1791
|
+
* Use parseAsync instead of parse if any of your action handlers are async.
|
|
1792
|
+
*
|
|
1793
|
+
* Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
|
|
1794
|
+
*
|
|
1795
|
+
* Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
|
|
1796
|
+
* - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
|
|
1797
|
+
* - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
|
|
1798
|
+
* - `'user'`: just user arguments
|
|
1799
|
+
*
|
|
1800
|
+
* @example
|
|
1801
|
+
* program.parse(); // parse process.argv and auto-detect electron and special node flags
|
|
1802
|
+
* program.parse(process.argv); // assume argv[0] is app and argv[1] is script
|
|
1803
|
+
* program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
|
|
1804
|
+
*
|
|
1805
|
+
* @param {string[]} [argv] - optional, defaults to process.argv
|
|
1806
|
+
* @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
|
|
1807
|
+
* @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
|
|
1808
|
+
* @return {Command} `this` command for chaining
|
|
1809
|
+
*/
|
|
1810
|
+
parse(argv, parseOptions) {
|
|
1811
|
+
this._prepareForParse();
|
|
1812
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
1813
|
+
this._parseCommand([], userArgs);
|
|
1814
|
+
return this;
|
|
1815
|
+
}
|
|
1816
|
+
/**
|
|
1817
|
+
* Parse `argv`, setting options and invoking commands when defined.
|
|
1818
|
+
*
|
|
1819
|
+
* Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
|
|
1820
|
+
*
|
|
1821
|
+
* Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
|
|
1822
|
+
* - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
|
|
1823
|
+
* - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
|
|
1824
|
+
* - `'user'`: just user arguments
|
|
1825
|
+
*
|
|
1826
|
+
* @example
|
|
1827
|
+
* await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
|
|
1828
|
+
* await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
|
|
1829
|
+
* await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
|
|
1830
|
+
*
|
|
1831
|
+
* @param {string[]} [argv]
|
|
1832
|
+
* @param {object} [parseOptions]
|
|
1833
|
+
* @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
|
|
1834
|
+
* @return {Promise}
|
|
1835
|
+
*/
|
|
1836
|
+
async parseAsync(argv, parseOptions) {
|
|
1837
|
+
this._prepareForParse();
|
|
1838
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
1839
|
+
await this._parseCommand([], userArgs);
|
|
1840
|
+
return this;
|
|
1841
|
+
}
|
|
1842
|
+
_prepareForParse() {
|
|
1843
|
+
if (this._savedState === null) {
|
|
1844
|
+
this.options.filter((option) => option.negate && option.defaultValue === void 0 && this.getOptionValue(option.attributeName()) === void 0).forEach((option) => {
|
|
1845
|
+
const positiveLongFlag = option.long.replace(/^--no-/, "--");
|
|
1846
|
+
if (!this._findOption(positiveLongFlag)) this.setOptionValueWithSource(option.attributeName(), true, "default");
|
|
1847
|
+
});
|
|
1848
|
+
this.saveStateBeforeParse();
|
|
1849
|
+
} else this.restoreStateBeforeParse();
|
|
1850
|
+
}
|
|
1851
|
+
/**
|
|
1852
|
+
* Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
|
|
1853
|
+
* Not usually called directly, but available for subclasses to save their custom state.
|
|
1854
|
+
*
|
|
1855
|
+
* This is called in a lazy way. Only commands used in parsing chain will have state saved.
|
|
1856
|
+
*/
|
|
1857
|
+
saveStateBeforeParse() {
|
|
1858
|
+
this._savedState = {
|
|
1859
|
+
_name: this._name,
|
|
1860
|
+
_optionValues: { ...this._optionValues },
|
|
1861
|
+
_optionValueSources: { ...this._optionValueSources }
|
|
1862
|
+
};
|
|
1863
|
+
}
|
|
1864
|
+
/**
|
|
1865
|
+
* Restore state before parse for calls after the first.
|
|
1866
|
+
* Not usually called directly, but available for subclasses to save their custom state.
|
|
1867
|
+
*
|
|
1868
|
+
* This is called in a lazy way. Only commands used in parsing chain will have state restored.
|
|
1869
|
+
*/
|
|
1870
|
+
restoreStateBeforeParse() {
|
|
1871
|
+
if (this._storeOptionsAsProperties) throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
1872
|
+
- either make a new Command for each call to parse, or stop storing options as properties`);
|
|
1873
|
+
this._name = this._savedState._name;
|
|
1874
|
+
this._scriptPath = null;
|
|
1875
|
+
this.rawArgs = [];
|
|
1876
|
+
this._optionValues = { ...this._savedState._optionValues };
|
|
1877
|
+
this._optionValueSources = { ...this._savedState._optionValueSources };
|
|
1878
|
+
this.args = [];
|
|
1879
|
+
this.processedArgs = [];
|
|
1880
|
+
}
|
|
1881
|
+
/**
|
|
1882
|
+
* Throw if expected executable is missing. Add lots of help for author.
|
|
1883
|
+
*
|
|
1884
|
+
* @param {string} executableFile
|
|
1885
|
+
* @param {string} executableDir
|
|
1886
|
+
* @param {string} subcommandName
|
|
1887
|
+
*/
|
|
1888
|
+
_checkForMissingExecutable(executableFile, executableDir, subcommandName) {
|
|
1889
|
+
if (fs.existsSync(executableFile)) return;
|
|
1890
|
+
const executableMissing = `'${executableFile}' does not exist
|
|
1891
|
+
- if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
1892
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
1893
|
+
- ${executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory"}`;
|
|
1894
|
+
throw new Error(executableMissing);
|
|
1895
|
+
}
|
|
1896
|
+
/**
|
|
1897
|
+
* Execute a sub-command executable.
|
|
1898
|
+
*
|
|
1899
|
+
* @private
|
|
1900
|
+
*/
|
|
1901
|
+
_executeSubCommand(subcommand, args) {
|
|
1902
|
+
args = args.slice();
|
|
1903
|
+
const sourceExt = [
|
|
1904
|
+
".js",
|
|
1905
|
+
".ts",
|
|
1906
|
+
".tsx",
|
|
1907
|
+
".mjs",
|
|
1908
|
+
".cjs"
|
|
1909
|
+
];
|
|
1910
|
+
function findFile(baseDir, baseName) {
|
|
1911
|
+
const localBin = path.resolve(baseDir, baseName);
|
|
1912
|
+
if (fs.existsSync(localBin)) return localBin;
|
|
1913
|
+
if (sourceExt.includes(path.extname(baseName))) return void 0;
|
|
1914
|
+
const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
|
|
1915
|
+
if (foundExt) return `${localBin}${foundExt}`;
|
|
1916
|
+
}
|
|
1917
|
+
this._checkForMissingMandatoryOptions();
|
|
1918
|
+
this._checkForConflictingOptions();
|
|
1919
|
+
let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
|
|
1920
|
+
let executableDir = this._executableDir || "";
|
|
1921
|
+
if (this._scriptPath) {
|
|
1922
|
+
let resolvedScriptPath;
|
|
1923
|
+
try {
|
|
1924
|
+
resolvedScriptPath = fs.realpathSync(this._scriptPath);
|
|
1925
|
+
} catch {
|
|
1926
|
+
resolvedScriptPath = this._scriptPath;
|
|
1927
|
+
}
|
|
1928
|
+
executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
|
|
1929
|
+
}
|
|
1930
|
+
if (executableDir) {
|
|
1931
|
+
let localFile = findFile(executableDir, executableFile);
|
|
1932
|
+
if (!localFile && !subcommand._executableFile && this._scriptPath) {
|
|
1933
|
+
const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
|
|
1934
|
+
if (legacyName !== this._name) localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
|
|
1935
|
+
}
|
|
1936
|
+
executableFile = localFile || executableFile;
|
|
1937
|
+
}
|
|
1938
|
+
const launchWithNode = sourceExt.includes(path.extname(executableFile));
|
|
1939
|
+
let proc;
|
|
1940
|
+
if (process$1.platform !== "win32") {
|
|
1941
|
+
if (launchWithNode) {
|
|
1942
|
+
args.unshift(executableFile);
|
|
1943
|
+
args = incrementNodeInspectorPort(process$1.execArgv).concat(args);
|
|
1944
|
+
proc = childProcess.spawn(process$1.argv[0], args, { stdio: "inherit" });
|
|
1945
|
+
} else proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
|
|
1946
|
+
} else {
|
|
1947
|
+
this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
|
|
1948
|
+
args.unshift(executableFile);
|
|
1949
|
+
args = incrementNodeInspectorPort(process$1.execArgv).concat(args);
|
|
1950
|
+
proc = childProcess.spawn(process$1.execPath, args, { stdio: "inherit" });
|
|
1951
|
+
}
|
|
1952
|
+
if (!proc.killed) [
|
|
1953
|
+
"SIGUSR1",
|
|
1954
|
+
"SIGUSR2",
|
|
1955
|
+
"SIGTERM",
|
|
1956
|
+
"SIGINT",
|
|
1957
|
+
"SIGHUP"
|
|
1958
|
+
].forEach((signal) => {
|
|
1959
|
+
process$1.on(signal, () => {
|
|
1960
|
+
if (proc.killed === false && proc.exitCode === null) proc.kill(signal);
|
|
1961
|
+
});
|
|
1962
|
+
});
|
|
1963
|
+
const exitCallback = this._exitCallback;
|
|
1964
|
+
proc.on("close", (code) => {
|
|
1965
|
+
code = code ?? 1;
|
|
1966
|
+
if (!exitCallback) process$1.exit(code);
|
|
1967
|
+
else exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
|
|
1968
|
+
});
|
|
1969
|
+
proc.on("error", (err) => {
|
|
1970
|
+
if (err.code === "ENOENT") this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
|
|
1971
|
+
else if (err.code === "EACCES") throw new Error(`'${executableFile}' not executable`);
|
|
1972
|
+
if (!exitCallback) process$1.exit(1);
|
|
1973
|
+
else {
|
|
1974
|
+
const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
|
|
1975
|
+
wrappedError.nestedError = err;
|
|
1976
|
+
exitCallback(wrappedError);
|
|
1977
|
+
}
|
|
1978
|
+
});
|
|
1979
|
+
this.runningCommand = proc;
|
|
1980
|
+
}
|
|
1981
|
+
/**
|
|
1982
|
+
* @private
|
|
1983
|
+
*/
|
|
1984
|
+
_dispatchSubcommand(commandName, operands, unknown) {
|
|
1985
|
+
const subCommand = this._findCommand(commandName);
|
|
1986
|
+
if (!subCommand) this.help({ error: true });
|
|
1987
|
+
subCommand._prepareForParse();
|
|
1988
|
+
let promiseChain;
|
|
1989
|
+
promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
|
|
1990
|
+
promiseChain = this._chainOrCall(promiseChain, () => {
|
|
1991
|
+
if (subCommand._executableHandler) this._executeSubCommand(subCommand, operands.concat(unknown));
|
|
1992
|
+
else return subCommand._parseCommand(operands, unknown);
|
|
1993
|
+
});
|
|
1994
|
+
return promiseChain;
|
|
1995
|
+
}
|
|
1996
|
+
/**
|
|
1997
|
+
* Invoke help directly if possible, or dispatch if necessary.
|
|
1998
|
+
* e.g. help foo
|
|
1999
|
+
*
|
|
2000
|
+
* @private
|
|
2001
|
+
*/
|
|
2002
|
+
_dispatchHelpCommand(subcommandName) {
|
|
2003
|
+
if (!subcommandName) this.help();
|
|
2004
|
+
const subCommand = this._findCommand(subcommandName);
|
|
2005
|
+
if (subCommand && !subCommand._executableHandler) subCommand.help();
|
|
2006
|
+
return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
|
|
2007
|
+
}
|
|
2008
|
+
/**
|
|
2009
|
+
* Check this.args against expected this.registeredArguments.
|
|
2010
|
+
*
|
|
2011
|
+
* @private
|
|
2012
|
+
*/
|
|
2013
|
+
_checkNumberOfArguments() {
|
|
2014
|
+
this.registeredArguments.forEach((arg, i) => {
|
|
2015
|
+
if (arg.required && this.args[i] == null) this.missingArgument(arg.name());
|
|
2016
|
+
});
|
|
2017
|
+
if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) return;
|
|
2018
|
+
if (this.args.length > this.registeredArguments.length) this._excessArguments(this.args);
|
|
2019
|
+
}
|
|
2020
|
+
/**
|
|
2021
|
+
* Process this.args using this.registeredArguments and save as this.processedArgs!
|
|
2022
|
+
*
|
|
2023
|
+
* @private
|
|
2024
|
+
*/
|
|
2025
|
+
_processArguments() {
|
|
2026
|
+
const myParseArg = (argument, value, previous) => {
|
|
2027
|
+
let parsedValue = value;
|
|
2028
|
+
if (value !== null && argument.parseArg) {
|
|
2029
|
+
const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
|
|
2030
|
+
parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
|
|
2031
|
+
}
|
|
2032
|
+
return parsedValue;
|
|
2033
|
+
};
|
|
2034
|
+
this._checkNumberOfArguments();
|
|
2035
|
+
const processedArgs = [];
|
|
2036
|
+
this.registeredArguments.forEach((declaredArg, index) => {
|
|
2037
|
+
let value = declaredArg.defaultValue;
|
|
2038
|
+
if (declaredArg.variadic) {
|
|
2039
|
+
if (index < this.args.length) {
|
|
2040
|
+
value = this.args.slice(index);
|
|
2041
|
+
if (declaredArg.parseArg) value = value.reduce((processed, v) => {
|
|
2042
|
+
return myParseArg(declaredArg, v, processed);
|
|
2043
|
+
}, declaredArg.defaultValue);
|
|
2044
|
+
} else if (value === void 0) value = [];
|
|
2045
|
+
} else if (index < this.args.length) {
|
|
2046
|
+
value = this.args[index];
|
|
2047
|
+
if (declaredArg.parseArg) value = myParseArg(declaredArg, value, declaredArg.defaultValue);
|
|
2048
|
+
}
|
|
2049
|
+
processedArgs[index] = value;
|
|
2050
|
+
});
|
|
2051
|
+
this.processedArgs = processedArgs;
|
|
2052
|
+
}
|
|
2053
|
+
/**
|
|
2054
|
+
* Once we have a promise we chain, but call synchronously until then.
|
|
2055
|
+
*
|
|
2056
|
+
* @param {(Promise|undefined)} promise
|
|
2057
|
+
* @param {Function} fn
|
|
2058
|
+
* @return {(Promise|undefined)}
|
|
2059
|
+
* @private
|
|
2060
|
+
*/
|
|
2061
|
+
_chainOrCall(promise, fn) {
|
|
2062
|
+
if (promise?.then && typeof promise.then === "function") return promise.then(() => fn());
|
|
2063
|
+
return fn();
|
|
2064
|
+
}
|
|
2065
|
+
/**
|
|
2066
|
+
*
|
|
2067
|
+
* @param {(Promise|undefined)} promise
|
|
2068
|
+
* @param {string} event
|
|
2069
|
+
* @return {(Promise|undefined)}
|
|
2070
|
+
* @private
|
|
2071
|
+
*/
|
|
2072
|
+
_chainOrCallHooks(promise, event) {
|
|
2073
|
+
let result = promise;
|
|
2074
|
+
const hooks = [];
|
|
2075
|
+
this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
|
|
2076
|
+
hookedCommand._lifeCycleHooks[event].forEach((callback) => {
|
|
2077
|
+
hooks.push({
|
|
2078
|
+
hookedCommand,
|
|
2079
|
+
callback
|
|
2080
|
+
});
|
|
2081
|
+
});
|
|
2082
|
+
});
|
|
2083
|
+
if (event === "postAction") hooks.reverse();
|
|
2084
|
+
hooks.forEach((hookDetail) => {
|
|
2085
|
+
result = this._chainOrCall(result, () => {
|
|
2086
|
+
return hookDetail.callback(hookDetail.hookedCommand, this);
|
|
2087
|
+
});
|
|
2088
|
+
});
|
|
2089
|
+
return result;
|
|
2090
|
+
}
|
|
2091
|
+
/**
|
|
2092
|
+
*
|
|
2093
|
+
* @param {(Promise|undefined)} promise
|
|
2094
|
+
* @param {Command} subCommand
|
|
2095
|
+
* @param {string} event
|
|
2096
|
+
* @return {(Promise|undefined)}
|
|
2097
|
+
* @private
|
|
2098
|
+
*/
|
|
2099
|
+
_chainOrCallSubCommandHook(promise, subCommand, event) {
|
|
2100
|
+
let result = promise;
|
|
2101
|
+
if (this._lifeCycleHooks[event] !== void 0) this._lifeCycleHooks[event].forEach((hook) => {
|
|
2102
|
+
result = this._chainOrCall(result, () => {
|
|
2103
|
+
return hook(this, subCommand);
|
|
2104
|
+
});
|
|
2105
|
+
});
|
|
2106
|
+
return result;
|
|
2107
|
+
}
|
|
2108
|
+
/**
|
|
2109
|
+
* Process arguments in context of this command.
|
|
2110
|
+
* Returns action result, in case it is a promise.
|
|
2111
|
+
*
|
|
2112
|
+
* @private
|
|
2113
|
+
*/
|
|
2114
|
+
_parseCommand(operands, unknown) {
|
|
2115
|
+
const parsed = this.parseOptions(unknown);
|
|
2116
|
+
this._parseOptionsEnv();
|
|
2117
|
+
this._parseOptionsImplied();
|
|
2118
|
+
operands = operands.concat(parsed.operands);
|
|
2119
|
+
unknown = parsed.unknown;
|
|
2120
|
+
this.args = operands.concat(unknown);
|
|
2121
|
+
if (operands && this._findCommand(operands[0])) return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
|
|
2122
|
+
if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) return this._dispatchHelpCommand(operands[1]);
|
|
2123
|
+
if (this._defaultCommandName) {
|
|
2124
|
+
this._outputHelpIfRequested(unknown);
|
|
2125
|
+
return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
|
|
2126
|
+
}
|
|
2127
|
+
if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) this.help({ error: true });
|
|
2128
|
+
this._outputHelpIfRequested(parsed.unknown);
|
|
2129
|
+
this._checkForMissingMandatoryOptions();
|
|
2130
|
+
this._checkForConflictingOptions();
|
|
2131
|
+
const checkForUnknownOptions = () => {
|
|
2132
|
+
if (parsed.unknown.length > 0) this.unknownOption(parsed.unknown[0]);
|
|
2133
|
+
};
|
|
2134
|
+
const commandEvent = `command:${this.name()}`;
|
|
2135
|
+
if (this._actionHandler) {
|
|
2136
|
+
checkForUnknownOptions();
|
|
2137
|
+
this._processArguments();
|
|
2138
|
+
let promiseChain;
|
|
2139
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
|
|
2140
|
+
promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
|
|
2141
|
+
if (this.parent) promiseChain = this._chainOrCall(promiseChain, () => {
|
|
2142
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
2143
|
+
});
|
|
2144
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
|
|
2145
|
+
return promiseChain;
|
|
2146
|
+
}
|
|
2147
|
+
if (this.parent?.listenerCount(commandEvent)) {
|
|
2148
|
+
checkForUnknownOptions();
|
|
2149
|
+
this._processArguments();
|
|
2150
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
2151
|
+
} else if (operands.length) {
|
|
2152
|
+
if (this._findCommand("*")) return this._dispatchSubcommand("*", operands, unknown);
|
|
2153
|
+
if (this.listenerCount("command:*")) this.emit("command:*", operands, unknown);
|
|
2154
|
+
else if (this.commands.length) this.unknownCommand();
|
|
2155
|
+
else {
|
|
2156
|
+
checkForUnknownOptions();
|
|
2157
|
+
this._processArguments();
|
|
2158
|
+
}
|
|
2159
|
+
} else if (this.commands.length) {
|
|
2160
|
+
checkForUnknownOptions();
|
|
2161
|
+
this.help({ error: true });
|
|
2162
|
+
} else {
|
|
2163
|
+
checkForUnknownOptions();
|
|
2164
|
+
this._processArguments();
|
|
2165
|
+
}
|
|
2166
|
+
}
|
|
2167
|
+
/**
|
|
2168
|
+
* Find matching command.
|
|
2169
|
+
*
|
|
2170
|
+
* @private
|
|
2171
|
+
* @return {Command | undefined}
|
|
2172
|
+
*/
|
|
2173
|
+
_findCommand(name) {
|
|
2174
|
+
if (!name) return void 0;
|
|
2175
|
+
return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
|
|
2176
|
+
}
|
|
2177
|
+
/**
|
|
2178
|
+
* Return an option matching `arg` if any.
|
|
2179
|
+
*
|
|
2180
|
+
* @param {string} arg
|
|
2181
|
+
* @return {Option}
|
|
2182
|
+
* @package
|
|
2183
|
+
*/
|
|
2184
|
+
_findOption(arg) {
|
|
2185
|
+
return this.options.find((option) => option.is(arg));
|
|
2186
|
+
}
|
|
2187
|
+
/**
|
|
2188
|
+
* Display an error message if a mandatory option does not have a value.
|
|
2189
|
+
* Called after checking for help flags in leaf subcommand.
|
|
2190
|
+
*
|
|
2191
|
+
* @private
|
|
2192
|
+
*/
|
|
2193
|
+
_checkForMissingMandatoryOptions() {
|
|
2194
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
2195
|
+
cmd.options.forEach((anOption) => {
|
|
2196
|
+
if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) cmd.missingMandatoryOptionValue(anOption);
|
|
2197
|
+
});
|
|
2198
|
+
});
|
|
2199
|
+
}
|
|
2200
|
+
/**
|
|
2201
|
+
* Display an error message if conflicting options are used together in this.
|
|
2202
|
+
*
|
|
2203
|
+
* @private
|
|
2204
|
+
*/
|
|
2205
|
+
_checkForConflictingLocalOptions() {
|
|
2206
|
+
const definedNonDefaultOptions = this.options.filter((option) => {
|
|
2207
|
+
const optionKey = option.attributeName();
|
|
2208
|
+
if (this.getOptionValue(optionKey) === void 0) return false;
|
|
2209
|
+
return this.getOptionValueSource(optionKey) !== "default";
|
|
2210
|
+
});
|
|
2211
|
+
definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0).forEach((option) => {
|
|
2212
|
+
const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
|
|
2213
|
+
if (conflictingAndDefined) this._conflictingOption(option, conflictingAndDefined);
|
|
2214
|
+
});
|
|
2215
|
+
}
|
|
2216
|
+
/**
|
|
2217
|
+
* Display an error message if conflicting options are used together.
|
|
2218
|
+
* Called after checking for help flags in leaf subcommand.
|
|
2219
|
+
*
|
|
2220
|
+
* @private
|
|
2221
|
+
*/
|
|
2222
|
+
_checkForConflictingOptions() {
|
|
2223
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
2224
|
+
cmd._checkForConflictingLocalOptions();
|
|
2225
|
+
});
|
|
2226
|
+
}
|
|
2227
|
+
/**
|
|
2228
|
+
* Parse options from `argv` removing known options,
|
|
2229
|
+
* and return argv split into operands and unknown arguments.
|
|
2230
|
+
*
|
|
2231
|
+
* Side effects: modifies command by storing options. Does not reset state if called again.
|
|
2232
|
+
*
|
|
2233
|
+
* Examples:
|
|
2234
|
+
*
|
|
2235
|
+
* argv => operands, unknown
|
|
2236
|
+
* --known kkk op => [op], []
|
|
2237
|
+
* op --known kkk => [op], []
|
|
2238
|
+
* sub --unknown uuu op => [sub], [--unknown uuu op]
|
|
2239
|
+
* sub -- --unknown uuu op => [sub --unknown uuu op], []
|
|
2240
|
+
*
|
|
2241
|
+
* @param {string[]} args
|
|
2242
|
+
* @return {{operands: string[], unknown: string[]}}
|
|
2243
|
+
*/
|
|
2244
|
+
parseOptions(args) {
|
|
2245
|
+
const operands = [];
|
|
2246
|
+
const unknown = [];
|
|
2247
|
+
let dest = operands;
|
|
2248
|
+
function maybeOption(arg) {
|
|
2249
|
+
return arg.length > 1 && arg[0] === "-";
|
|
2250
|
+
}
|
|
2251
|
+
const negativeNumberArg = (arg) => {
|
|
2252
|
+
if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
|
|
2253
|
+
return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short)));
|
|
2254
|
+
};
|
|
2255
|
+
let activeVariadicOption = null;
|
|
2256
|
+
let activeGroup = null;
|
|
2257
|
+
let i = 0;
|
|
2258
|
+
while (i < args.length || activeGroup) {
|
|
2259
|
+
const arg = activeGroup ?? args[i++];
|
|
2260
|
+
activeGroup = null;
|
|
2261
|
+
if (arg === "--") {
|
|
2262
|
+
if (dest === unknown) dest.push(arg);
|
|
2263
|
+
dest.push(...args.slice(i));
|
|
2264
|
+
break;
|
|
2265
|
+
}
|
|
2266
|
+
if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
|
|
2267
|
+
this.emit(`option:${activeVariadicOption.name()}`, arg);
|
|
2268
|
+
continue;
|
|
2269
|
+
}
|
|
2270
|
+
activeVariadicOption = null;
|
|
2271
|
+
if (maybeOption(arg)) {
|
|
2272
|
+
const option = this._findOption(arg);
|
|
2273
|
+
if (option) {
|
|
2274
|
+
if (option.required) {
|
|
2275
|
+
const value = args[i++];
|
|
2276
|
+
if (value === void 0) this.optionMissingArgument(option);
|
|
2277
|
+
this.emit(`option:${option.name()}`, value);
|
|
2278
|
+
} else if (option.optional) {
|
|
2279
|
+
let value = null;
|
|
2280
|
+
if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) value = args[i++];
|
|
2281
|
+
this.emit(`option:${option.name()}`, value);
|
|
2282
|
+
} else this.emit(`option:${option.name()}`);
|
|
2283
|
+
activeVariadicOption = option.variadic ? option : null;
|
|
2284
|
+
continue;
|
|
2285
|
+
}
|
|
2286
|
+
}
|
|
2287
|
+
if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
|
|
2288
|
+
const option = this._findOption(`-${arg[1]}`);
|
|
2289
|
+
if (option) {
|
|
2290
|
+
if (option.required || option.optional && this._combineFlagAndOptionalValue) this.emit(`option:${option.name()}`, arg.slice(2));
|
|
2291
|
+
else {
|
|
2292
|
+
this.emit(`option:${option.name()}`);
|
|
2293
|
+
activeGroup = `-${arg.slice(2)}`;
|
|
2294
|
+
}
|
|
2295
|
+
continue;
|
|
2296
|
+
}
|
|
2297
|
+
}
|
|
2298
|
+
if (/^--[^=]+=/.test(arg)) {
|
|
2299
|
+
const index = arg.indexOf("=");
|
|
2300
|
+
const option = this._findOption(arg.slice(0, index));
|
|
2301
|
+
if (option && (option.required || option.optional)) {
|
|
2302
|
+
this.emit(`option:${option.name()}`, arg.slice(index + 1));
|
|
2303
|
+
continue;
|
|
2304
|
+
}
|
|
2305
|
+
}
|
|
2306
|
+
if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) dest = unknown;
|
|
2307
|
+
if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
|
|
2308
|
+
if (this._findCommand(arg)) {
|
|
2309
|
+
operands.push(arg);
|
|
2310
|
+
unknown.push(...args.slice(i));
|
|
2311
|
+
break;
|
|
2312
|
+
} else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
|
|
2313
|
+
operands.push(arg, ...args.slice(i));
|
|
2314
|
+
break;
|
|
2315
|
+
} else if (this._defaultCommandName) {
|
|
2316
|
+
unknown.push(arg, ...args.slice(i));
|
|
2317
|
+
break;
|
|
2318
|
+
}
|
|
2319
|
+
}
|
|
2320
|
+
if (this._passThroughOptions) {
|
|
2321
|
+
dest.push(arg, ...args.slice(i));
|
|
2322
|
+
break;
|
|
2323
|
+
}
|
|
2324
|
+
dest.push(arg);
|
|
2325
|
+
}
|
|
2326
|
+
return {
|
|
2327
|
+
operands,
|
|
2328
|
+
unknown
|
|
2329
|
+
};
|
|
2330
|
+
}
|
|
2331
|
+
/**
|
|
2332
|
+
* Return an object containing local option values as key-value pairs.
|
|
2333
|
+
*
|
|
2334
|
+
* @return {object}
|
|
2335
|
+
*/
|
|
2336
|
+
opts() {
|
|
2337
|
+
if (this._storeOptionsAsProperties) {
|
|
2338
|
+
const result = {};
|
|
2339
|
+
const len = this.options.length;
|
|
2340
|
+
for (let i = 0; i < len; i++) {
|
|
2341
|
+
const key = this.options[i].attributeName();
|
|
2342
|
+
result[key] = key === this._versionOptionName ? this._version : this[key];
|
|
2343
|
+
}
|
|
2344
|
+
return result;
|
|
2345
|
+
}
|
|
2346
|
+
return this._optionValues;
|
|
2347
|
+
}
|
|
2348
|
+
/**
|
|
2349
|
+
* Return an object containing merged local and global option values as key-value pairs.
|
|
2350
|
+
*
|
|
2351
|
+
* @return {object}
|
|
2352
|
+
*/
|
|
2353
|
+
optsWithGlobals() {
|
|
2354
|
+
return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
|
|
2355
|
+
}
|
|
2356
|
+
/**
|
|
2357
|
+
* Display error message and exit (or call exitOverride).
|
|
2358
|
+
*
|
|
2359
|
+
* @param {string} message
|
|
2360
|
+
* @param {object} [errorOptions]
|
|
2361
|
+
* @param {string} [errorOptions.code] - an id string representing the error
|
|
2362
|
+
* @param {number} [errorOptions.exitCode] - used with process.exit
|
|
2363
|
+
*/
|
|
2364
|
+
error(message, errorOptions) {
|
|
2365
|
+
this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);
|
|
2366
|
+
if (typeof this._showHelpAfterError === "string") this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);
|
|
2367
|
+
else if (this._showHelpAfterError) {
|
|
2368
|
+
this._outputConfiguration.writeErr("\n");
|
|
2369
|
+
this.outputHelp({ error: true });
|
|
2370
|
+
}
|
|
2371
|
+
const config = errorOptions || {};
|
|
2372
|
+
const exitCode = config.exitCode || 1;
|
|
2373
|
+
const code = config.code || "commander.error";
|
|
2374
|
+
this._exit(exitCode, code, message);
|
|
2375
|
+
}
|
|
2376
|
+
/**
|
|
2377
|
+
* Apply any option related environment variables, if option does
|
|
2378
|
+
* not have a value from cli or client code.
|
|
2379
|
+
*
|
|
2380
|
+
* @private
|
|
2381
|
+
*/
|
|
2382
|
+
_parseOptionsEnv() {
|
|
2383
|
+
this.options.forEach((option) => {
|
|
2384
|
+
if (option.envVar && option.envVar in process$1.env) {
|
|
2385
|
+
const optionKey = option.attributeName();
|
|
2386
|
+
if (this.getOptionValue(optionKey) === void 0 || [
|
|
2387
|
+
"default",
|
|
2388
|
+
"config",
|
|
2389
|
+
"env"
|
|
2390
|
+
].includes(this.getOptionValueSource(optionKey))) {
|
|
2391
|
+
if (option.required || option.optional) this.emit(`optionEnv:${option.name()}`, process$1.env[option.envVar]);
|
|
2392
|
+
else this.emit(`optionEnv:${option.name()}`);
|
|
2393
|
+
}
|
|
2394
|
+
}
|
|
2395
|
+
});
|
|
2396
|
+
}
|
|
2397
|
+
/**
|
|
2398
|
+
* Apply any implied option values, if option is undefined or default value.
|
|
2399
|
+
*
|
|
2400
|
+
* @private
|
|
2401
|
+
*/
|
|
2402
|
+
_parseOptionsImplied() {
|
|
2403
|
+
const dualHelper = new DualOptions(this.options);
|
|
2404
|
+
const hasCustomOptionValue = (optionKey) => {
|
|
2405
|
+
return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
|
|
2406
|
+
};
|
|
2407
|
+
this.options.filter((option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
|
|
2408
|
+
Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
|
|
2409
|
+
this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
|
|
2410
|
+
});
|
|
2411
|
+
});
|
|
2412
|
+
}
|
|
2413
|
+
/**
|
|
2414
|
+
* Argument `name` is missing.
|
|
2415
|
+
*
|
|
2416
|
+
* @param {string} name
|
|
2417
|
+
* @private
|
|
2418
|
+
*/
|
|
2419
|
+
missingArgument(name) {
|
|
2420
|
+
const message = `error: missing required argument '${name}'`;
|
|
2421
|
+
this.error(message, { code: "commander.missingArgument" });
|
|
2422
|
+
}
|
|
2423
|
+
/**
|
|
2424
|
+
* `Option` is missing an argument.
|
|
2425
|
+
*
|
|
2426
|
+
* @param {Option} option
|
|
2427
|
+
* @private
|
|
2428
|
+
*/
|
|
2429
|
+
optionMissingArgument(option) {
|
|
2430
|
+
const message = `error: option '${option.flags}' argument missing`;
|
|
2431
|
+
this.error(message, { code: "commander.optionMissingArgument" });
|
|
2432
|
+
}
|
|
2433
|
+
/**
|
|
2434
|
+
* `Option` does not have a value, and is a mandatory option.
|
|
2435
|
+
*
|
|
2436
|
+
* @param {Option} option
|
|
2437
|
+
* @private
|
|
2438
|
+
*/
|
|
2439
|
+
missingMandatoryOptionValue(option) {
|
|
2440
|
+
const message = `error: required option '${option.flags}' not specified`;
|
|
2441
|
+
this.error(message, { code: "commander.missingMandatoryOptionValue" });
|
|
2442
|
+
}
|
|
2443
|
+
/**
|
|
2444
|
+
* `Option` conflicts with another option.
|
|
2445
|
+
*
|
|
2446
|
+
* @param {Option} option
|
|
2447
|
+
* @param {Option} conflictingOption
|
|
2448
|
+
* @private
|
|
2449
|
+
*/
|
|
2450
|
+
_conflictingOption(option, conflictingOption) {
|
|
2451
|
+
const findBestOptionFromValue = (option) => {
|
|
2452
|
+
const optionKey = option.attributeName();
|
|
2453
|
+
const optionValue = this.getOptionValue(optionKey);
|
|
2454
|
+
const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
|
|
2455
|
+
const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
|
|
2456
|
+
if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) return negativeOption;
|
|
2457
|
+
return positiveOption || option;
|
|
2458
|
+
};
|
|
2459
|
+
const getErrorMessage = (option) => {
|
|
2460
|
+
const bestOption = findBestOptionFromValue(option);
|
|
2461
|
+
const optionKey = bestOption.attributeName();
|
|
2462
|
+
if (this.getOptionValueSource(optionKey) === "env") return `environment variable '${bestOption.envVar}'`;
|
|
2463
|
+
return `option '${bestOption.flags}'`;
|
|
2464
|
+
};
|
|
2465
|
+
const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
|
|
2466
|
+
this.error(message, { code: "commander.conflictingOption" });
|
|
2467
|
+
}
|
|
2468
|
+
/**
|
|
2469
|
+
* Unknown option `flag`.
|
|
2470
|
+
*
|
|
2471
|
+
* @param {string} flag
|
|
2472
|
+
* @private
|
|
2473
|
+
*/
|
|
2474
|
+
unknownOption(flag) {
|
|
2475
|
+
if (this._allowUnknownOption) return;
|
|
2476
|
+
let suggestion = "";
|
|
2477
|
+
if (flag.startsWith("--") && this._showSuggestionAfterError) {
|
|
2478
|
+
let candidateFlags = [];
|
|
2479
|
+
let command = this;
|
|
2480
|
+
do {
|
|
2481
|
+
const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
|
|
2482
|
+
candidateFlags = candidateFlags.concat(moreFlags);
|
|
2483
|
+
command = command.parent;
|
|
2484
|
+
} while (command && !command._enablePositionalOptions);
|
|
2485
|
+
suggestion = suggestSimilar(flag, candidateFlags);
|
|
2486
|
+
}
|
|
2487
|
+
const message = `error: unknown option '${flag}'${suggestion}`;
|
|
2488
|
+
this.error(message, { code: "commander.unknownOption" });
|
|
2489
|
+
}
|
|
2490
|
+
/**
|
|
2491
|
+
* Excess arguments, more than expected.
|
|
2492
|
+
*
|
|
2493
|
+
* @param {string[]} receivedArgs
|
|
2494
|
+
* @private
|
|
2495
|
+
*/
|
|
2496
|
+
_excessArguments(receivedArgs) {
|
|
2497
|
+
if (this._allowExcessArguments) return;
|
|
2498
|
+
const expected = this.registeredArguments.length;
|
|
2499
|
+
const s = expected === 1 ? "" : "s";
|
|
2500
|
+
const received = receivedArgs.length;
|
|
2501
|
+
const message = `error: too many arguments${this.parent ? ` for '${this.name()}'` : ""}. Expected ${expected} argument${s} but got ${received}: ${receivedArgs.join(", ")}.`;
|
|
2502
|
+
this.error(message, { code: "commander.excessArguments" });
|
|
2503
|
+
}
|
|
2504
|
+
/**
|
|
2505
|
+
* Unknown command.
|
|
2506
|
+
*
|
|
2507
|
+
* @private
|
|
2508
|
+
*/
|
|
2509
|
+
unknownCommand() {
|
|
2510
|
+
const unknownName = this.args[0];
|
|
2511
|
+
let suggestion = "";
|
|
2512
|
+
if (this._showSuggestionAfterError) {
|
|
2513
|
+
const candidateNames = [];
|
|
2514
|
+
this.createHelp().visibleCommands(this).forEach((command) => {
|
|
2515
|
+
candidateNames.push(command.name());
|
|
2516
|
+
if (command.alias()) candidateNames.push(command.alias());
|
|
2517
|
+
});
|
|
2518
|
+
suggestion = suggestSimilar(unknownName, candidateNames);
|
|
2519
|
+
}
|
|
2520
|
+
const message = `error: unknown command '${unknownName}'${suggestion}`;
|
|
2521
|
+
this.error(message, { code: "commander.unknownCommand" });
|
|
2522
|
+
}
|
|
2523
|
+
/**
|
|
2524
|
+
* Get or set the program version.
|
|
2525
|
+
*
|
|
2526
|
+
* This method auto-registers the "-V, --version" option which will print the version number.
|
|
2527
|
+
*
|
|
2528
|
+
* You can optionally supply the flags and description to override the defaults.
|
|
2529
|
+
*
|
|
2530
|
+
* @param {string} [str]
|
|
2531
|
+
* @param {string} [flags]
|
|
2532
|
+
* @param {string} [description]
|
|
2533
|
+
* @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
|
|
2534
|
+
*/
|
|
2535
|
+
version(str, flags, description) {
|
|
2536
|
+
if (str === void 0) return this._version;
|
|
2537
|
+
this._version = str;
|
|
2538
|
+
flags = flags || "-V, --version";
|
|
2539
|
+
description = description || "output the version number";
|
|
2540
|
+
const versionOption = this.createOption(flags, description);
|
|
2541
|
+
this._versionOptionName = versionOption.attributeName();
|
|
2542
|
+
this._registerOption(versionOption);
|
|
2543
|
+
this.on("option:" + versionOption.name(), () => {
|
|
2544
|
+
this._outputConfiguration.writeOut(`${str}\n`);
|
|
2545
|
+
this._exit(0, "commander.version", str);
|
|
2546
|
+
});
|
|
2547
|
+
return this;
|
|
2548
|
+
}
|
|
2549
|
+
/**
|
|
2550
|
+
* Set the description.
|
|
2551
|
+
*
|
|
2552
|
+
* @param {string} [str]
|
|
2553
|
+
* @param {object} [argsDescription]
|
|
2554
|
+
* @return {(string|Command)}
|
|
2555
|
+
*/
|
|
2556
|
+
description(str, argsDescription) {
|
|
2557
|
+
if (str === void 0 && argsDescription === void 0) return this._description;
|
|
2558
|
+
this._description = str;
|
|
2559
|
+
if (argsDescription) this._argsDescription = argsDescription;
|
|
2560
|
+
return this;
|
|
2561
|
+
}
|
|
2562
|
+
/**
|
|
2563
|
+
* Set the summary. Used when listed as subcommand of parent.
|
|
2564
|
+
*
|
|
2565
|
+
* @param {string} [str]
|
|
2566
|
+
* @return {(string|Command)}
|
|
2567
|
+
*/
|
|
2568
|
+
summary(str) {
|
|
2569
|
+
if (str === void 0) return this._summary;
|
|
2570
|
+
this._summary = str;
|
|
2571
|
+
return this;
|
|
2572
|
+
}
|
|
2573
|
+
/**
|
|
2574
|
+
* Set an alias for the command.
|
|
2575
|
+
*
|
|
2576
|
+
* You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
|
|
2577
|
+
*
|
|
2578
|
+
* @param {string} [alias]
|
|
2579
|
+
* @return {(string|Command)}
|
|
2580
|
+
*/
|
|
2581
|
+
alias(alias) {
|
|
2582
|
+
if (alias === void 0) return this._aliases[0];
|
|
2583
|
+
/** @type {Command} */
|
|
2584
|
+
let command = this;
|
|
2585
|
+
if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) command = this.commands[this.commands.length - 1];
|
|
2586
|
+
if (alias === command._name) throw new Error("Command alias can't be the same as its name");
|
|
2587
|
+
const matchingCommand = this.parent?._findCommand(alias);
|
|
2588
|
+
if (matchingCommand) {
|
|
2589
|
+
const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
|
|
2590
|
+
throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
|
|
2591
|
+
}
|
|
2592
|
+
command._aliases.push(alias);
|
|
2593
|
+
return this;
|
|
2594
|
+
}
|
|
2595
|
+
/**
|
|
2596
|
+
* Set aliases for the command.
|
|
2597
|
+
*
|
|
2598
|
+
* Only the first alias is shown in the auto-generated help.
|
|
2599
|
+
*
|
|
2600
|
+
* @param {string[]} [aliases]
|
|
2601
|
+
* @return {(string[]|Command)}
|
|
2602
|
+
*/
|
|
2603
|
+
aliases(aliases) {
|
|
2604
|
+
if (aliases === void 0) return this._aliases;
|
|
2605
|
+
aliases.forEach((alias) => this.alias(alias));
|
|
2606
|
+
return this;
|
|
2607
|
+
}
|
|
2608
|
+
/**
|
|
2609
|
+
* Set / get the command usage `str`.
|
|
2610
|
+
*
|
|
2611
|
+
* @param {string} [str]
|
|
2612
|
+
* @return {(string|Command)}
|
|
2613
|
+
*/
|
|
2614
|
+
usage(str) {
|
|
2615
|
+
if (str === void 0) {
|
|
2616
|
+
if (this._usage) return this._usage;
|
|
2617
|
+
const args = this.registeredArguments.map((arg) => {
|
|
2618
|
+
return humanReadableArgName(arg);
|
|
2619
|
+
});
|
|
2620
|
+
return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
|
|
2621
|
+
}
|
|
2622
|
+
this._usage = str;
|
|
2623
|
+
return this;
|
|
2624
|
+
}
|
|
2625
|
+
/**
|
|
2626
|
+
* Get or set the name of the command.
|
|
2627
|
+
*
|
|
2628
|
+
* @param {string} [str]
|
|
2629
|
+
* @return {(string|Command)}
|
|
2630
|
+
*/
|
|
2631
|
+
name(str) {
|
|
2632
|
+
if (str === void 0) return this._name;
|
|
2633
|
+
this._name = str;
|
|
2634
|
+
return this;
|
|
2635
|
+
}
|
|
2636
|
+
/**
|
|
2637
|
+
* Set/get the help group heading for this subcommand in parent command's help.
|
|
2638
|
+
*
|
|
2639
|
+
* @param {string} [heading]
|
|
2640
|
+
* @return {Command | string}
|
|
2641
|
+
*/
|
|
2642
|
+
helpGroup(heading) {
|
|
2643
|
+
if (heading === void 0) return this._helpGroupHeading ?? "";
|
|
2644
|
+
this._helpGroupHeading = heading;
|
|
2645
|
+
return this;
|
|
2646
|
+
}
|
|
2647
|
+
/**
|
|
2648
|
+
* Set/get the default help group heading for subcommands added to this command.
|
|
2649
|
+
* (This does not override a group set directly on the subcommand using .helpGroup().)
|
|
2650
|
+
*
|
|
2651
|
+
* @example
|
|
2652
|
+
* program.commandsGroup('Development Commands:);
|
|
2653
|
+
* program.command('watch')...
|
|
2654
|
+
* program.command('lint')...
|
|
2655
|
+
* ...
|
|
2656
|
+
*
|
|
2657
|
+
* @param {string} [heading]
|
|
2658
|
+
* @returns {Command | string}
|
|
2659
|
+
*/
|
|
2660
|
+
commandsGroup(heading) {
|
|
2661
|
+
if (heading === void 0) return this._defaultCommandGroup ?? "";
|
|
2662
|
+
this._defaultCommandGroup = heading;
|
|
2663
|
+
return this;
|
|
2664
|
+
}
|
|
2665
|
+
/**
|
|
2666
|
+
* Set/get the default help group heading for options added to this command.
|
|
2667
|
+
* (This does not override a group set directly on the option using .helpGroup().)
|
|
2668
|
+
*
|
|
2669
|
+
* @example
|
|
2670
|
+
* program
|
|
2671
|
+
* .optionsGroup('Development Options:')
|
|
2672
|
+
* .option('-d, --debug', 'output extra debugging')
|
|
2673
|
+
* .option('-p, --profile', 'output profiling information')
|
|
2674
|
+
*
|
|
2675
|
+
* @param {string} [heading]
|
|
2676
|
+
* @returns {Command | string}
|
|
2677
|
+
*/
|
|
2678
|
+
optionsGroup(heading) {
|
|
2679
|
+
if (heading === void 0) return this._defaultOptionGroup ?? "";
|
|
2680
|
+
this._defaultOptionGroup = heading;
|
|
2681
|
+
return this;
|
|
2682
|
+
}
|
|
2683
|
+
/**
|
|
2684
|
+
* @param {Option} option
|
|
2685
|
+
* @private
|
|
2686
|
+
*/
|
|
2687
|
+
_initOptionGroup(option) {
|
|
2688
|
+
if (this._defaultOptionGroup && !option.helpGroupHeading) option.helpGroup(this._defaultOptionGroup);
|
|
2689
|
+
}
|
|
2690
|
+
/**
|
|
2691
|
+
* @param {Command} cmd
|
|
2692
|
+
* @private
|
|
2693
|
+
*/
|
|
2694
|
+
_initCommandGroup(cmd) {
|
|
2695
|
+
if (this._defaultCommandGroup && !cmd.helpGroup()) cmd.helpGroup(this._defaultCommandGroup);
|
|
2696
|
+
}
|
|
2697
|
+
/**
|
|
2698
|
+
* Set the name of the command from script filename, such as process.argv[1],
|
|
2699
|
+
* or import.meta.filename.
|
|
2700
|
+
*
|
|
2701
|
+
* (Used internally and public although not documented in README.)
|
|
2702
|
+
*
|
|
2703
|
+
* @example
|
|
2704
|
+
* program.nameFromFilename(import.meta.filename);
|
|
2705
|
+
*
|
|
2706
|
+
* @param {string} filename
|
|
2707
|
+
* @return {Command}
|
|
2708
|
+
*/
|
|
2709
|
+
nameFromFilename(filename) {
|
|
2710
|
+
this._name = path.basename(filename, path.extname(filename));
|
|
2711
|
+
return this;
|
|
2712
|
+
}
|
|
2713
|
+
/**
|
|
2714
|
+
* Get or set the directory for searching for executable subcommands of this command.
|
|
2715
|
+
*
|
|
2716
|
+
* @example
|
|
2717
|
+
* program.executableDir(import.meta.dirname);
|
|
2718
|
+
* // or
|
|
2719
|
+
* program.executableDir('subcommands');
|
|
2720
|
+
*
|
|
2721
|
+
* @param {string} [path]
|
|
2722
|
+
* @return {(string|null|Command)}
|
|
2723
|
+
*/
|
|
2724
|
+
executableDir(path) {
|
|
2725
|
+
if (path === void 0) return this._executableDir;
|
|
2726
|
+
this._executableDir = path;
|
|
2727
|
+
return this;
|
|
2728
|
+
}
|
|
2729
|
+
/**
|
|
2730
|
+
* Return program help documentation.
|
|
2731
|
+
*
|
|
2732
|
+
* @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
|
|
2733
|
+
* @return {string}
|
|
2734
|
+
*/
|
|
2735
|
+
helpInformation(contextOptions) {
|
|
2736
|
+
const helper = this.createHelp();
|
|
2737
|
+
const context = this._getOutputContext(contextOptions);
|
|
2738
|
+
helper.prepareContext({
|
|
2739
|
+
error: context.error,
|
|
2740
|
+
helpWidth: context.helpWidth,
|
|
2741
|
+
outputHasColors: context.hasColors
|
|
2742
|
+
});
|
|
2743
|
+
const text = helper.formatHelp(this, helper);
|
|
2744
|
+
if (context.hasColors) return text;
|
|
2745
|
+
return this._outputConfiguration.stripColor(text);
|
|
2746
|
+
}
|
|
2747
|
+
/**
|
|
2748
|
+
* @typedef HelpContext
|
|
2749
|
+
* @type {object}
|
|
2750
|
+
* @property {boolean} error
|
|
2751
|
+
* @property {number} helpWidth
|
|
2752
|
+
* @property {boolean} hasColors
|
|
2753
|
+
* @property {function} write - includes stripColor if needed
|
|
2754
|
+
*
|
|
2755
|
+
* @returns {HelpContext}
|
|
2756
|
+
* @private
|
|
2757
|
+
*/
|
|
2758
|
+
_getOutputContext(contextOptions) {
|
|
2759
|
+
contextOptions = contextOptions || {};
|
|
2760
|
+
const error = !!contextOptions.error;
|
|
2761
|
+
let baseWrite;
|
|
2762
|
+
let hasColors;
|
|
2763
|
+
let helpWidth;
|
|
2764
|
+
if (error) {
|
|
2765
|
+
baseWrite = (str) => this._outputConfiguration.writeErr(str);
|
|
2766
|
+
hasColors = this._outputConfiguration.getErrHasColors();
|
|
2767
|
+
helpWidth = this._outputConfiguration.getErrHelpWidth();
|
|
2768
|
+
} else {
|
|
2769
|
+
baseWrite = (str) => this._outputConfiguration.writeOut(str);
|
|
2770
|
+
hasColors = this._outputConfiguration.getOutHasColors();
|
|
2771
|
+
helpWidth = this._outputConfiguration.getOutHelpWidth();
|
|
2772
|
+
}
|
|
2773
|
+
const write = (str) => {
|
|
2774
|
+
if (!hasColors) str = this._outputConfiguration.stripColor(str);
|
|
2775
|
+
return baseWrite(str);
|
|
2776
|
+
};
|
|
2777
|
+
return {
|
|
2778
|
+
error,
|
|
2779
|
+
write,
|
|
2780
|
+
hasColors,
|
|
2781
|
+
helpWidth
|
|
2782
|
+
};
|
|
2783
|
+
}
|
|
2784
|
+
/**
|
|
2785
|
+
* Output help information for this command.
|
|
2786
|
+
*
|
|
2787
|
+
* Outputs built-in help, and custom text added using `.addHelpText()`.
|
|
2788
|
+
*
|
|
2789
|
+
* @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
|
|
2790
|
+
*/
|
|
2791
|
+
outputHelp(contextOptions) {
|
|
2792
|
+
let deprecatedCallback;
|
|
2793
|
+
if (typeof contextOptions === "function") {
|
|
2794
|
+
deprecatedCallback = contextOptions;
|
|
2795
|
+
contextOptions = void 0;
|
|
2796
|
+
}
|
|
2797
|
+
const outputContext = this._getOutputContext(contextOptions);
|
|
2798
|
+
/** @type {HelpTextEventContext} */
|
|
2799
|
+
const eventContext = {
|
|
2800
|
+
error: outputContext.error,
|
|
2801
|
+
write: outputContext.write,
|
|
2802
|
+
command: this
|
|
2803
|
+
};
|
|
2804
|
+
this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
|
|
2805
|
+
this.emit("beforeHelp", eventContext);
|
|
2806
|
+
let helpInformation = this.helpInformation({ error: outputContext.error });
|
|
2807
|
+
if (deprecatedCallback) {
|
|
2808
|
+
helpInformation = deprecatedCallback(helpInformation);
|
|
2809
|
+
if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) throw new Error("outputHelp callback must return a string or a Buffer");
|
|
2810
|
+
}
|
|
2811
|
+
outputContext.write(helpInformation);
|
|
2812
|
+
if (this._getHelpOption()?.long) this.emit(this._getHelpOption().long);
|
|
2813
|
+
this.emit("afterHelp", eventContext);
|
|
2814
|
+
this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
|
|
2815
|
+
}
|
|
2816
|
+
/**
|
|
2817
|
+
* You can pass in flags and a description to customise the built-in help option.
|
|
2818
|
+
* Pass in false to disable the built-in help option.
|
|
2819
|
+
*
|
|
2820
|
+
* @example
|
|
2821
|
+
* program.helpOption('-?, --help' 'show help'); // customise
|
|
2822
|
+
* program.helpOption(false); // disable
|
|
2823
|
+
*
|
|
2824
|
+
* @param {(string | boolean)} flags
|
|
2825
|
+
* @param {string} [description]
|
|
2826
|
+
* @return {Command} `this` command for chaining
|
|
2827
|
+
*/
|
|
2828
|
+
helpOption(flags, description) {
|
|
2829
|
+
if (typeof flags === "boolean") {
|
|
2830
|
+
if (flags) {
|
|
2831
|
+
if (this._helpOption === null) this._helpOption = void 0;
|
|
2832
|
+
if (this._defaultOptionGroup) this._initOptionGroup(this._getHelpOption());
|
|
2833
|
+
} else this._helpOption = null;
|
|
2834
|
+
return this;
|
|
2835
|
+
}
|
|
2836
|
+
this._helpOption = this.createOption(flags ?? "-h, --help", description ?? "display help for command");
|
|
2837
|
+
if (flags || description) this._initOptionGroup(this._helpOption);
|
|
2838
|
+
return this;
|
|
2839
|
+
}
|
|
2840
|
+
/**
|
|
2841
|
+
* Lazy create help option.
|
|
2842
|
+
* Returns null if has been disabled with .helpOption(false).
|
|
2843
|
+
*
|
|
2844
|
+
* @returns {(Option | null)} the help option
|
|
2845
|
+
* @package
|
|
2846
|
+
*/
|
|
2847
|
+
_getHelpOption() {
|
|
2848
|
+
if (this._helpOption === void 0) this.helpOption(void 0, void 0);
|
|
2849
|
+
return this._helpOption;
|
|
2850
|
+
}
|
|
2851
|
+
/**
|
|
2852
|
+
* Supply your own option to use for the built-in help option.
|
|
2853
|
+
* This is an alternative to using helpOption() to customise the flags and description etc.
|
|
2854
|
+
*
|
|
2855
|
+
* @param {Option} option
|
|
2856
|
+
* @return {Command} `this` command for chaining
|
|
2857
|
+
*/
|
|
2858
|
+
addHelpOption(option) {
|
|
2859
|
+
this._helpOption = option;
|
|
2860
|
+
this._initOptionGroup(option);
|
|
2861
|
+
return this;
|
|
2862
|
+
}
|
|
2863
|
+
/**
|
|
2864
|
+
* Output help information and exit.
|
|
2865
|
+
*
|
|
2866
|
+
* Outputs built-in help, and custom text added using `.addHelpText()`.
|
|
2867
|
+
*
|
|
2868
|
+
* @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
|
|
2869
|
+
*/
|
|
2870
|
+
help(contextOptions) {
|
|
2871
|
+
this.outputHelp(contextOptions);
|
|
2872
|
+
let exitCode = Number(process$1.exitCode ?? 0);
|
|
2873
|
+
if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) exitCode = 1;
|
|
2874
|
+
this._exit(exitCode, "commander.help", "(outputHelp)");
|
|
2875
|
+
}
|
|
2876
|
+
/**
|
|
2877
|
+
* // Do a little typing to coordinate emit and listener for the help text events.
|
|
2878
|
+
* @typedef HelpTextEventContext
|
|
2879
|
+
* @type {object}
|
|
2880
|
+
* @property {boolean} error
|
|
2881
|
+
* @property {Command} command
|
|
2882
|
+
* @property {function} write
|
|
2883
|
+
*/
|
|
2884
|
+
/**
|
|
2885
|
+
* Add additional text to be displayed with the built-in help.
|
|
2886
|
+
*
|
|
2887
|
+
* Position is 'before' or 'after' to affect just this command,
|
|
2888
|
+
* and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
|
|
2889
|
+
*
|
|
2890
|
+
* @param {string} position - before or after built-in help
|
|
2891
|
+
* @param {(string | Function)} text - string to add, or a function returning a string
|
|
2892
|
+
* @return {Command} `this` command for chaining
|
|
2893
|
+
*/
|
|
2894
|
+
addHelpText(position, text) {
|
|
2895
|
+
const allowedValues = [
|
|
2896
|
+
"beforeAll",
|
|
2897
|
+
"before",
|
|
2898
|
+
"after",
|
|
2899
|
+
"afterAll"
|
|
2900
|
+
];
|
|
2901
|
+
if (!allowedValues.includes(position)) throw new Error(`Unexpected value for position to addHelpText.
|
|
2902
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
2903
|
+
const helpEvent = `${position}Help`;
|
|
2904
|
+
this.on(helpEvent, (context) => {
|
|
2905
|
+
let helpStr;
|
|
2906
|
+
if (typeof text === "function") helpStr = text({
|
|
2907
|
+
error: context.error,
|
|
2908
|
+
command: context.command
|
|
2909
|
+
});
|
|
2910
|
+
else helpStr = text;
|
|
2911
|
+
if (helpStr) context.write(`${helpStr}\n`);
|
|
2912
|
+
});
|
|
2913
|
+
return this;
|
|
2914
|
+
}
|
|
2915
|
+
/**
|
|
2916
|
+
* Output help information if help flags specified
|
|
2917
|
+
*
|
|
2918
|
+
* @param {Array} args - array of options to search for help flags
|
|
2919
|
+
* @private
|
|
2920
|
+
*/
|
|
2921
|
+
_outputHelpIfRequested(args) {
|
|
2922
|
+
const helpOption = this._getHelpOption();
|
|
2923
|
+
if (helpOption && args.find((arg) => helpOption.is(arg))) {
|
|
2924
|
+
this.outputHelp();
|
|
2925
|
+
this._exit(0, "commander.helpDisplayed", "(outputHelp)");
|
|
2926
|
+
}
|
|
2927
|
+
}
|
|
2928
|
+
};
|
|
2929
|
+
/**
|
|
2930
|
+
* Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
|
|
2931
|
+
*
|
|
2932
|
+
* @param {string[]} args - array of arguments from node.execArgv
|
|
2933
|
+
* @returns {string[]}
|
|
2934
|
+
* @private
|
|
2935
|
+
*/
|
|
2936
|
+
function incrementNodeInspectorPort(args) {
|
|
2937
|
+
return args.map((arg) => {
|
|
2938
|
+
if (!arg.startsWith("--inspect")) return arg;
|
|
2939
|
+
let debugOption;
|
|
2940
|
+
let debugHost = "127.0.0.1";
|
|
2941
|
+
let debugPort = "9229";
|
|
2942
|
+
let match;
|
|
2943
|
+
if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) debugOption = match[1];
|
|
2944
|
+
else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
|
|
2945
|
+
debugOption = match[1];
|
|
2946
|
+
if (/^\d+$/.test(match[3])) debugPort = match[3];
|
|
2947
|
+
else debugHost = match[3];
|
|
2948
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
|
|
2949
|
+
debugOption = match[1];
|
|
2950
|
+
debugHost = match[3];
|
|
2951
|
+
debugPort = match[4];
|
|
2952
|
+
}
|
|
2953
|
+
if (debugOption && debugPort !== "0") return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
|
|
2954
|
+
return arg;
|
|
2955
|
+
});
|
|
2956
|
+
}
|
|
2957
|
+
/**
|
|
2958
|
+
* Exported for using from tests, not otherwise used outside this file.
|
|
2959
|
+
*
|
|
2960
|
+
* @returns {boolean | undefined}
|
|
2961
|
+
* @package
|
|
2962
|
+
*/
|
|
2963
|
+
function useColor() {
|
|
2964
|
+
if (process$1.env.NO_COLOR || process$1.env.FORCE_COLOR === "0" || process$1.env.FORCE_COLOR === "false") return false;
|
|
2965
|
+
if (process$1.env.FORCE_COLOR || process$1.env.CLICOLOR_FORCE !== void 0) return true;
|
|
2966
|
+
}
|
|
2967
|
+
new Command();
|
|
2968
|
+
//#endregion
|
|
2969
|
+
//#region src/doctor/doctor.ts
|
|
2970
|
+
async function inspectStateFile(stateRoot, name) {
|
|
2971
|
+
let bytes;
|
|
2972
|
+
try {
|
|
2973
|
+
bytes = await readFile(join(stateRoot, name));
|
|
2974
|
+
} catch (error) {
|
|
2975
|
+
if (error.code === "ENOENT") return {
|
|
2976
|
+
status: "missing",
|
|
2977
|
+
storeVersion: null,
|
|
2978
|
+
bytes: null,
|
|
2979
|
+
errorCode: null,
|
|
2980
|
+
detail: null
|
|
2981
|
+
};
|
|
2982
|
+
throw error;
|
|
2983
|
+
}
|
|
2984
|
+
try {
|
|
2985
|
+
const decoded = decodeStateFile(bytes, name);
|
|
2986
|
+
const blobs = new Set(await readdir(join(stateRoot, "blobs")).catch(() => []));
|
|
2987
|
+
for (const blob of referencedBlobs(decoded.payload)) if (!blobs.has(blob)) return {
|
|
2988
|
+
status: "corrupt",
|
|
2989
|
+
storeVersion: decoded.storeVersion,
|
|
2990
|
+
bytes: bytes.byteLength,
|
|
2991
|
+
errorCode: "E_STATE_CORRUPT",
|
|
2992
|
+
detail: "missing-blob"
|
|
2993
|
+
};
|
|
2994
|
+
return {
|
|
2995
|
+
status: "ok",
|
|
2996
|
+
storeVersion: decoded.storeVersion,
|
|
2997
|
+
bytes: bytes.byteLength,
|
|
2998
|
+
errorCode: null,
|
|
2999
|
+
detail: null
|
|
3000
|
+
};
|
|
3001
|
+
} catch (error) {
|
|
3002
|
+
if (!isVdeError(error)) throw error;
|
|
3003
|
+
return {
|
|
3004
|
+
status: error.code === "E_STATE_FORMAT_UNSUPPORTED" ? "unsupported" : "corrupt",
|
|
3005
|
+
storeVersion: null,
|
|
3006
|
+
bytes: bytes.byteLength,
|
|
3007
|
+
errorCode: error.code,
|
|
3008
|
+
detail: error.message
|
|
3009
|
+
};
|
|
3010
|
+
}
|
|
3011
|
+
}
|
|
3012
|
+
function isBroken(state, previous) {
|
|
3013
|
+
return state.status === "corrupt" || state.status === "missing" && previous.status !== "missing";
|
|
3014
|
+
}
|
|
3015
|
+
async function runDoctor(options) {
|
|
3016
|
+
const { environment, control, version } = options;
|
|
3017
|
+
const probe = options.probe ?? systemProcessProbe;
|
|
3018
|
+
const stateRoot = control.stateRoot;
|
|
3019
|
+
const secure = {
|
|
3020
|
+
uid: environment.uid,
|
|
3021
|
+
platform: environment.platform
|
|
3022
|
+
};
|
|
3023
|
+
const warnings = [];
|
|
3024
|
+
const problems = [];
|
|
3025
|
+
const repairs = [];
|
|
3026
|
+
const rootInspection = await inspectPrivateDirectory(stateRoot, secure);
|
|
3027
|
+
const rootSecure = rootInspection === "ok";
|
|
3028
|
+
const rootReason = rootInspection === "ok" || rootInspection === "missing" ? null : rootInspection;
|
|
3029
|
+
if (rootReason) {
|
|
3030
|
+
problems.push({
|
|
3031
|
+
code: "E_INSECURE_PATH",
|
|
3032
|
+
message: `The state root is not secure (${rootReason}).`,
|
|
3033
|
+
repairable: false
|
|
3034
|
+
});
|
|
3035
|
+
if (options.repair) throw new VdeError("E_INSECURE_PATH", `${stateRoot} is not secure, so it will not be repaired.`, {
|
|
3036
|
+
path: stateRoot,
|
|
3037
|
+
reason: rootReason
|
|
3038
|
+
});
|
|
3039
|
+
}
|
|
3040
|
+
let reachable = false;
|
|
3041
|
+
if (rootSecure) {
|
|
3042
|
+
const connection = await control.connectExisting().catch(() => null);
|
|
3043
|
+
reachable = connection !== null;
|
|
3044
|
+
connection?.close();
|
|
3045
|
+
}
|
|
3046
|
+
const readLockState = async () => {
|
|
3047
|
+
const lock = await readCurrentLock(stateRoot, DAEMON_LOCK_NAME);
|
|
3048
|
+
if (lock === "invalid") return {
|
|
3049
|
+
state: "invalid",
|
|
3050
|
+
pid: null
|
|
3051
|
+
};
|
|
3052
|
+
if (!lock || lock.released) return {
|
|
3053
|
+
state: "none",
|
|
3054
|
+
pid: null
|
|
3055
|
+
};
|
|
3056
|
+
return {
|
|
3057
|
+
state: await inspectOwner(lock, probe) === "alive" ? "owner-alive" : "owner-stopped",
|
|
3058
|
+
pid: lock.pid
|
|
3059
|
+
};
|
|
3060
|
+
};
|
|
3061
|
+
let lock = await readLockState();
|
|
3062
|
+
const location = resolveRuntimeLocation(stateRoot, environment);
|
|
3063
|
+
if (!reachable && lock.state === "owner-stopped") problems.push({
|
|
3064
|
+
code: "W_STALE_RUNTIME",
|
|
3065
|
+
message: "The lock and runtime of a stopped daemon remain.",
|
|
3066
|
+
repairable: true
|
|
3067
|
+
});
|
|
3068
|
+
if (!reachable && lock.state === "owner-alive") problems.push({
|
|
3069
|
+
code: "E_DAEMON_LOCKED",
|
|
3070
|
+
message: "The lock owner is alive, but the daemon cannot be reached. Check the owner process.",
|
|
3071
|
+
repairable: false
|
|
3072
|
+
});
|
|
3073
|
+
if (lock.state === "invalid") problems.push({
|
|
3074
|
+
code: "E_DAEMON_LOCKED",
|
|
3075
|
+
message: "The daemon lock cannot be read.",
|
|
3076
|
+
repairable: false
|
|
3077
|
+
});
|
|
3078
|
+
let state = await inspectStateFile(stateRoot, "state.json");
|
|
3079
|
+
let previousState = await inspectStateFile(stateRoot, "state.prev.json");
|
|
3080
|
+
if (isBroken(state, previousState)) problems.push({
|
|
3081
|
+
code: "E_STATE_CORRUPT",
|
|
3082
|
+
message: previousState.status === "ok" ? "state.json cannot be read. It can be rolled back to the previous state, but the last change will be lost." : "state.json cannot be read, and there is no verified backup.",
|
|
3083
|
+
repairable: previousState.status === "ok"
|
|
3084
|
+
});
|
|
3085
|
+
if (state.status === "unsupported") problems.push({
|
|
3086
|
+
code: "E_STATE_FORMAT_UNSUPPORTED",
|
|
3087
|
+
message: "The state was written by a newer version of vde-open. Use that version.",
|
|
3088
|
+
repairable: false
|
|
3089
|
+
});
|
|
3090
|
+
if (options.repair && rootSecure) {
|
|
3091
|
+
const ownerId = `doctor_${randomUUID()}`;
|
|
3092
|
+
const hadStaleOwner = lock.state === "owner-stopped";
|
|
3093
|
+
const outcome = await acquireLock(stateRoot, DAEMON_LOCK_NAME, {
|
|
3094
|
+
pid: process.pid,
|
|
3095
|
+
ownerId
|
|
3096
|
+
}, probe);
|
|
3097
|
+
if (!outcome.acquired) throw new VdeError("E_DAEMON_LOCKED", outcome.reason === "invalid" ? "The daemon lock cannot be read, so nothing will be repaired." : "The daemon is running, or the lock owner is alive. Stop it before repairing.", { reason: outcome.reason });
|
|
3098
|
+
try {
|
|
3099
|
+
const pointer = await readPointer(stateRoot);
|
|
3100
|
+
let removed = false;
|
|
3101
|
+
if (pointer) {
|
|
3102
|
+
await removeWithRetry(join(stateRoot, POINTER_FILE));
|
|
3103
|
+
removed = true;
|
|
3104
|
+
}
|
|
3105
|
+
if (await inspectPrivateDirectory(location.runtimeDir, secure) === "ok") {
|
|
3106
|
+
for (const path of [...environment.platform === "win32" ? [] : [location.socketPath], location.keyPath]) if (await lstat(path).catch(() => null) !== null) {
|
|
3107
|
+
await removeWithRetry(path);
|
|
3108
|
+
removed = true;
|
|
3109
|
+
}
|
|
3110
|
+
}
|
|
3111
|
+
if (hadStaleOwner || removed) repairs.push("stale-runtime-removed");
|
|
3112
|
+
state = await inspectStateFile(stateRoot, "state.json");
|
|
3113
|
+
previousState = await inspectStateFile(stateRoot, "state.prev.json");
|
|
3114
|
+
if (isBroken(state, previousState) && previousState.status === "ok") {
|
|
3115
|
+
const statePath = join(stateRoot, "state.json");
|
|
3116
|
+
if (state.status !== "missing") await renameWithRetry(statePath, join(stateRoot, `state.json.corrupt-${Date.now().toString()}`));
|
|
3117
|
+
const temp = join(stateRoot, `.tmp-repair-${randomUUID()}`);
|
|
3118
|
+
await writeFile(temp, await readFile(join(stateRoot, "state.prev.json")), { mode: 384 });
|
|
3119
|
+
await renameWithRetry(temp, statePath);
|
|
3120
|
+
repairs.push("state-restored-from-backup");
|
|
3121
|
+
warnings.push({
|
|
3122
|
+
code: "W_STATE_ROLLED_BACK",
|
|
3123
|
+
message: "The state was rolled back to the previous backup. The last change may have been lost.",
|
|
3124
|
+
details: { storeVersion: previousState.storeVersion }
|
|
3125
|
+
});
|
|
3126
|
+
state = await inspectStateFile(stateRoot, "state.json");
|
|
3127
|
+
}
|
|
3128
|
+
} finally {
|
|
3129
|
+
await releaseLock(stateRoot, DAEMON_LOCK_NAME, ownerId);
|
|
3130
|
+
}
|
|
3131
|
+
lock = await readLockState();
|
|
3132
|
+
}
|
|
3133
|
+
let blobCount = 0;
|
|
3134
|
+
let blobBytes = 0;
|
|
3135
|
+
for (const name of await readdir(join(stateRoot, "blobs")).catch(() => [])) {
|
|
3136
|
+
const size = await stat$1(join(stateRoot, "blobs", name)).then((stats) => stats.size, () => 0);
|
|
3137
|
+
blobCount += 1;
|
|
3138
|
+
blobBytes += size;
|
|
3139
|
+
}
|
|
3140
|
+
return {
|
|
3141
|
+
report: {
|
|
3142
|
+
version,
|
|
3143
|
+
protocolVersion: 1,
|
|
3144
|
+
stateFormatVersion: 1,
|
|
3145
|
+
stateRoot: {
|
|
3146
|
+
path: stateRoot,
|
|
3147
|
+
exists: rootInspection !== "missing",
|
|
3148
|
+
secure: rootSecure,
|
|
3149
|
+
reason: rootReason
|
|
3150
|
+
},
|
|
3151
|
+
state,
|
|
3152
|
+
previousState,
|
|
3153
|
+
daemon: {
|
|
3154
|
+
reachable,
|
|
3155
|
+
lock: lock.state,
|
|
3156
|
+
lockPid: lock.pid,
|
|
3157
|
+
pointer: await readPointer(stateRoot) !== null
|
|
3158
|
+
},
|
|
3159
|
+
runtime: {
|
|
3160
|
+
path: location.runtimeDir,
|
|
3161
|
+
exists: await lstat(location.runtimeDir).catch(() => null) !== null
|
|
3162
|
+
},
|
|
3163
|
+
storage: {
|
|
3164
|
+
blobCount,
|
|
3165
|
+
blobBytes,
|
|
3166
|
+
blobLimitBytes: LIMITS.blobStoreBytes
|
|
3167
|
+
},
|
|
3168
|
+
problems,
|
|
3169
|
+
repairs
|
|
3170
|
+
},
|
|
3171
|
+
warnings
|
|
3172
|
+
};
|
|
3173
|
+
}
|
|
3174
|
+
//#endregion
|
|
3175
|
+
//#region src/cli/argv.ts
|
|
3176
|
+
function normalizeArgv(argv, stdinIsPiped, rules) {
|
|
3177
|
+
let firstPositional;
|
|
3178
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
3179
|
+
const token = argv[index];
|
|
3180
|
+
if (token === "--" || token === "-") return ["open", ...argv];
|
|
3181
|
+
if (token.startsWith("-")) {
|
|
3182
|
+
if (rules.valueOptions.has(token)) index += 1;
|
|
3183
|
+
continue;
|
|
3184
|
+
}
|
|
3185
|
+
firstPositional = token;
|
|
3186
|
+
break;
|
|
3187
|
+
}
|
|
3188
|
+
if (firstPositional !== void 0) return rules.subcommands.has(firstPositional) ? argv : ["open", ...argv];
|
|
3189
|
+
const asksForInfo = argv.some((token) => [
|
|
3190
|
+
"-h",
|
|
3191
|
+
"--help",
|
|
3192
|
+
"-V",
|
|
3193
|
+
"--version"
|
|
3194
|
+
].includes(token));
|
|
3195
|
+
if (stdinIsPiped && !asksForInfo) return ["open", ...argv];
|
|
3196
|
+
return argv;
|
|
3197
|
+
}
|
|
3198
|
+
//#endregion
|
|
3199
|
+
//#region src/cli/browser.ts
|
|
3200
|
+
const LAUNCH_WAIT_MS = 3e3;
|
|
3201
|
+
function launchCommand(env, platform, url) {
|
|
3202
|
+
const override = env["BROWSER"];
|
|
3203
|
+
if (override !== void 0 && override !== "") return {
|
|
3204
|
+
command: override,
|
|
3205
|
+
args: [url]
|
|
3206
|
+
};
|
|
3207
|
+
if (platform === "darwin") return {
|
|
3208
|
+
command: "open",
|
|
3209
|
+
args: [url]
|
|
3210
|
+
};
|
|
3211
|
+
if (platform === "win32") return {
|
|
3212
|
+
command: "rundll32",
|
|
3213
|
+
args: ["url.dll,FileProtocolHandler", url]
|
|
3214
|
+
};
|
|
3215
|
+
return {
|
|
3216
|
+
command: "xdg-open",
|
|
3217
|
+
args: [url]
|
|
3218
|
+
};
|
|
3219
|
+
}
|
|
3220
|
+
function createBrowserLauncher(env, platform) {
|
|
3221
|
+
return { open(url) {
|
|
3222
|
+
return new Promise((resolve) => {
|
|
3223
|
+
const { command, args } = launchCommand(env, platform, url);
|
|
3224
|
+
let settled = false;
|
|
3225
|
+
const settle = (opened) => {
|
|
3226
|
+
if (settled) return;
|
|
3227
|
+
settled = true;
|
|
3228
|
+
clearTimeout(timer);
|
|
3229
|
+
resolve(opened);
|
|
3230
|
+
};
|
|
3231
|
+
const child = spawn(command, args, {
|
|
3232
|
+
detached: true,
|
|
3233
|
+
stdio: "ignore",
|
|
3234
|
+
env
|
|
3235
|
+
});
|
|
3236
|
+
const timer = setTimeout(() => settle(true), LAUNCH_WAIT_MS);
|
|
3237
|
+
child.on("error", () => settle(false));
|
|
3238
|
+
child.on("exit", (code) => settle(code === 0));
|
|
3239
|
+
child.unref();
|
|
3240
|
+
});
|
|
3241
|
+
} };
|
|
3242
|
+
}
|
|
3243
|
+
function unavailable(message, cause) {
|
|
3244
|
+
return new VdeError("E_DAEMON_UNAVAILABLE", message, {}, { cause });
|
|
3245
|
+
}
|
|
3246
|
+
function connectIpc(options) {
|
|
3247
|
+
return new Promise((resolve, reject) => {
|
|
3248
|
+
const socket = connect(options.socketPath);
|
|
3249
|
+
const clientNonce = createNonce();
|
|
3250
|
+
const decoder = new FrameDecoder(() => phase === "ready" ? LIMITS.ipcFrameBytes : LIMITS.ipcPreAuthFrameBytes);
|
|
3251
|
+
const pending = /* @__PURE__ */ new Map();
|
|
3252
|
+
let phase = "await-hello";
|
|
3253
|
+
let daemonId = "";
|
|
3254
|
+
const rejectPending = (error) => {
|
|
3255
|
+
for (const waiter of pending.values()) {
|
|
3256
|
+
clearTimeout(waiter.timer);
|
|
3257
|
+
waiter.reject(error);
|
|
3258
|
+
}
|
|
3259
|
+
pending.clear();
|
|
3260
|
+
};
|
|
3261
|
+
const failAll = (error) => {
|
|
3262
|
+
if (phase !== "ready") reject(error);
|
|
3263
|
+
phase = "closed";
|
|
3264
|
+
clearTimeout(timer);
|
|
3265
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
3266
|
+
rejectPending(error);
|
|
3267
|
+
socket.destroy();
|
|
3268
|
+
};
|
|
3269
|
+
const timer = setTimeout(() => {
|
|
3270
|
+
failAll(unavailable("The handshake with the daemon did not finish in time."));
|
|
3271
|
+
}, options.timeoutMs ?? 5e3);
|
|
3272
|
+
const onAbort = () => {
|
|
3273
|
+
if (phase !== "ready") failAll(unavailable("The connection to the daemon was aborted."));
|
|
3274
|
+
};
|
|
3275
|
+
if (options.signal?.aborted) onAbort();
|
|
3276
|
+
else options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
3277
|
+
const connection = {
|
|
3278
|
+
get daemonId() {
|
|
3279
|
+
return daemonId;
|
|
3280
|
+
},
|
|
3281
|
+
request(method, params, requestOptions = {}) {
|
|
3282
|
+
return new Promise((resolveRequest, rejectRequest) => {
|
|
3283
|
+
if (phase !== "ready") {
|
|
3284
|
+
rejectRequest(unavailable("The connection to the daemon is closed."));
|
|
3285
|
+
return;
|
|
3286
|
+
}
|
|
3287
|
+
const id = randomUUID();
|
|
3288
|
+
const requestTimer = setTimeout(() => {
|
|
3289
|
+
pending.delete(id);
|
|
3290
|
+
rejectRequest(unavailable("The daemon did not respond in time."));
|
|
3291
|
+
}, requestOptions.timeoutMs ?? 6e4);
|
|
3292
|
+
pending.set(id, {
|
|
3293
|
+
resolve: (envelope) => resolveRequest(envelope),
|
|
3294
|
+
reject: rejectRequest,
|
|
3295
|
+
timer: requestTimer
|
|
3296
|
+
});
|
|
3297
|
+
socket.write(encodeFrame({
|
|
3298
|
+
id,
|
|
3299
|
+
method,
|
|
3300
|
+
params
|
|
3301
|
+
}));
|
|
3302
|
+
});
|
|
3303
|
+
},
|
|
3304
|
+
close() {
|
|
3305
|
+
phase = "closed";
|
|
3306
|
+
clearTimeout(timer);
|
|
3307
|
+
rejectPending(unavailable("The connection to the daemon was closed."));
|
|
3308
|
+
socket.destroy();
|
|
3309
|
+
}
|
|
3310
|
+
};
|
|
3311
|
+
const handleFrame = (frame) => {
|
|
3312
|
+
if (frame["type"] === "error") {
|
|
3313
|
+
const code = frame["code"] === "E_PROTOCOL_MISMATCH" ? "E_PROTOCOL_MISMATCH" : "E_UNAUTHORIZED";
|
|
3314
|
+
failAll(new VdeError(code, "The daemon refused the connection.", { code: String(frame["code"]) }));
|
|
3315
|
+
return;
|
|
3316
|
+
}
|
|
3317
|
+
if (phase === "await-hello") {
|
|
3318
|
+
if (frame["type"] !== "hello" || frame["protocolVersion"] !== 1) {
|
|
3319
|
+
failAll(new VdeError("E_PROTOCOL_MISMATCH", "The protocolVersion of the daemon does not match.", { expected: 1 }));
|
|
3320
|
+
return;
|
|
3321
|
+
}
|
|
3322
|
+
const { daemonId: id, serverNonce, proof } = frame;
|
|
3323
|
+
if (typeof id !== "string" || typeof serverNonce !== "string") {
|
|
3324
|
+
failAll(new VdeError("E_UNAUTHORIZED", "The peer could not be verified."));
|
|
3325
|
+
return;
|
|
3326
|
+
}
|
|
3327
|
+
if (!proofMatches(computeProof(options.key, "server", id, clientNonce, serverNonce), proof)) {
|
|
3328
|
+
failAll(new VdeError("E_UNAUTHORIZED", "The peer could not be verified."));
|
|
3329
|
+
return;
|
|
3330
|
+
}
|
|
3331
|
+
daemonId = id;
|
|
3332
|
+
phase = "await-auth-ok";
|
|
3333
|
+
socket.write(encodeFrame({
|
|
3334
|
+
type: "auth",
|
|
3335
|
+
proof: computeProof(options.key, "client", id, clientNonce, serverNonce)
|
|
3336
|
+
}));
|
|
3337
|
+
return;
|
|
3338
|
+
}
|
|
3339
|
+
if (phase === "await-auth-ok") {
|
|
3340
|
+
if (frame["type"] !== "auth-ok") {
|
|
3341
|
+
failAll(new VdeError("E_UNAUTHORIZED", "Authentication failed."));
|
|
3342
|
+
return;
|
|
3343
|
+
}
|
|
3344
|
+
phase = "ready";
|
|
3345
|
+
clearTimeout(timer);
|
|
3346
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
3347
|
+
resolve(connection);
|
|
3348
|
+
return;
|
|
3349
|
+
}
|
|
3350
|
+
const id = frame["id"];
|
|
3351
|
+
if (typeof id !== "string") return;
|
|
3352
|
+
const waiter = pending.get(id);
|
|
3353
|
+
if (!waiter) return;
|
|
3354
|
+
pending.delete(id);
|
|
3355
|
+
clearTimeout(waiter.timer);
|
|
3356
|
+
const { id: _id, ...body } = frame;
|
|
3357
|
+
const parsed = envelopeSchema.safeParse(body);
|
|
3358
|
+
if (parsed.success) waiter.resolve(parsed.data);
|
|
3359
|
+
else waiter.reject(new VdeError("E_PROTOCOL_MISMATCH", "The response from the daemon could not be parsed."));
|
|
3360
|
+
};
|
|
3361
|
+
socket.on("connect", () => {
|
|
3362
|
+
socket.write(encodeFrame({
|
|
3363
|
+
type: "hello",
|
|
3364
|
+
protocolVersion: 1,
|
|
3365
|
+
clientNonce
|
|
3366
|
+
}));
|
|
3367
|
+
});
|
|
3368
|
+
socket.on("data", (chunk) => {
|
|
3369
|
+
try {
|
|
3370
|
+
for (const frame of decoder.push(chunk)) {
|
|
3371
|
+
if (phase === "closed") return;
|
|
3372
|
+
handleFrame(frame);
|
|
3373
|
+
}
|
|
3374
|
+
} catch (error) {
|
|
3375
|
+
failAll(unavailable("The response from the daemon is invalid.", error));
|
|
3376
|
+
}
|
|
3377
|
+
});
|
|
3378
|
+
socket.on("error", (error) => {
|
|
3379
|
+
clearTimeout(timer);
|
|
3380
|
+
failAll(unavailable("Could not connect to the daemon.", error));
|
|
3381
|
+
});
|
|
3382
|
+
socket.on("close", () => {
|
|
3383
|
+
clearTimeout(timer);
|
|
3384
|
+
if (phase !== "closed") failAll(unavailable("The connection to the daemon was lost."));
|
|
3385
|
+
});
|
|
3386
|
+
});
|
|
3387
|
+
}
|
|
3388
|
+
//#endregion
|
|
3389
|
+
//#region src/cli/daemon-control.ts
|
|
3390
|
+
const START_TIMEOUT_MS = 1e4;
|
|
3391
|
+
const STOP_TIMEOUT_MS = 1e4;
|
|
3392
|
+
const POLL_INTERVAL_MS = 50;
|
|
3393
|
+
const LOCKED_RETRY_MS = 3e3;
|
|
3394
|
+
function createDaemonControl(environment) {
|
|
3395
|
+
const stateRoot = resolveStateRoot(environment);
|
|
3396
|
+
const secure = {
|
|
3397
|
+
uid: environment.uid,
|
|
3398
|
+
platform: environment.platform
|
|
3399
|
+
};
|
|
3400
|
+
const connectExisting = async ({ signal } = {}) => {
|
|
3401
|
+
signal?.throwIfAborted();
|
|
3402
|
+
if (!await requirePrivateDirectoryIfExists(stateRoot, secure)) return null;
|
|
3403
|
+
const pointer = await readPointer(stateRoot);
|
|
3404
|
+
if (!pointer) return null;
|
|
3405
|
+
if (await inspectPrivateDirectory(pointer.runtimeDir, secure) !== "ok") return null;
|
|
3406
|
+
const key = await readIpcKey(pointer.keyPath);
|
|
3407
|
+
if (!key) return null;
|
|
3408
|
+
try {
|
|
3409
|
+
return await connectIpc({
|
|
3410
|
+
socketPath: pointer.socketPath,
|
|
3411
|
+
key,
|
|
3412
|
+
...signal === void 0 ? {} : { signal }
|
|
3413
|
+
});
|
|
3414
|
+
} catch (error) {
|
|
3415
|
+
signal?.throwIfAborted();
|
|
3416
|
+
if (error instanceof VdeError && error.code === "E_DAEMON_UNAVAILABLE") return null;
|
|
3417
|
+
throw error;
|
|
3418
|
+
}
|
|
3419
|
+
};
|
|
3420
|
+
const spawnDaemon = (signal) => new Promise((resolve, reject) => {
|
|
3421
|
+
const child = spawn(process.execPath, [daemonEntryPath()], {
|
|
3422
|
+
detached: true,
|
|
3423
|
+
stdio: [
|
|
3424
|
+
"ignore",
|
|
3425
|
+
"ignore",
|
|
3426
|
+
"ignore",
|
|
3427
|
+
"ipc"
|
|
3428
|
+
],
|
|
3429
|
+
env: environment.env,
|
|
3430
|
+
windowsHide: true
|
|
3431
|
+
});
|
|
3432
|
+
let settled = false;
|
|
3433
|
+
const settle = (error) => {
|
|
3434
|
+
if (settled) return;
|
|
3435
|
+
settled = true;
|
|
3436
|
+
clearTimeout(timer);
|
|
3437
|
+
signal?.removeEventListener("abort", onAbort);
|
|
3438
|
+
if (child.connected) child.disconnect();
|
|
3439
|
+
child.unref();
|
|
3440
|
+
if (error) reject(error);
|
|
3441
|
+
else resolve();
|
|
3442
|
+
};
|
|
3443
|
+
const onAbort = () => settle(signal?.reason instanceof Error ? signal.reason : /* @__PURE__ */ new Error("aborted"));
|
|
3444
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
3445
|
+
const logPath = join(stateRoot, "logs", "daemon.jsonl");
|
|
3446
|
+
const timer = setTimeout(() => {
|
|
3447
|
+
settle(new VdeError("E_DAEMON_START_FAILED", "The daemon did not start in time.", { log: logPath }));
|
|
3448
|
+
}, START_TIMEOUT_MS);
|
|
3449
|
+
child.on("message", (message) => {
|
|
3450
|
+
const { type, code, message: text, details } = message;
|
|
3451
|
+
if (type === "ready") {
|
|
3452
|
+
settle();
|
|
3453
|
+
return;
|
|
3454
|
+
}
|
|
3455
|
+
settle(new VdeError(typeof code === "string" && isErrorCode(code) ? code : "E_DAEMON_START_FAILED", typeof text === "string" ? text : "The daemon could not be started.", {
|
|
3456
|
+
...details,
|
|
3457
|
+
log: logPath
|
|
3458
|
+
}));
|
|
3459
|
+
});
|
|
3460
|
+
child.on("error", (error) => {
|
|
3461
|
+
settle(new VdeError("E_DAEMON_START_FAILED", "The daemon could not be started.", { log: logPath }, { cause: error }));
|
|
3462
|
+
});
|
|
3463
|
+
child.on("exit", (exitCode) => {
|
|
3464
|
+
settle(new VdeError("E_DAEMON_START_FAILED", "The daemon exited while starting.", {
|
|
3465
|
+
exitCode,
|
|
3466
|
+
log: logPath
|
|
3467
|
+
}));
|
|
3468
|
+
});
|
|
3469
|
+
if (signal?.aborted) onAbort();
|
|
3470
|
+
});
|
|
3471
|
+
const ensureDetailed = async (options = {}) => {
|
|
3472
|
+
const { signal } = options;
|
|
3473
|
+
const existing = await connectExisting(options);
|
|
3474
|
+
if (existing) return {
|
|
3475
|
+
connection: existing,
|
|
3476
|
+
started: false
|
|
3477
|
+
};
|
|
3478
|
+
await ensurePrivateDirectory(stateRoot, secure);
|
|
3479
|
+
const ownerId = `start_${randomUUID()}`;
|
|
3480
|
+
const deadline = Date.now() + START_TIMEOUT_MS;
|
|
3481
|
+
for (;;) {
|
|
3482
|
+
signal?.throwIfAborted();
|
|
3483
|
+
if ((await acquireLock(stateRoot, "start.lock", {
|
|
3484
|
+
pid: process.pid,
|
|
3485
|
+
ownerId
|
|
3486
|
+
}, systemProcessProbe)).acquired) break;
|
|
3487
|
+
const connection = await connectExisting(options);
|
|
3488
|
+
if (connection) return {
|
|
3489
|
+
connection,
|
|
3490
|
+
started: false
|
|
3491
|
+
};
|
|
3492
|
+
if (Date.now() > deadline) throw new VdeError("E_DAEMON_UNAVAILABLE", "Waited for the daemon to start, but could not connect.", { reason: "start-lock-timeout" });
|
|
3493
|
+
await setTimeout$1(POLL_INTERVAL_MS, void 0, { signal });
|
|
3494
|
+
}
|
|
3495
|
+
try {
|
|
3496
|
+
const already = await connectExisting(options);
|
|
3497
|
+
if (already) return {
|
|
3498
|
+
connection: already,
|
|
3499
|
+
started: false
|
|
3500
|
+
};
|
|
3501
|
+
try {
|
|
3502
|
+
await spawnDaemon(signal);
|
|
3503
|
+
} catch (error) {
|
|
3504
|
+
if (!(error instanceof VdeError) || error.code !== "E_DAEMON_LOCKED") throw error;
|
|
3505
|
+
const waitUntil = Date.now() + LOCKED_RETRY_MS;
|
|
3506
|
+
for (;;) {
|
|
3507
|
+
const other = await connectExisting(options);
|
|
3508
|
+
if (other) return {
|
|
3509
|
+
connection: other,
|
|
3510
|
+
started: false
|
|
3511
|
+
};
|
|
3512
|
+
if (Date.now() > waitUntil) throw error;
|
|
3513
|
+
await setTimeout$1(POLL_INTERVAL_MS, void 0, { signal });
|
|
3514
|
+
}
|
|
3515
|
+
}
|
|
3516
|
+
const connection = await connectExisting(options);
|
|
3517
|
+
if (!connection) throw new VdeError("E_DAEMON_START_FAILED", "Could not connect to the daemon that was started.", { log: join(stateRoot, "logs", "daemon.jsonl") });
|
|
3518
|
+
return {
|
|
3519
|
+
connection,
|
|
3520
|
+
started: true
|
|
3521
|
+
};
|
|
3522
|
+
} finally {
|
|
3523
|
+
await releaseLock(stateRoot, START_LOCK_NAME, ownerId);
|
|
3524
|
+
}
|
|
3525
|
+
};
|
|
3526
|
+
const ensure = async (options = {}) => (await ensureDetailed(options)).connection;
|
|
3527
|
+
const stop = async () => {
|
|
3528
|
+
const connection = await connectExisting();
|
|
3529
|
+
if (!connection) return { wasRunning: false };
|
|
3530
|
+
const daemonId = connection.daemonId;
|
|
3531
|
+
try {
|
|
3532
|
+
await connection.request("daemon.stop", {});
|
|
3533
|
+
} catch {} finally {
|
|
3534
|
+
connection.close();
|
|
3535
|
+
}
|
|
3536
|
+
const deadline = Date.now() + STOP_TIMEOUT_MS;
|
|
3537
|
+
for (;;) {
|
|
3538
|
+
const lock = await readCurrentLock(stateRoot, DAEMON_LOCK_NAME);
|
|
3539
|
+
if (!(lock !== null && lock !== "invalid" && lock.ownerId === daemonId && !lock.released)) return { wasRunning: true };
|
|
3540
|
+
if (Date.now() > deadline) throw new VdeError("E_DAEMON_UNAVAILABLE", "The daemon did not stop in time.", { daemonId });
|
|
3541
|
+
await setTimeout$1(POLL_INTERVAL_MS);
|
|
3542
|
+
}
|
|
3543
|
+
};
|
|
3544
|
+
const stoppedStatus = () => ({
|
|
3545
|
+
state: "stopped",
|
|
3546
|
+
daemonId: null,
|
|
3547
|
+
pid: null,
|
|
3548
|
+
version: null,
|
|
3549
|
+
protocolVersion: null,
|
|
3550
|
+
startedAt: null,
|
|
3551
|
+
stateRoot,
|
|
3552
|
+
openDocuments: null,
|
|
3553
|
+
catalogVersion: null,
|
|
3554
|
+
uiUrl: null
|
|
3555
|
+
});
|
|
3556
|
+
return {
|
|
3557
|
+
stateRoot,
|
|
3558
|
+
connectExisting,
|
|
3559
|
+
ensure,
|
|
3560
|
+
ensureDetailed,
|
|
3561
|
+
stop,
|
|
3562
|
+
stoppedStatus
|
|
3563
|
+
};
|
|
3564
|
+
}
|
|
3565
|
+
//#endregion
|
|
3566
|
+
//#region src/cli/output.ts
|
|
3567
|
+
function codeUnitEscape(character) {
|
|
3568
|
+
return `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`;
|
|
3569
|
+
}
|
|
3570
|
+
function safeJson(value) {
|
|
3571
|
+
return JSON.stringify(value).replace(/[\u007f-\u009f\u2028\u2029]/g, codeUnitEscape);
|
|
3572
|
+
}
|
|
3573
|
+
function escapeForTerminal(text) {
|
|
3574
|
+
return text.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, codeUnitEscape);
|
|
3575
|
+
}
|
|
3576
|
+
function escapeContentForTerminal(text) {
|
|
3577
|
+
return text.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, codeUnitEscape);
|
|
3578
|
+
}
|
|
3579
|
+
//#endregion
|
|
3580
|
+
//#region src/cli/wait-for-answer.ts
|
|
3581
|
+
const RECONNECTABLE = /* @__PURE__ */ new Set([
|
|
3582
|
+
"E_DAEMON_STOPPING",
|
|
3583
|
+
"E_DAEMON_UNAVAILABLE",
|
|
3584
|
+
"E_DAEMON_START_FAILED",
|
|
3585
|
+
"E_DAEMON_LOCKED"
|
|
3586
|
+
]);
|
|
3587
|
+
const RECONNECT_INTERVAL_MS = 250;
|
|
3588
|
+
const IPC_GRACE_MS = 1e3;
|
|
3589
|
+
async function waitForAnswer(options) {
|
|
3590
|
+
const { requestId, connect } = options;
|
|
3591
|
+
const deadline = Date.now() + options.timeoutMs;
|
|
3592
|
+
const timeoutError = () => new VdeError("E_TIMEOUT", "The wait for the answer timed out. The question is still pending.", {
|
|
3593
|
+
requestId,
|
|
3594
|
+
status: "pending"
|
|
3595
|
+
});
|
|
3596
|
+
const interruptedError = () => new VdeError("E_INTERRUPTED", "The wait was interrupted. The question is still pending.", { requestId });
|
|
3597
|
+
let interrupted = false;
|
|
3598
|
+
const abandon = new AbortController();
|
|
3599
|
+
const stops = /* @__PURE__ */ new Set();
|
|
3600
|
+
const unsubscribe = options.subscribeInterrupt(() => {
|
|
3601
|
+
interrupted = true;
|
|
3602
|
+
for (const stop of stops) stop();
|
|
3603
|
+
});
|
|
3604
|
+
const bounded = (work, discard) => new Promise((resolve, reject) => {
|
|
3605
|
+
let settled = false;
|
|
3606
|
+
const finish = (action) => {
|
|
3607
|
+
if (settled) return;
|
|
3608
|
+
settled = true;
|
|
3609
|
+
clearTimeout(timer);
|
|
3610
|
+
stops.delete(stop);
|
|
3611
|
+
action();
|
|
3612
|
+
};
|
|
3613
|
+
const stop = () => finish(() => reject(interruptedError()));
|
|
3614
|
+
const timer = setTimeout(() => finish(() => reject(timeoutError())), Math.max(0, deadline - Date.now()));
|
|
3615
|
+
stops.add(stop);
|
|
3616
|
+
work.then((value) => {
|
|
3617
|
+
if (settled) discard(value);
|
|
3618
|
+
else finish(() => resolve(value));
|
|
3619
|
+
}, (error) => finish(() => reject(error)));
|
|
3620
|
+
if (interrupted) stop();
|
|
3621
|
+
});
|
|
3622
|
+
try {
|
|
3623
|
+
for (;;) {
|
|
3624
|
+
if (deadline - Date.now() <= 0) throw timeoutError();
|
|
3625
|
+
let connection = null;
|
|
3626
|
+
try {
|
|
3627
|
+
connection = await bounded(connect(abandon.signal), (late) => late.close());
|
|
3628
|
+
const remaining = deadline - Date.now();
|
|
3629
|
+
if (remaining <= 0) throw timeoutError();
|
|
3630
|
+
const envelope = await bounded(connection.request("feedback.wait", {
|
|
3631
|
+
requestId,
|
|
3632
|
+
timeoutMs: remaining
|
|
3633
|
+
}, { timeoutMs: remaining + IPC_GRACE_MS }), () => void 0);
|
|
3634
|
+
if (envelope.ok) return envelope;
|
|
3635
|
+
const { code, message, details, retryable } = envelope.error;
|
|
3636
|
+
throw new VdeError(isErrorCode(code) ? code : "E_INTERNAL", message, details, { retryable });
|
|
3637
|
+
} catch (error) {
|
|
3638
|
+
if (!isVdeError(error) || !RECONNECTABLE.has(error.code)) throw error;
|
|
3639
|
+
} finally {
|
|
3640
|
+
connection?.close();
|
|
3641
|
+
}
|
|
3642
|
+
await bounded(setTimeout$1(RECONNECT_INTERVAL_MS, void 0, { signal: abandon.signal }), () => void 0);
|
|
3643
|
+
}
|
|
3644
|
+
} finally {
|
|
3645
|
+
unsubscribe();
|
|
3646
|
+
abandon.abort(new VdeError("E_INTERRUPTED", "The wait has ended."));
|
|
3647
|
+
}
|
|
3648
|
+
}
|
|
3649
|
+
//#endregion
|
|
3650
|
+
//#region src/cli/run.ts
|
|
3651
|
+
const CLI_VERSION = version;
|
|
3652
|
+
const PROGRAM_NAME = "vde-open";
|
|
3653
|
+
function toErrorBody(error) {
|
|
3654
|
+
if (isVdeError(error)) return {
|
|
3655
|
+
code: error.code,
|
|
3656
|
+
message: error.message,
|
|
3657
|
+
retryable: error.retryable,
|
|
3658
|
+
details: error.details
|
|
3659
|
+
};
|
|
3660
|
+
return {
|
|
3661
|
+
code: "E_INTERNAL",
|
|
3662
|
+
message: "An internal error occurred.",
|
|
3663
|
+
retryable: false,
|
|
3664
|
+
details: {}
|
|
3665
|
+
};
|
|
3666
|
+
}
|
|
3667
|
+
function unwrap(envelope) {
|
|
3668
|
+
if (!envelope.ok) {
|
|
3669
|
+
const { code, message, details, retryable } = envelope.error;
|
|
3670
|
+
throw new VdeError(isErrorCode(code) ? code : "E_INTERNAL", message, details, { retryable });
|
|
3671
|
+
}
|
|
3672
|
+
const outcome = {
|
|
3673
|
+
data: envelope.data,
|
|
3674
|
+
warnings: envelope.warnings
|
|
3675
|
+
};
|
|
3676
|
+
if (envelope.meta.catalogVersion !== void 0) outcome.catalogVersion = envelope.meta.catalogVersion;
|
|
3677
|
+
return outcome;
|
|
3678
|
+
}
|
|
3679
|
+
function parseInteger(label, min, max) {
|
|
3680
|
+
return (value) => {
|
|
3681
|
+
if (!/^\d+$/.test(value)) throw new InvalidArgumentError(`${label} must be an integer.`);
|
|
3682
|
+
const parsed = Number(value);
|
|
3683
|
+
if (parsed < min || parsed > max) throw new InvalidArgumentError(`${label} must be between ${String(min)} and ${String(max)}.`);
|
|
3684
|
+
return parsed;
|
|
3685
|
+
};
|
|
3686
|
+
}
|
|
3687
|
+
function parseLines(value) {
|
|
3688
|
+
const match = /^(\d+):(\d+)$/.exec(value);
|
|
3689
|
+
if (!match) throw new InvalidArgumentError("--lines must be in the form A:B.");
|
|
3690
|
+
const start = Number(match[1]);
|
|
3691
|
+
const end = Number(match[2]);
|
|
3692
|
+
if (start < 1 || end < start) throw new InvalidArgumentError("--lines must be 1 or greater, with A <= B.");
|
|
3693
|
+
return {
|
|
3694
|
+
start,
|
|
3695
|
+
end
|
|
3696
|
+
};
|
|
3697
|
+
}
|
|
3698
|
+
function parseFormat(value) {
|
|
3699
|
+
if (value === "auto" || value === "markdown" || value === "html") return value;
|
|
3700
|
+
throw new InvalidArgumentError("--format must be one of auto, markdown, or html.");
|
|
3701
|
+
}
|
|
3702
|
+
function parseHtmlMode(value) {
|
|
3703
|
+
if (value === "static" || value === "interactive") return value;
|
|
3704
|
+
throw new InvalidArgumentError("--html-mode must be static or interactive.");
|
|
3705
|
+
}
|
|
3706
|
+
function describeDocument(document) {
|
|
3707
|
+
const path = document.displayPath ?? `(${document.sourceKind})`;
|
|
3708
|
+
return `${document.documentId} ${escapeForTerminal(document.title)} ${escapeForTerminal(path)}`;
|
|
3709
|
+
}
|
|
3710
|
+
function decodeStdin(bytes) {
|
|
3711
|
+
if (bytes.byteLength > LIMITS.documentBytes) throw new VdeError("E_LIMIT_EXCEEDED", "The stdin content exceeds the size limit for one document.", {
|
|
3712
|
+
limit: "documentBytes",
|
|
3713
|
+
max: LIMITS.documentBytes,
|
|
3714
|
+
actual: bytes.byteLength
|
|
3715
|
+
});
|
|
3716
|
+
if (bytes.includes(0)) throw new VdeError("E_INVALID_SOURCE", "The stdin content cannot be opened (contains-nul).", {
|
|
3717
|
+
path: "stdin",
|
|
3718
|
+
reason: "contains-nul"
|
|
3719
|
+
});
|
|
3720
|
+
try {
|
|
3721
|
+
return new TextDecoder("utf-8", {
|
|
3722
|
+
fatal: true,
|
|
3723
|
+
ignoreBOM: true
|
|
3724
|
+
}).decode(bytes);
|
|
3725
|
+
} catch {
|
|
3726
|
+
throw new VdeError("E_INVALID_SOURCE", "The stdin content cannot be opened (invalid-utf8).", {
|
|
3727
|
+
path: "stdin",
|
|
3728
|
+
reason: "invalid-utf8"
|
|
3729
|
+
});
|
|
3730
|
+
}
|
|
3731
|
+
}
|
|
3732
|
+
function parseFeedbackStatus(value) {
|
|
3733
|
+
if (value === "pending" || value === "submitted" || value === "cancelled") return value;
|
|
3734
|
+
throw new InvalidArgumentError("--status must be one of pending, submitted, or cancelled.");
|
|
3735
|
+
}
|
|
3736
|
+
function describeRequest(request) {
|
|
3737
|
+
return `${request.requestId} ${request.status} ${escapeForTerminal(request.title)} ${request.documentId}`;
|
|
3738
|
+
}
|
|
3739
|
+
function describeAnswers(request) {
|
|
3740
|
+
const lines = [describeRequest(request)];
|
|
3741
|
+
if (request.submission) {
|
|
3742
|
+
lines.push(`answer ${request.submission.submissionId} (${request.submission.submittedAt})`);
|
|
3743
|
+
for (const [name, value] of Object.entries(request.submission.answers)) lines.push(` ${escapeForTerminal(name)}: ${escapeContentForTerminal(JSON.stringify(value))}`);
|
|
3744
|
+
if (request.submission.confirmedAgainstOlderRevision) lines.push(" (answered against the question's revision after confirming that a newer revision exists)");
|
|
3745
|
+
}
|
|
3746
|
+
if (request.cancellation) lines.push(`cancelled: ${request.cancellation.reason}`);
|
|
3747
|
+
if (request.acknowledgedAt) lines.push(`acknowledged: ${request.acknowledgedAt}`);
|
|
3748
|
+
return lines.join("\n");
|
|
3749
|
+
}
|
|
3750
|
+
async function readQuestionnaire(cwd, path) {
|
|
3751
|
+
const absolute = resolve(cwd, path);
|
|
3752
|
+
let size;
|
|
3753
|
+
try {
|
|
3754
|
+
const info = await stat$1(absolute);
|
|
3755
|
+
if (!info.isFile()) throw new Error("not-file");
|
|
3756
|
+
size = info.size;
|
|
3757
|
+
} catch {
|
|
3758
|
+
throw new VdeError("E_PATH_NOT_FOUND", "The questionnaire file cannot be read.", { path });
|
|
3759
|
+
}
|
|
3760
|
+
if (size > LIMITS.questionnaireBytes) throw new VdeError("E_LIMIT_EXCEEDED", "The questionnaire is too large.", {
|
|
3761
|
+
limit: "questionnaireBytes",
|
|
3762
|
+
max: LIMITS.questionnaireBytes,
|
|
3763
|
+
actual: size
|
|
3764
|
+
});
|
|
3765
|
+
try {
|
|
3766
|
+
return new TextDecoder("utf-8", {
|
|
3767
|
+
fatal: true,
|
|
3768
|
+
ignoreBOM: false
|
|
3769
|
+
}).decode(await readFile(absolute));
|
|
3770
|
+
} catch {
|
|
3771
|
+
throw new VdeError("E_QUESTIONNAIRE_INVALID", "The questionnaire cannot be read as UTF-8.", { path });
|
|
3772
|
+
}
|
|
3773
|
+
}
|
|
3774
|
+
function parseSearchMode(value) {
|
|
3775
|
+
if (value === "text" || value === "exact" || value === "path") return value;
|
|
3776
|
+
throw new InvalidArgumentError("--mode must be one of text, exact, or path.");
|
|
3777
|
+
}
|
|
3778
|
+
async function runCli(rawArgv, context) {
|
|
3779
|
+
const wantsJson = rawArgv.includes("--json");
|
|
3780
|
+
const control = createDaemonControl(context.environment);
|
|
3781
|
+
const browser = createBrowserLauncher(context.environment.env, context.environment.platform);
|
|
3782
|
+
let exitCode = ExitCode.success;
|
|
3783
|
+
const fail = (error, json) => {
|
|
3784
|
+
const body = toErrorBody(error);
|
|
3785
|
+
exitCode = exitCodeForError(body.code);
|
|
3786
|
+
if (json) context.stdout(`${safeJson(errorEnvelope(body))}\n`);
|
|
3787
|
+
else context.stderr(`${escapeForTerminal(`${body.code}: ${body.message}`)}\n`);
|
|
3788
|
+
if (!isVdeError(error) && error instanceof Error) context.stderr(`${escapeForTerminal(error.message)}\n`);
|
|
3789
|
+
};
|
|
3790
|
+
const execute = async (command, json, work, render) => {
|
|
3791
|
+
try {
|
|
3792
|
+
const outcome = await work();
|
|
3793
|
+
const warnings = outcome.warnings ?? [];
|
|
3794
|
+
if (json) {
|
|
3795
|
+
const meta = outcome.catalogVersion === void 0 ? { command } : {
|
|
3796
|
+
command,
|
|
3797
|
+
catalogVersion: outcome.catalogVersion
|
|
3798
|
+
};
|
|
3799
|
+
context.stdout(`${safeJson(successEnvelope(outcome.data, meta, warnings))}\n`);
|
|
3800
|
+
} else {
|
|
3801
|
+
for (const warning of warnings) context.stderr(`${escapeForTerminal(`${warning.code}: ${warning.message}`)}\n`);
|
|
3802
|
+
const text = render(outcome.data);
|
|
3803
|
+
if (text !== "") context.stdout(text.endsWith("\n") ? text : `${text}\n`);
|
|
3804
|
+
}
|
|
3805
|
+
} catch (error) {
|
|
3806
|
+
fail(error, json);
|
|
3807
|
+
}
|
|
3808
|
+
};
|
|
3809
|
+
const viaDaemon = async (method, params) => {
|
|
3810
|
+
const connection = await control.ensure();
|
|
3811
|
+
try {
|
|
3812
|
+
return unwrap(await connection.request(method, params));
|
|
3813
|
+
} finally {
|
|
3814
|
+
connection.close();
|
|
3815
|
+
}
|
|
3816
|
+
};
|
|
3817
|
+
const openBrowser = async (connection) => {
|
|
3818
|
+
const { data } = unwrap(await connection.request("ui.bootstrap", {}));
|
|
3819
|
+
if (await browser.open(data.bootstrapUrl)) return [];
|
|
3820
|
+
return [{
|
|
3821
|
+
code: "W_BROWSER_OPEN_FAILED",
|
|
3822
|
+
message: "The browser could not be opened. Open the URL shown by `vde-open ui --print-url` in your browser.",
|
|
3823
|
+
details: { uiUrl: data.uiUrl }
|
|
3824
|
+
}];
|
|
3825
|
+
};
|
|
3826
|
+
const showUi = async (printUrl) => {
|
|
3827
|
+
const connection = await control.ensure();
|
|
3828
|
+
try {
|
|
3829
|
+
if (printUrl) {
|
|
3830
|
+
const { data } = unwrap(await connection.request("ui.bootstrap", {}));
|
|
3831
|
+
context.stderr("This URL contains a one-time secret valid for 60 seconds. Do not share it.\n");
|
|
3832
|
+
context.stdout(`${data.bootstrapUrl}\n`);
|
|
3833
|
+
return { data: {
|
|
3834
|
+
uiUrl: data.uiUrl,
|
|
3835
|
+
opened: false
|
|
3836
|
+
} };
|
|
3837
|
+
}
|
|
3838
|
+
const status = unwrap(await connection.request("daemon.status", {})).data;
|
|
3839
|
+
const warnings = await openBrowser(connection);
|
|
3840
|
+
return {
|
|
3841
|
+
data: {
|
|
3842
|
+
uiUrl: status.uiUrl ?? "",
|
|
3843
|
+
opened: warnings.length === 0
|
|
3844
|
+
},
|
|
3845
|
+
warnings
|
|
3846
|
+
};
|
|
3847
|
+
} finally {
|
|
3848
|
+
connection.close();
|
|
3849
|
+
}
|
|
3850
|
+
};
|
|
3851
|
+
const program = new Command();
|
|
3852
|
+
program.name(PROGRAM_NAME).description("Local CLI that shows opened Markdown and HTML in the browser and lets agents list, search, and read parts of them").version(CLI_VERSION, "-V, --version", "Show the version").helpOption("-h, --help", "Show help").addHelpText("after", "\n`vo` is the same command as `vde-open`. Passing a file directly is treated as `open` (for example: vo a.md).\nRunning with no arguments opens the management UI in the browser.").exitOverride().configureOutput({
|
|
3853
|
+
writeOut: context.stdout,
|
|
3854
|
+
writeErr: context.stderr
|
|
3855
|
+
}).action(async () => {
|
|
3856
|
+
await execute("ui", false, () => showUi(false), () => "");
|
|
3857
|
+
});
|
|
3858
|
+
const openCommand = program.command("open");
|
|
3859
|
+
const seenOpenFlags = /* @__PURE__ */ new Set();
|
|
3860
|
+
openCommand.on("option:open", () => seenOpenFlags.add("open"));
|
|
3861
|
+
openCommand.on("option:no-open", () => seenOpenFlags.add("no-open"));
|
|
3862
|
+
openCommand.description("Open documents. A directory or glob is expanded to the matching documents").argument("[paths...]", "File, directory, or glob. `-` means stdin").option("--format <format>", "auto, markdown, or html. Required for stdin", parseFormat, "auto").option("--title <text>", "Title to display. Only for a single document").option("--key <key>", "Key that updates the stdin document as the same entry. Only for a single document").option("-R, --recursive", "List directories recursively", false).option("-w, --watch", "Also open documents that newly appear in the directory or glob", false).option("--html-mode <mode>", "How to show HTML. static (default; scripts do not run) or interactive (scripts are allowed to run)", parseHtmlMode).option("--assets-root <dir>", "Range of local files (images, CSS, etc.) that may be read. Defaults to the directory of the document").option("--asset <path>", "Register a local file that document parsing does not find (path relative to assets-root). Can be repeated", (value, previous) => [...previous, value], []).option("--open", "Open the management UI in the browser").option("--no-open", "Do not open the browser").option("--focus", "Make the first specified document the displayed document", false).option("--json", "Output the result as JSON", false).action(async (paths, options) => {
|
|
3863
|
+
await execute("open", options.json, async () => {
|
|
3864
|
+
if (seenOpenFlags.size === 2) throw new VdeError("E_INVALID_ARGUMENT", "--open and --no-open cannot be used together.");
|
|
3865
|
+
const explicitStdin = paths.includes("-");
|
|
3866
|
+
const filePaths = paths.filter((path) => path !== "-");
|
|
3867
|
+
const fromStdin = explicitStdin || filePaths.length === 0 && context.stdin.isPiped;
|
|
3868
|
+
if (fromStdin && filePaths.length > 0) throw new VdeError("E_INVALID_ARGUMENT", "stdin and paths cannot be used together.");
|
|
3869
|
+
if (!fromStdin && context.stdin.isPiped) throw new VdeError("E_INVALID_ARGUMENT", "stdin and paths cannot be used together. Do not pipe content to stdin when opening paths.");
|
|
3870
|
+
const base = {
|
|
3871
|
+
cwd: context.cwd,
|
|
3872
|
+
format: options.format,
|
|
3873
|
+
recursive: options.recursive,
|
|
3874
|
+
watch: options.watch,
|
|
3875
|
+
...options.title === void 0 ? {} : { title: options.title },
|
|
3876
|
+
...options.key === void 0 ? {} : { key: options.key },
|
|
3877
|
+
...options.htmlMode === void 0 ? {} : { htmlMode: options.htmlMode },
|
|
3878
|
+
...options.assetsRoot === void 0 ? {} : { assetsRoot: options.assetsRoot },
|
|
3879
|
+
assets: options.asset
|
|
3880
|
+
};
|
|
3881
|
+
let params;
|
|
3882
|
+
if (fromStdin) {
|
|
3883
|
+
if (options.format === "auto") throw new VdeError("E_INVALID_ARGUMENT", "--format is required when opening from stdin.");
|
|
3884
|
+
params = {
|
|
3885
|
+
...base,
|
|
3886
|
+
paths: [],
|
|
3887
|
+
stdin: { content: decodeStdin(await context.stdin.read()) }
|
|
3888
|
+
};
|
|
3889
|
+
} else params = {
|
|
3890
|
+
...base,
|
|
3891
|
+
paths: filePaths
|
|
3892
|
+
};
|
|
3893
|
+
const { connection, started } = await control.ensureDetailed();
|
|
3894
|
+
try {
|
|
3895
|
+
const outcome = unwrap(await connection.request("documents.open", params));
|
|
3896
|
+
const warnings = [...outcome.warnings ?? []];
|
|
3897
|
+
const first = outcome.data.documents[0];
|
|
3898
|
+
if (options.focus && first) await connection.request("documents.focus", { documentId: first.documentId });
|
|
3899
|
+
if (options.open ?? (!options.json && context.stdoutIsTty && started)) warnings.push(...await openBrowser(connection));
|
|
3900
|
+
return {
|
|
3901
|
+
...outcome,
|
|
3902
|
+
warnings
|
|
3903
|
+
};
|
|
3904
|
+
} finally {
|
|
3905
|
+
connection.close();
|
|
3906
|
+
}
|
|
3907
|
+
}, (data) => [
|
|
3908
|
+
...data.documents.map(describeDocument),
|
|
3909
|
+
...data.watchRules.map((rule) => `watch: ${rule.watchId} ${escapeForTerminal(rule.pattern ?? rule.root)}`),
|
|
3910
|
+
`documents: ${String(data.documents.length)} (new ${String(data.created)}, updated ${String(data.updated)}, unchanged ${String(data.unchanged)})`
|
|
3911
|
+
].join("\n"));
|
|
3912
|
+
});
|
|
3913
|
+
program.command("list").description("List open documents").option("--limit <n>", `Number of results (default ${String(LIMITS.listLimitDefault)}, max ${String(LIMITS.listLimitMax)})`, parseInteger("--limit", 1, LIMITS.listLimitMax)).option("--cursor <cursor>", "nextCursor from the previous result").option("--json", "Output the result as JSON", false).action(async (options) => {
|
|
3914
|
+
await execute("list", options.json, () => viaDaemon("documents.list", {
|
|
3915
|
+
...options.limit === void 0 ? {} : { limit: options.limit },
|
|
3916
|
+
...options.cursor === void 0 ? {} : { cursor: options.cursor }
|
|
3917
|
+
}), (data) => [...data.documents.map(describeDocument), `showing ${String(data.documents.length)} of ${String(data.totalDocuments)} open documents`].join("\n"));
|
|
3918
|
+
});
|
|
3919
|
+
program.command("search").description("Search open documents. Only open documents are searched").argument("<query>", "Words to search for. Treated literally, not as a regular expression").option("--mode <mode>", "text (word match; default), exact (contiguous string only), or path (file name and path only)", parseSearchMode).option("--limit <n>", `Number of results (default ${String(LIMITS.searchLimitDefault)}, max ${String(LIMITS.searchLimitMax)})`, parseInteger("--limit", 1, LIMITS.searchLimitMax)).option("--document <documentId>", "Document ID to restrict the search to. Can be repeated", (value, previous) => [...previous, value], []).option("--max-bytes <n>", `Maximum bytes of results (default ${String(LIMITS.readMaxBytesDefault)})`, parseInteger("--max-bytes", 1, Number.MAX_SAFE_INTEGER)).option("--cursor <cursor>", "nextCursor from the previous result").option("--json", "Output the result as JSON", false).action(async (query, options) => {
|
|
3920
|
+
await execute("search", options.json, () => {
|
|
3921
|
+
if (options.maxBytes !== void 0 && (options.maxBytes < LIMITS.readMaxBytesMin || options.maxBytes > LIMITS.readMaxBytesMax)) throw new VdeError("E_INVALID_ARGUMENT", `--max-bytes must be between ${String(LIMITS.readMaxBytesMin)} and ${String(LIMITS.readMaxBytesMax)}.`, {
|
|
3922
|
+
min: LIMITS.readMaxBytesMin,
|
|
3923
|
+
max: LIMITS.readMaxBytesMax
|
|
3924
|
+
});
|
|
3925
|
+
return viaDaemon("documents.search", {
|
|
3926
|
+
query,
|
|
3927
|
+
documents: options.document,
|
|
3928
|
+
...options.mode === void 0 ? {} : { mode: options.mode },
|
|
3929
|
+
...options.limit === void 0 ? {} : { limit: options.limit },
|
|
3930
|
+
...options.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes },
|
|
3931
|
+
...options.cursor === void 0 ? {} : { cursor: options.cursor }
|
|
3932
|
+
});
|
|
3933
|
+
}, (data) => [
|
|
3934
|
+
...data.hits.map((hit) => `${hit.documentId} ${hit.sectionId} ${escapeForTerminal(hit.title)}${hit.headingPath.length > 0 ? ` > ${escapeForTerminal(hit.headingPath.join(" > "))}` : ""}\n ${escapeForTerminal(hit.excerpt)}`),
|
|
3935
|
+
`hits: ${String(data.hits.length)} / searched documents: ${String(data.searchedDocuments)} (open documents: ${String(data.registeredDocuments)})${data.truncated ? " more results available" : ""}`,
|
|
3936
|
+
...data.incomplete ? [`Some documents could not be searched (indexing ${String(data.indexingDocuments.length)}, failed ${String(data.failedDocuments.length)})`] : []
|
|
3937
|
+
].join("\n"));
|
|
3938
|
+
});
|
|
3939
|
+
program.command("read").description("Read the source of an open document, its outline, or the body of one section").argument("<documentId>", "Document ID").option("--outline", "Read the outline", false).option("--section <sectionId>", "Read the extracted body of one section (for example: sec_0002)").option("--lines <A:B>", "Line range of the source (1-based, inclusive)", parseLines).option("--revision <revision>", "Revision to read. Fails if it is no longer kept").option("--max-bytes <n>", `Maximum bytes of the body (default ${String(LIMITS.readMaxBytesDefault)})`, parseInteger("--max-bytes", 1, Number.MAX_SAFE_INTEGER)).option("--cursor <cursor>", "nextCursor from the previous result").option("--json", "Output the result as JSON", false).action(async (documentId, options) => {
|
|
3940
|
+
await execute("read", options.json, () => {
|
|
3941
|
+
if (options.maxBytes !== void 0 && (options.maxBytes < LIMITS.readMaxBytesMin || options.maxBytes > LIMITS.readMaxBytesMax)) throw new VdeError("E_INVALID_ARGUMENT", `--max-bytes must be between ${String(LIMITS.readMaxBytesMin)} and ${String(LIMITS.readMaxBytesMax)}.`, {
|
|
3942
|
+
min: LIMITS.readMaxBytesMin,
|
|
3943
|
+
max: LIMITS.readMaxBytesMax
|
|
3944
|
+
});
|
|
3945
|
+
const selectors = [
|
|
3946
|
+
options.outline,
|
|
3947
|
+
options.section !== void 0,
|
|
3948
|
+
options.lines !== void 0
|
|
3949
|
+
].filter(Boolean).length;
|
|
3950
|
+
if (selectors > 1) throw new VdeError("E_INVALID_ARGUMENT", "Only one of --outline, --section, or --lines can be specified.");
|
|
3951
|
+
if (options.cursor !== void 0 && (selectors > 0 || options.revision !== void 0)) throw new VdeError("E_INVALID_ARGUMENT", "--cursor cannot be combined with --revision, --outline, --section, or --lines.");
|
|
3952
|
+
return viaDaemon("documents.read", {
|
|
3953
|
+
documentId,
|
|
3954
|
+
outline: options.outline,
|
|
3955
|
+
...options.section === void 0 ? {} : { section: options.section },
|
|
3956
|
+
...options.lines === void 0 ? {} : { lines: options.lines },
|
|
3957
|
+
...options.revision === void 0 ? {} : { revision: options.revision },
|
|
3958
|
+
...options.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes },
|
|
3959
|
+
...options.cursor === void 0 ? {} : { cursor: options.cursor }
|
|
3960
|
+
});
|
|
3961
|
+
}, (data) => {
|
|
3962
|
+
if (data.outline) return data.outline.map((item) => `${" ".repeat(item.level - 1)}${escapeForTerminal(item.title)} (${item.sectionId})`).join("\n");
|
|
3963
|
+
const content = data.content ?? "";
|
|
3964
|
+
return context.stdoutIsTty ? escapeContentForTerminal(content) : content;
|
|
3965
|
+
});
|
|
3966
|
+
});
|
|
3967
|
+
program.command("close").description("Remove documents from the list. The original files are not deleted").argument("[targets...]", "Document ID or path").option("--all", "Close all open documents and remove the watch rules too", false).option("--json", "Output the result as JSON", false).action(async (targets, options) => {
|
|
3968
|
+
await execute("close", options.json, () => viaDaemon("documents.close", {
|
|
3969
|
+
cwd: context.cwd,
|
|
3970
|
+
targets,
|
|
3971
|
+
all: options.all
|
|
3972
|
+
}), (data) => `closed: ${String(data.closed.length)} (already closed: ${String(data.alreadyClosed.length)})`);
|
|
3973
|
+
});
|
|
3974
|
+
program.command("focus").description("Switch the document displayed in the management UI").argument("<documentId>", "Document ID").option("--json", "Output the result as JSON", false).action(async (documentId, options) => {
|
|
3975
|
+
await execute("focus", options.json, () => viaDaemon("documents.focus", { documentId }), (data) => `Switched the displayed document to ${data.documentId}`);
|
|
3976
|
+
});
|
|
3977
|
+
program.command("refresh").description("Re-read files. Without an argument, all open files").argument("[documentId]", "Document ID").option("--json", "Output the result as JSON", false).action(async (documentId, options) => {
|
|
3978
|
+
await execute("refresh", options.json, () => viaDaemon("documents.refresh", documentId === void 0 ? {} : { documentId }), (data) => `checked ${String(data.documents.length)} documents, updated ${String(data.changed.length)}`);
|
|
3979
|
+
});
|
|
3980
|
+
const renderRules = (data) => data.watchRules.length === 0 ? "No watch rules" : data.watchRules.map((rule) => `${rule.watchId} ${rule.kind} ${escapeForTerminal(rule.pattern ?? rule.root)}${rule.recursive ? " (recursive)" : ""}`).join("\n");
|
|
3981
|
+
const askCommand = program.command("ask");
|
|
3982
|
+
const seenAskFlags = /* @__PURE__ */ new Set();
|
|
3983
|
+
askCommand.on("option:open", () => seenAskFlags.add("open"));
|
|
3984
|
+
askCommand.on("option:no-open", () => seenAskFlags.add("no-open"));
|
|
3985
|
+
askCommand.description("Ask a person a question. The answer is entered and submitted in the management UI and received with `feedback wait`. Do not use it for secrets (passwords, API keys)").argument("<questionnaire>", "Questionnaire JSON file").option("--document <documentId>", "Ask about an open document").option("--revision <revision>", "Revision of --document to ask about. Defaults to the current revision").option("--view <path>", "Open the document, then ask about that revision").option("--html-mode <mode>", "How to show HTML opened with --view. With interactive, the HTML can send draft answers", parseHtmlMode).option("--assets-root <dir>", "Range of local files that the --view document may read").option("--asset <path>", "Local file to register individually for the --view document (can be repeated)", (value, previous) => [...previous, value], []).option("--operation-id <uuid>", "Identifier that keeps a retry from creating the same question twice").option("--open", "Open the management UI in the browser").option("--no-open", "Do not open the browser").option("--focus", "Make the asked document the displayed document", false).option("--json", "Output the result as JSON", false).action(async (questionnaire, options) => {
|
|
3986
|
+
await execute("ask", options.json, async () => {
|
|
3987
|
+
if (seenAskFlags.size === 2) throw new VdeError("E_INVALID_ARGUMENT", "--open and --no-open cannot be used together.");
|
|
3988
|
+
const params = {
|
|
3989
|
+
cwd: context.cwd,
|
|
3990
|
+
questionnaire: await readQuestionnaire(context.cwd, questionnaire),
|
|
3991
|
+
...options.document === void 0 ? {} : { documentId: options.document },
|
|
3992
|
+
...options.revision === void 0 ? {} : { revision: options.revision },
|
|
3993
|
+
...options.view === void 0 ? {} : { view: options.view },
|
|
3994
|
+
...options.htmlMode === void 0 ? {} : { htmlMode: options.htmlMode },
|
|
3995
|
+
...options.assetsRoot === void 0 ? {} : { assetsRoot: options.assetsRoot },
|
|
3996
|
+
assets: options.asset,
|
|
3997
|
+
...options.operationId === void 0 ? {} : { operationId: options.operationId }
|
|
3998
|
+
};
|
|
3999
|
+
const { connection, started } = await control.ensureDetailed();
|
|
4000
|
+
try {
|
|
4001
|
+
const outcome = unwrap(await connection.request("feedback.create", params));
|
|
4002
|
+
const warnings = [...outcome.warnings ?? []];
|
|
4003
|
+
if (options.focus) await connection.request("documents.focus", { documentId: outcome.data.request.documentId });
|
|
4004
|
+
if (options.open ?? (!options.json && context.stdoutIsTty && started)) warnings.push(...await openBrowser(connection));
|
|
4005
|
+
return {
|
|
4006
|
+
...outcome,
|
|
4007
|
+
warnings
|
|
4008
|
+
};
|
|
4009
|
+
} finally {
|
|
4010
|
+
connection.close();
|
|
4011
|
+
}
|
|
4012
|
+
}, (data) => `${describeRequest(data.request)}${data.replayed ? "\n(returned the existing question with the same operation ID)" : ""}`);
|
|
4013
|
+
});
|
|
4014
|
+
const feedbackCommand = program.command("feedback").description("Check the status and answers of questions. Draft answers (input before submit) are not returned");
|
|
4015
|
+
feedbackCommand.command("list").description("List questions").option("--status <status>", "pending, submitted, or cancelled", parseFeedbackStatus).option("--json", "Output the result as JSON", false).action(async (options) => {
|
|
4016
|
+
await execute("feedback.list", options.json, () => viaDaemon("feedback.list", options.status === void 0 ? {} : { status: options.status }), (data) => [...data.requests.map(describeRequest), `questions: ${String(data.requests.length)}`].join("\n"));
|
|
4017
|
+
});
|
|
4018
|
+
feedbackCommand.command("get").description("Get the status of a question and its submitted answers. Does not acknowledge").argument("<requestId>", "Question ID").option("--json", "Output the result as JSON", false).action(async (requestId, options) => {
|
|
4019
|
+
await execute("feedback.get", options.json, () => viaDaemon("feedback.get", { requestId }), describeAnswers);
|
|
4020
|
+
});
|
|
4021
|
+
feedbackCommand.command("wait").description("Wait until the answer is submitted or the question is cancelled. After the timeout, the question stays pending").argument("<requestId>", "Question ID").option("--timeout <seconds>", `Seconds to wait (default ${String(LIMITS.feedbackWaitDefaultSeconds)}, max ${String(LIMITS.feedbackWaitMaxSeconds)})`, parseInteger("--timeout", 1, LIMITS.feedbackWaitMaxSeconds), LIMITS.feedbackWaitDefaultSeconds).option("--json", "Output the result as JSON", false).action(async (requestId, options) => {
|
|
4022
|
+
await execute("feedback.wait", options.json, async () => unwrap(await waitForAnswer({
|
|
4023
|
+
requestId,
|
|
4024
|
+
timeoutMs: options.timeout * 1e3,
|
|
4025
|
+
connect: (signal) => control.ensure({ signal }),
|
|
4026
|
+
subscribeInterrupt: (listener) => {
|
|
4027
|
+
process.on("SIGINT", listener);
|
|
4028
|
+
return () => process.off("SIGINT", listener);
|
|
4029
|
+
}
|
|
4030
|
+
})), describeAnswers);
|
|
4031
|
+
});
|
|
4032
|
+
feedbackCommand.command("ack").description("Record that the submitted answers were received and handled. Repeating it gives the same result").argument("<requestId>", "Question ID").requiredOption("--submission-id <submissionId>", "Answer ID (from the result of get or wait)").option("--json", "Output the result as JSON", false).action(async (requestId, options) => {
|
|
4033
|
+
await execute("feedback.ack", options.json, () => viaDaemon("feedback.ack", {
|
|
4034
|
+
requestId,
|
|
4035
|
+
submissionId: options.submissionId
|
|
4036
|
+
}), describeAnswers);
|
|
4037
|
+
});
|
|
4038
|
+
feedbackCommand.command("cancel").description("Cancel a pending question").argument("<requestId>", "Question ID").option("--json", "Output the result as JSON", false).action(async (requestId, options) => {
|
|
4039
|
+
await execute("feedback.cancel", options.json, () => viaDaemon("feedback.cancel", { requestId }), describeAnswers);
|
|
4040
|
+
});
|
|
4041
|
+
feedbackCommand.command("forget").description("Delete the record of a finished question. A pending question cannot be deleted. Files and documents are kept").argument("<requestId>", "Question ID").option("--yes", "Confirm the deletion", false).option("--json", "Output the result as JSON", false).action(async (requestId, options) => {
|
|
4042
|
+
await execute("feedback.forget", options.json, () => viaDaemon("feedback.forget", {
|
|
4043
|
+
requestId,
|
|
4044
|
+
confirmed: options.yes
|
|
4045
|
+
}), (data) => `${data.requestId} deleted`);
|
|
4046
|
+
});
|
|
4047
|
+
const watchCommand = program.command("watch").description("List and remove watch rules");
|
|
4048
|
+
watchCommand.command("list").description("List watch rules").option("--json", "Output the result as JSON", false).action(async (options) => {
|
|
4049
|
+
await execute("watch.list", options.json, () => viaDaemon("watch.list", {}), renderRules);
|
|
4050
|
+
});
|
|
4051
|
+
watchCommand.command("remove").description("Remove a watch rule. Open documents stay open").argument("<watchId>", "Watch rule ID").option("--json", "Output the result as JSON", false).action(async (watchId, options) => {
|
|
4052
|
+
await execute("watch.remove", options.json, () => viaDaemon("watch.remove", { watchId }), renderRules);
|
|
4053
|
+
});
|
|
4054
|
+
program.command("ui").description("Open the management UI in the browser").option("--print-url", "Print a one-time URL instead of opening the browser", false).option("--json", "Output the result as JSON", false).action(async (options) => {
|
|
4055
|
+
if (options.printUrl && options.json) {
|
|
4056
|
+
fail(new VdeError("E_INVALID_ARGUMENT", "--print-url cannot be combined with --json because its output contains a secret."), true);
|
|
4057
|
+
return;
|
|
4058
|
+
}
|
|
4059
|
+
await execute("ui", options.json, () => showUi(options.printUrl), () => "");
|
|
4060
|
+
});
|
|
4061
|
+
const renderStatus = (status) => status.state === "running" ? `running pid=${String(status.pid)} open documents: ${String(status.openDocuments)} ${status.uiUrl ?? ""}` : "stopped";
|
|
4062
|
+
const daemon = program.command("daemon").description("Start, inspect, and stop the daemon");
|
|
4063
|
+
daemon.command("status").description("Show the daemon status. Does not start a new daemon when stopped").option("--json", "Output the result as JSON", false).action(async (options) => {
|
|
4064
|
+
await execute("daemon.status", options.json, async () => {
|
|
4065
|
+
const connection = await control.connectExisting();
|
|
4066
|
+
if (!connection) return { data: control.stoppedStatus() };
|
|
4067
|
+
try {
|
|
4068
|
+
return unwrap(await connection.request("daemon.status", {}));
|
|
4069
|
+
} finally {
|
|
4070
|
+
connection.close();
|
|
4071
|
+
}
|
|
4072
|
+
}, renderStatus);
|
|
4073
|
+
});
|
|
4074
|
+
daemon.command("start").description("Start the daemon. Reuses it if already running").option("--json", "Output the result as JSON", false).action(async (options) => {
|
|
4075
|
+
await execute("daemon.start", options.json, () => viaDaemon("daemon.status", {}), renderStatus);
|
|
4076
|
+
});
|
|
4077
|
+
daemon.command("stop").description("Stop the daemon. Open documents stay registered").option("--json", "Output the result as JSON", false).action(async (options) => {
|
|
4078
|
+
await execute("daemon.stop", options.json, async () => ({ data: {
|
|
4079
|
+
state: "stopped",
|
|
4080
|
+
...await control.stop()
|
|
4081
|
+
} }), (data) => data.wasRunning ? "Stopped" : "Not running");
|
|
4082
|
+
});
|
|
4083
|
+
daemon.command("restart").description("Stop the daemon, then start it").option("--json", "Output the result as JSON", false).action(async (options) => {
|
|
4084
|
+
await execute("daemon.restart", options.json, async () => {
|
|
4085
|
+
await control.stop();
|
|
4086
|
+
return viaDaemon("daemon.status", {});
|
|
4087
|
+
}, renderStatus);
|
|
4088
|
+
});
|
|
4089
|
+
program.command("serve").description("Run the daemon in the foreground. Press Ctrl+C to stop").option("--port <n>", "Port for the management UI. Defaults to a free port", parseInteger("--port", 1, 65535)).option("--preview-port <n>", "Port for the listener that shows documents. Defaults to a free port", parseInteger("--preview-port", 1, 65535)).action(async (options) => {
|
|
4090
|
+
try {
|
|
4091
|
+
const handle = await startDaemon({
|
|
4092
|
+
environment: context.environment,
|
|
4093
|
+
version: CLI_VERSION,
|
|
4094
|
+
...options.port === void 0 ? {} : { managementPort: options.port },
|
|
4095
|
+
...options.previewPort === void 0 ? {} : { previewPort: options.previewPort }
|
|
4096
|
+
});
|
|
4097
|
+
context.stderr(`Started the daemon in the foreground (pid=${String(process.pid)}, ${handle.uiUrl}). Press Ctrl+C to stop.\n`);
|
|
4098
|
+
const onSignal = () => void handle.stop("signal");
|
|
4099
|
+
process.once("SIGINT", onSignal);
|
|
4100
|
+
process.once("SIGTERM", onSignal);
|
|
4101
|
+
await handle.stopped;
|
|
4102
|
+
process.off("SIGINT", onSignal);
|
|
4103
|
+
process.off("SIGTERM", onSignal);
|
|
4104
|
+
} catch (error) {
|
|
4105
|
+
fail(error, false);
|
|
4106
|
+
}
|
|
4107
|
+
});
|
|
4108
|
+
program.command("doctor").description("Diagnose the state and the daemon").option("--repair", "Recover from a verified backup and reclaim the runtime of a stopped daemon", false).option("--yes", "Confirm running --repair", false).option("--json", "Output the result as JSON", false).action(async (options) => {
|
|
4109
|
+
await execute("doctor", options.json, async () => {
|
|
4110
|
+
if (options.repair && !options.yes) throw new VdeError("E_CONFIRMATION_REQUIRED", "--repair may rewrite the state. Add --yes to run it.");
|
|
4111
|
+
const result = await runDoctor({
|
|
4112
|
+
environment: context.environment,
|
|
4113
|
+
control,
|
|
4114
|
+
version: CLI_VERSION,
|
|
4115
|
+
repair: options.repair
|
|
4116
|
+
});
|
|
4117
|
+
return {
|
|
4118
|
+
data: result.report,
|
|
4119
|
+
warnings: result.warnings
|
|
4120
|
+
};
|
|
4121
|
+
}, (report) => [
|
|
4122
|
+
`state root: ${escapeForTerminal(report.stateRoot.path)}`,
|
|
4123
|
+
`state: ${report.state.status}`,
|
|
4124
|
+
`backup: ${report.previousState.status}`,
|
|
4125
|
+
`daemon: ${report.daemon.reachable ? "running" : "stopped"} (lock: ${report.daemon.lock})`,
|
|
4126
|
+
...report.problems.map((problem) => `problem: ${problem.code} ${problem.message}`),
|
|
4127
|
+
...report.repairs.map((repair) => `repair: ${repair}`),
|
|
4128
|
+
report.problems.length === 0 ? "No problems found." : ""
|
|
4129
|
+
].filter((line) => line !== "").join("\n"));
|
|
4130
|
+
});
|
|
4131
|
+
const valueOptions = /* @__PURE__ */ new Set();
|
|
4132
|
+
for (const option of openCommand.options) {
|
|
4133
|
+
if (!option.required && !option.optional) continue;
|
|
4134
|
+
if (option.short) valueOptions.add(option.short);
|
|
4135
|
+
if (option.long) valueOptions.add(option.long);
|
|
4136
|
+
}
|
|
4137
|
+
const argv = normalizeArgv(rawArgv, context.stdin.isPiped, {
|
|
4138
|
+
subcommands: /* @__PURE__ */ new Set([...program.commands.map((command) => command.name()), "help"]),
|
|
4139
|
+
valueOptions
|
|
4140
|
+
});
|
|
4141
|
+
try {
|
|
4142
|
+
await program.parseAsync(argv, { from: "user" });
|
|
4143
|
+
} catch (error) {
|
|
4144
|
+
if (error instanceof CommanderError) {
|
|
4145
|
+
if (error.exitCode === 0) return ExitCode.success;
|
|
4146
|
+
if (wantsJson) context.stdout(`${safeJson(errorEnvelope({
|
|
4147
|
+
code: "E_INVALID_ARGUMENT",
|
|
4148
|
+
message: error.message,
|
|
4149
|
+
retryable: false,
|
|
4150
|
+
details: { reason: error.code }
|
|
4151
|
+
}))}\n`);
|
|
4152
|
+
return ExitCode.usage;
|
|
4153
|
+
}
|
|
4154
|
+
throw error;
|
|
4155
|
+
}
|
|
4156
|
+
return exitCode;
|
|
4157
|
+
}
|
|
4158
|
+
//#endregion
|
|
4159
|
+
//#region src/cli.ts
|
|
4160
|
+
function stdinIsPiped() {
|
|
4161
|
+
try {
|
|
4162
|
+
const stats = fstatSync(0);
|
|
4163
|
+
return stats.isFIFO() || stats.isFile();
|
|
4164
|
+
} catch {
|
|
4165
|
+
return false;
|
|
4166
|
+
}
|
|
4167
|
+
}
|
|
4168
|
+
async function readStdin() {
|
|
4169
|
+
const chunks = [];
|
|
4170
|
+
let size = 0;
|
|
4171
|
+
for await (const chunk of process.stdin) {
|
|
4172
|
+
const bytes = chunk;
|
|
4173
|
+
size += bytes.byteLength;
|
|
4174
|
+
if (size > LIMITS.documentBytes) throw new VdeError("E_LIMIT_EXCEEDED", "The stdin content exceeds the size limit for one document.", {
|
|
4175
|
+
limit: "documentBytes",
|
|
4176
|
+
max: LIMITS.documentBytes
|
|
4177
|
+
});
|
|
4178
|
+
chunks.push(bytes);
|
|
4179
|
+
}
|
|
4180
|
+
return Buffer.concat(chunks, size);
|
|
4181
|
+
}
|
|
4182
|
+
process.exitCode = await runCli(process.argv.slice(2), {
|
|
4183
|
+
stdout: (text) => process.stdout.write(text),
|
|
4184
|
+
stderr: (text) => process.stderr.write(text),
|
|
4185
|
+
cwd: process.cwd(),
|
|
4186
|
+
environment: currentPathEnvironment(),
|
|
4187
|
+
stdoutIsTty: process.stdout.isTTY === true,
|
|
4188
|
+
stdin: {
|
|
4189
|
+
isPiped: stdinIsPiped(),
|
|
4190
|
+
read: readStdin
|
|
4191
|
+
}
|
|
4192
|
+
});
|
|
4193
|
+
//#endregion
|
|
4194
|
+
export {};
|