acpus 0.0.1 → 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.
Files changed (45) hide show
  1. package/README.md +6 -90
  2. package/dist/catalog.d.ts +27 -0
  3. package/dist/catalog.d.ts.map +1 -0
  4. package/dist/catalog.js +189 -0
  5. package/dist/catalog.js.map +1 -0
  6. package/dist/follow.d.ts +23 -0
  7. package/dist/follow.d.ts.map +1 -0
  8. package/dist/follow.js +109 -0
  9. package/dist/follow.js.map +1 -0
  10. package/dist/index.d.ts +3 -0
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/index.js +414 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/io.d.ts +4 -0
  15. package/dist/io.d.ts.map +1 -0
  16. package/dist/io.js +38 -0
  17. package/dist/io.js.map +1 -0
  18. package/dist/observations.d.ts +26 -0
  19. package/dist/observations.d.ts.map +1 -0
  20. package/dist/observations.js +60 -0
  21. package/dist/observations.js.map +1 -0
  22. package/dist/output.d.ts +9 -0
  23. package/dist/output.d.ts.map +1 -0
  24. package/dist/output.js +51 -0
  25. package/dist/output.js.map +1 -0
  26. package/dist/runs-show.d.ts +5 -0
  27. package/dist/runs-show.d.ts.map +1 -0
  28. package/dist/runs-show.js +83 -0
  29. package/dist/runs-show.js.map +1 -0
  30. package/dist/supervisor-client.d.ts +9 -0
  31. package/dist/supervisor-client.d.ts.map +1 -0
  32. package/dist/supervisor-client.js +8 -0
  33. package/dist/supervisor-client.js.map +1 -0
  34. package/dist/supervisor.d.ts +18 -0
  35. package/dist/supervisor.d.ts.map +1 -0
  36. package/dist/supervisor.js +24 -0
  37. package/dist/supervisor.js.map +1 -0
  38. package/package.json +31 -45
  39. package/dist/cli.d.mts +0 -1
  40. package/dist/cli.mjs +0 -3860
  41. package/dist/index.d.mts +0 -2742
  42. package/dist/index.mjs +0 -2
  43. package/dist/monitor-app-CSjUPe9j.mjs +0 -434
  44. package/dist/run-workflow-CbxKhAqF.mjs +0 -13586
  45. package/schemas/workflow-spec.schema.json +0 -2042
package/dist/cli.mjs DELETED
@@ -1,3860 +0,0 @@
1
- #!/usr/bin/env node
2
- import { At as __require, Ct as writeRunIndex, Dt as runDir, Et as projectWorkflowsDir, O as compileExecutionPlan, Ot as runsDir, S as syncRun, St as readRunIndex, Tt as globalWorkflowsDir, _ as applyInputDefaults, a as previewRunView, b as issue, d as recoverDriver, f as runWorkflowWorker, ft as WorkflowSpecSchema, g as lintWorkflowSpec, gt as resolveRunLocator, h as loadWorkflowSpec, jt as __toESM, kt as __commonJSMin, l as buildRunMonitorView, m as workerIsActive, mt as getOutputContract, o as runViewFromIndex, p as spawnBackgroundWorker, t as prepareRun, u as buildTaskDetailView, v as validateWorkflowInput, wt as draftsDir, x as resultFromIssues, xt as appendEvent, yt as buildRunDiagnosticsView } from "./run-workflow-CbxKhAqF.mjs";
3
- import path from "node:path";
4
- import fs from "node:fs/promises";
5
- import React from "react";
6
- import { render } from "ink";
7
- import { fileURLToPath } from "node:url";
8
- //#region node_modules/commander/lib/error.js
9
- var require_error = /* @__PURE__ */ __commonJSMin(((exports) => {
10
- /**
11
- * CommanderError class
12
- */
13
- var CommanderError = class extends Error {
14
- /**
15
- * Constructs the CommanderError class
16
- * @param {number} exitCode suggested exit code which could be used with process.exit
17
- * @param {string} code an id string representing the error
18
- * @param {string} message human-readable description of the error
19
- */
20
- constructor(exitCode, code, message) {
21
- super(message);
22
- Error.captureStackTrace(this, this.constructor);
23
- this.name = this.constructor.name;
24
- this.code = code;
25
- this.exitCode = exitCode;
26
- this.nestedError = void 0;
27
- }
28
- };
29
- /**
30
- * InvalidArgumentError class
31
- */
32
- var InvalidArgumentError = class extends CommanderError {
33
- /**
34
- * Constructs the InvalidArgumentError class
35
- * @param {string} [message] explanation of why argument is invalid
36
- */
37
- constructor(message) {
38
- super(1, "commander.invalidArgument", message);
39
- Error.captureStackTrace(this, this.constructor);
40
- this.name = this.constructor.name;
41
- }
42
- };
43
- exports.CommanderError = CommanderError;
44
- exports.InvalidArgumentError = InvalidArgumentError;
45
- }));
46
- //#endregion
47
- //#region node_modules/commander/lib/argument.js
48
- var require_argument = /* @__PURE__ */ __commonJSMin(((exports) => {
49
- const { InvalidArgumentError } = require_error();
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
- break;
79
- }
80
- if (this._name.endsWith("...")) {
81
- this.variadic = true;
82
- this._name = this._name.slice(0, -3);
83
- }
84
- }
85
- /**
86
- * Return argument name.
87
- *
88
- * @return {string}
89
- */
90
- name() {
91
- return this._name;
92
- }
93
- /**
94
- * @package
95
- */
96
- _collectValue(value, previous) {
97
- if (previous === this.defaultValue || !Array.isArray(previous)) return [value];
98
- previous.push(value);
99
- return previous;
100
- }
101
- /**
102
- * Set the default value, and optionally supply the description to be displayed in the help.
103
- *
104
- * @param {*} value
105
- * @param {string} [description]
106
- * @return {Argument}
107
- */
108
- default(value, description) {
109
- this.defaultValue = value;
110
- this.defaultValueDescription = description;
111
- return this;
112
- }
113
- /**
114
- * Set the custom handler for processing CLI command arguments into argument values.
115
- *
116
- * @param {Function} [fn]
117
- * @return {Argument}
118
- */
119
- argParser(fn) {
120
- this.parseArg = fn;
121
- return this;
122
- }
123
- /**
124
- * Only allow argument value to be one of choices.
125
- *
126
- * @param {string[]} values
127
- * @return {Argument}
128
- */
129
- choices(values) {
130
- this.argChoices = values.slice();
131
- this.parseArg = (arg, previous) => {
132
- if (!this.argChoices.includes(arg)) throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
133
- if (this.variadic) return this._collectValue(arg, previous);
134
- return arg;
135
- };
136
- return this;
137
- }
138
- /**
139
- * Make argument required.
140
- *
141
- * @returns {Argument}
142
- */
143
- argRequired() {
144
- this.required = true;
145
- return this;
146
- }
147
- /**
148
- * Make argument optional.
149
- *
150
- * @returns {Argument}
151
- */
152
- argOptional() {
153
- this.required = false;
154
- return this;
155
- }
156
- };
157
- /**
158
- * Takes an argument and returns its human readable equivalent for help usage.
159
- *
160
- * @param {Argument} arg
161
- * @return {string}
162
- * @private
163
- */
164
- function humanReadableArgName(arg) {
165
- const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
166
- return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
167
- }
168
- exports.Argument = Argument;
169
- exports.humanReadableArgName = humanReadableArgName;
170
- }));
171
- //#endregion
172
- //#region node_modules/commander/lib/help.js
173
- var require_help = /* @__PURE__ */ __commonJSMin(((exports) => {
174
- const { humanReadableArgName } = require_argument();
175
- /**
176
- * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`
177
- * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types
178
- * @typedef { import("./argument.js").Argument } Argument
179
- * @typedef { import("./command.js").Command } Command
180
- * @typedef { import("./option.js").Option } Option
181
- */
182
- var Help = class {
183
- constructor() {
184
- this.helpWidth = void 0;
185
- this.minWidthToWrap = 40;
186
- this.sortSubcommands = false;
187
- this.sortOptions = false;
188
- this.showGlobalOptions = false;
189
- }
190
- /**
191
- * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
192
- * and just before calling `formatHelp()`.
193
- *
194
- * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
195
- *
196
- * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
197
- */
198
- prepareContext(contextOptions) {
199
- this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
200
- }
201
- /**
202
- * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
203
- *
204
- * @param {Command} cmd
205
- * @returns {Command[]}
206
- */
207
- visibleCommands(cmd) {
208
- const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);
209
- const helpCommand = cmd._getHelpCommand();
210
- if (helpCommand && !helpCommand._hidden) visibleCommands.push(helpCommand);
211
- if (this.sortSubcommands) visibleCommands.sort((a, b) => {
212
- return a.name().localeCompare(b.name());
213
- });
214
- return visibleCommands;
215
- }
216
- /**
217
- * Compare options for sort.
218
- *
219
- * @param {Option} a
220
- * @param {Option} b
221
- * @returns {number}
222
- */
223
- compareOptions(a, b) {
224
- const getSortKey = (option) => {
225
- return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
226
- };
227
- return getSortKey(a).localeCompare(getSortKey(b));
228
- }
229
- /**
230
- * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
231
- *
232
- * @param {Command} cmd
233
- * @returns {Option[]}
234
- */
235
- visibleOptions(cmd) {
236
- const visibleOptions = cmd.options.filter((option) => !option.hidden);
237
- const helpOption = cmd._getHelpOption();
238
- if (helpOption && !helpOption.hidden) {
239
- const removeShort = helpOption.short && cmd._findOption(helpOption.short);
240
- const removeLong = helpOption.long && cmd._findOption(helpOption.long);
241
- if (!removeShort && !removeLong) visibleOptions.push(helpOption);
242
- else if (helpOption.long && !removeLong) visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
243
- else if (helpOption.short && !removeShort) visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
244
- }
245
- if (this.sortOptions) visibleOptions.sort(this.compareOptions);
246
- return visibleOptions;
247
- }
248
- /**
249
- * Get an array of the visible global options. (Not including help.)
250
- *
251
- * @param {Command} cmd
252
- * @returns {Option[]}
253
- */
254
- visibleGlobalOptions(cmd) {
255
- if (!this.showGlobalOptions) return [];
256
- const globalOptions = [];
257
- for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
258
- const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
259
- globalOptions.push(...visibleOptions);
260
- }
261
- if (this.sortOptions) globalOptions.sort(this.compareOptions);
262
- return globalOptions;
263
- }
264
- /**
265
- * Get an array of the arguments if any have a description.
266
- *
267
- * @param {Command} cmd
268
- * @returns {Argument[]}
269
- */
270
- visibleArguments(cmd) {
271
- if (cmd._argsDescription) cmd.registeredArguments.forEach((argument) => {
272
- argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
273
- });
274
- if (cmd.registeredArguments.find((argument) => argument.description)) return cmd.registeredArguments;
275
- return [];
276
- }
277
- /**
278
- * Get the command term to show in the list of subcommands.
279
- *
280
- * @param {Command} cmd
281
- * @returns {string}
282
- */
283
- subcommandTerm(cmd) {
284
- const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
285
- return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
286
- }
287
- /**
288
- * Get the option term to show in the list of options.
289
- *
290
- * @param {Option} option
291
- * @returns {string}
292
- */
293
- optionTerm(option) {
294
- return option.flags;
295
- }
296
- /**
297
- * Get the argument term to show in the list of arguments.
298
- *
299
- * @param {Argument} argument
300
- * @returns {string}
301
- */
302
- argumentTerm(argument) {
303
- return argument.name();
304
- }
305
- /**
306
- * Get the longest command term length.
307
- *
308
- * @param {Command} cmd
309
- * @param {Help} helper
310
- * @returns {number}
311
- */
312
- longestSubcommandTermLength(cmd, helper) {
313
- return helper.visibleCommands(cmd).reduce((max, command) => {
314
- return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
315
- }, 0);
316
- }
317
- /**
318
- * Get the longest option term length.
319
- *
320
- * @param {Command} cmd
321
- * @param {Help} helper
322
- * @returns {number}
323
- */
324
- longestOptionTermLength(cmd, helper) {
325
- return helper.visibleOptions(cmd).reduce((max, option) => {
326
- return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
327
- }, 0);
328
- }
329
- /**
330
- * Get the longest global option term length.
331
- *
332
- * @param {Command} cmd
333
- * @param {Help} helper
334
- * @returns {number}
335
- */
336
- longestGlobalOptionTermLength(cmd, helper) {
337
- return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
338
- return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
339
- }, 0);
340
- }
341
- /**
342
- * Get the longest argument term length.
343
- *
344
- * @param {Command} cmd
345
- * @param {Help} helper
346
- * @returns {number}
347
- */
348
- longestArgumentTermLength(cmd, helper) {
349
- return helper.visibleArguments(cmd).reduce((max, argument) => {
350
- return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
351
- }, 0);
352
- }
353
- /**
354
- * Get the command usage to be displayed at the top of the built-in help.
355
- *
356
- * @param {Command} cmd
357
- * @returns {string}
358
- */
359
- commandUsage(cmd) {
360
- let cmdName = cmd._name;
361
- if (cmd._aliases[0]) cmdName = cmdName + "|" + cmd._aliases[0];
362
- let ancestorCmdNames = "";
363
- for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
364
- return ancestorCmdNames + cmdName + " " + cmd.usage();
365
- }
366
- /**
367
- * Get the description for the command.
368
- *
369
- * @param {Command} cmd
370
- * @returns {string}
371
- */
372
- commandDescription(cmd) {
373
- return cmd.description();
374
- }
375
- /**
376
- * Get the subcommand summary to show in the list of subcommands.
377
- * (Fallback to description for backwards compatibility.)
378
- *
379
- * @param {Command} cmd
380
- * @returns {string}
381
- */
382
- subcommandDescription(cmd) {
383
- return cmd.summary() || cmd.description();
384
- }
385
- /**
386
- * Get the option description to show in the list of options.
387
- *
388
- * @param {Option} option
389
- * @return {string}
390
- */
391
- optionDescription(option) {
392
- const extraInfo = [];
393
- if (option.argChoices) extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
394
- if (option.defaultValue !== void 0) {
395
- if (option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean") extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
396
- }
397
- if (option.presetArg !== void 0 && option.optional) extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
398
- if (option.envVar !== void 0) extraInfo.push(`env: ${option.envVar}`);
399
- if (extraInfo.length > 0) {
400
- const extraDescription = `(${extraInfo.join(", ")})`;
401
- if (option.description) return `${option.description} ${extraDescription}`;
402
- return extraDescription;
403
- }
404
- return option.description;
405
- }
406
- /**
407
- * Get the argument description to show in the list of arguments.
408
- *
409
- * @param {Argument} argument
410
- * @return {string}
411
- */
412
- argumentDescription(argument) {
413
- const extraInfo = [];
414
- if (argument.argChoices) extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
415
- if (argument.defaultValue !== void 0) extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
416
- if (extraInfo.length > 0) {
417
- const extraDescription = `(${extraInfo.join(", ")})`;
418
- if (argument.description) return `${argument.description} ${extraDescription}`;
419
- return extraDescription;
420
- }
421
- return argument.description;
422
- }
423
- /**
424
- * Format a list of items, given a heading and an array of formatted items.
425
- *
426
- * @param {string} heading
427
- * @param {string[]} items
428
- * @param {Help} helper
429
- * @returns string[]
430
- */
431
- formatItemList(heading, items, helper) {
432
- if (items.length === 0) return [];
433
- return [
434
- helper.styleTitle(heading),
435
- ...items,
436
- ""
437
- ];
438
- }
439
- /**
440
- * Group items by their help group heading.
441
- *
442
- * @param {Command[] | Option[]} unsortedItems
443
- * @param {Command[] | Option[]} visibleItems
444
- * @param {Function} getGroup
445
- * @returns {Map<string, Command[] | Option[]>}
446
- */
447
- groupItems(unsortedItems, visibleItems, getGroup) {
448
- const result = /* @__PURE__ */ new Map();
449
- unsortedItems.forEach((item) => {
450
- const group = getGroup(item);
451
- if (!result.has(group)) result.set(group, []);
452
- });
453
- visibleItems.forEach((item) => {
454
- const group = getGroup(item);
455
- if (!result.has(group)) result.set(group, []);
456
- result.get(group).push(item);
457
- });
458
- return result;
459
- }
460
- /**
461
- * Generate the built-in help text.
462
- *
463
- * @param {Command} cmd
464
- * @param {Help} helper
465
- * @returns {string}
466
- */
467
- formatHelp(cmd, helper) {
468
- const termWidth = helper.padWidth(cmd, helper);
469
- const helpWidth = helper.helpWidth ?? 80;
470
- function callFormatItem(term, description) {
471
- return helper.formatItem(term, termWidth, description, helper);
472
- }
473
- let output = [`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`, ""];
474
- const commandDescription = helper.commandDescription(cmd);
475
- if (commandDescription.length > 0) output = output.concat([helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth), ""]);
476
- const argumentList = helper.visibleArguments(cmd).map((argument) => {
477
- return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
478
- });
479
- output = output.concat(this.formatItemList("Arguments:", argumentList, helper));
480
- this.groupItems(cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? "Options:").forEach((options, group) => {
481
- const optionList = options.map((option) => {
482
- return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
483
- });
484
- output = output.concat(this.formatItemList(group, optionList, helper));
485
- });
486
- if (helper.showGlobalOptions) {
487
- const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
488
- return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
489
- });
490
- output = output.concat(this.formatItemList("Global Options:", globalOptionList, helper));
491
- }
492
- this.groupItems(cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || "Commands:").forEach((commands, group) => {
493
- const commandList = commands.map((sub) => {
494
- return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)));
495
- });
496
- output = output.concat(this.formatItemList(group, commandList, helper));
497
- });
498
- return output.join("\n");
499
- }
500
- /**
501
- * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
502
- *
503
- * @param {string} str
504
- * @returns {number}
505
- */
506
- displayWidth(str) {
507
- return stripColor(str).length;
508
- }
509
- /**
510
- * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
511
- *
512
- * @param {string} str
513
- * @returns {string}
514
- */
515
- styleTitle(str) {
516
- return str;
517
- }
518
- styleUsage(str) {
519
- return str.split(" ").map((word) => {
520
- if (word === "[options]") return this.styleOptionText(word);
521
- if (word === "[command]") return this.styleSubcommandText(word);
522
- if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
523
- return this.styleCommandText(word);
524
- }).join(" ");
525
- }
526
- styleCommandDescription(str) {
527
- return this.styleDescriptionText(str);
528
- }
529
- styleOptionDescription(str) {
530
- return this.styleDescriptionText(str);
531
- }
532
- styleSubcommandDescription(str) {
533
- return this.styleDescriptionText(str);
534
- }
535
- styleArgumentDescription(str) {
536
- return this.styleDescriptionText(str);
537
- }
538
- styleDescriptionText(str) {
539
- return str;
540
- }
541
- styleOptionTerm(str) {
542
- return this.styleOptionText(str);
543
- }
544
- styleSubcommandTerm(str) {
545
- return str.split(" ").map((word) => {
546
- if (word === "[options]") return this.styleOptionText(word);
547
- if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
548
- return this.styleSubcommandText(word);
549
- }).join(" ");
550
- }
551
- styleArgumentTerm(str) {
552
- return this.styleArgumentText(str);
553
- }
554
- styleOptionText(str) {
555
- return str;
556
- }
557
- styleArgumentText(str) {
558
- return str;
559
- }
560
- styleSubcommandText(str) {
561
- return str;
562
- }
563
- styleCommandText(str) {
564
- return str;
565
- }
566
- /**
567
- * Calculate the pad width from the maximum term length.
568
- *
569
- * @param {Command} cmd
570
- * @param {Help} helper
571
- * @returns {number}
572
- */
573
- padWidth(cmd, helper) {
574
- return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
575
- }
576
- /**
577
- * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
578
- *
579
- * @param {string} str
580
- * @returns {boolean}
581
- */
582
- preformatted(str) {
583
- return /\n[^\S\r\n]/.test(str);
584
- }
585
- /**
586
- * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
587
- *
588
- * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
589
- * TTT DDD DDDD
590
- * DD DDD
591
- *
592
- * @param {string} term
593
- * @param {number} termWidth
594
- * @param {string} description
595
- * @param {Help} helper
596
- * @returns {string}
597
- */
598
- formatItem(term, termWidth, description, helper) {
599
- const itemIndent = 2;
600
- const itemIndentStr = " ".repeat(itemIndent);
601
- if (!description) return itemIndentStr + term;
602
- const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
603
- const spacerWidth = 2;
604
- const remainingWidth = (this.helpWidth ?? 80) - termWidth - spacerWidth - itemIndent;
605
- let formattedDescription;
606
- if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) formattedDescription = description;
607
- else formattedDescription = helper.boxWrap(description, remainingWidth).replace(/\n/g, "\n" + " ".repeat(termWidth + spacerWidth));
608
- return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `\n${itemIndentStr}`);
609
- }
610
- /**
611
- * Wrap a string at whitespace, preserving existing line breaks.
612
- * Wrapping is skipped if the width is less than `minWidthToWrap`.
613
- *
614
- * @param {string} str
615
- * @param {number} width
616
- * @returns {string}
617
- */
618
- boxWrap(str, width) {
619
- if (width < this.minWidthToWrap) return str;
620
- const rawLines = str.split(/\r\n|\n/);
621
- const chunkPattern = /[\s]*[^\s]+/g;
622
- const wrappedLines = [];
623
- rawLines.forEach((line) => {
624
- const chunks = line.match(chunkPattern);
625
- if (chunks === null) {
626
- wrappedLines.push("");
627
- return;
628
- }
629
- let sumChunks = [chunks.shift()];
630
- let sumWidth = this.displayWidth(sumChunks[0]);
631
- chunks.forEach((chunk) => {
632
- const visibleWidth = this.displayWidth(chunk);
633
- if (sumWidth + visibleWidth <= width) {
634
- sumChunks.push(chunk);
635
- sumWidth += visibleWidth;
636
- return;
637
- }
638
- wrappedLines.push(sumChunks.join(""));
639
- const nextChunk = chunk.trimStart();
640
- sumChunks = [nextChunk];
641
- sumWidth = this.displayWidth(nextChunk);
642
- });
643
- wrappedLines.push(sumChunks.join(""));
644
- });
645
- return wrappedLines.join("\n");
646
- }
647
- };
648
- /**
649
- * Strip style ANSI escape sequences from the string. In particular, SGR (Select Graphic Rendition) codes.
650
- *
651
- * @param {string} str
652
- * @returns {string}
653
- * @package
654
- */
655
- function stripColor(str) {
656
- return str.replace(/\x1b\[\d*(;\d*)*m/g, "");
657
- }
658
- exports.Help = Help;
659
- exports.stripColor = stripColor;
660
- }));
661
- //#endregion
662
- //#region node_modules/commander/lib/option.js
663
- var require_option = /* @__PURE__ */ __commonJSMin(((exports) => {
664
- const { InvalidArgumentError } = require_error();
665
- var Option = class {
666
- /**
667
- * Initialize a new `Option` with the given `flags` and `description`.
668
- *
669
- * @param {string} flags
670
- * @param {string} [description]
671
- */
672
- constructor(flags, description) {
673
- this.flags = flags;
674
- this.description = description || "";
675
- this.required = flags.includes("<");
676
- this.optional = flags.includes("[");
677
- this.variadic = /\w\.\.\.[>\]]$/.test(flags);
678
- this.mandatory = false;
679
- const optionFlags = splitOptionFlags(flags);
680
- this.short = optionFlags.shortFlag;
681
- this.long = optionFlags.longFlag;
682
- this.negate = false;
683
- if (this.long) this.negate = this.long.startsWith("--no-");
684
- this.defaultValue = void 0;
685
- this.defaultValueDescription = void 0;
686
- this.presetArg = void 0;
687
- this.envVar = void 0;
688
- this.parseArg = void 0;
689
- this.hidden = false;
690
- this.argChoices = void 0;
691
- this.conflictsWith = [];
692
- this.implied = void 0;
693
- this.helpGroupHeading = void 0;
694
- }
695
- /**
696
- * Set the default value, and optionally supply the description to be displayed in the help.
697
- *
698
- * @param {*} value
699
- * @param {string} [description]
700
- * @return {Option}
701
- */
702
- default(value, description) {
703
- this.defaultValue = value;
704
- this.defaultValueDescription = description;
705
- return this;
706
- }
707
- /**
708
- * Preset to use when option used without option-argument, especially optional but also boolean and negated.
709
- * The custom processing (parseArg) is called.
710
- *
711
- * @example
712
- * new Option('--color').default('GREYSCALE').preset('RGB');
713
- * new Option('--donate [amount]').preset('20').argParser(parseFloat);
714
- *
715
- * @param {*} arg
716
- * @return {Option}
717
- */
718
- preset(arg) {
719
- this.presetArg = arg;
720
- return this;
721
- }
722
- /**
723
- * Add option name(s) that conflict with this option.
724
- * An error will be displayed if conflicting options are found during parsing.
725
- *
726
- * @example
727
- * new Option('--rgb').conflicts('cmyk');
728
- * new Option('--js').conflicts(['ts', 'jsx']);
729
- *
730
- * @param {(string | string[])} names
731
- * @return {Option}
732
- */
733
- conflicts(names) {
734
- this.conflictsWith = this.conflictsWith.concat(names);
735
- return this;
736
- }
737
- /**
738
- * Specify implied option values for when this option is set and the implied options are not.
739
- *
740
- * The custom processing (parseArg) is not called on the implied values.
741
- *
742
- * @example
743
- * program
744
- * .addOption(new Option('--log', 'write logging information to file'))
745
- * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
746
- *
747
- * @param {object} impliedOptionValues
748
- * @return {Option}
749
- */
750
- implies(impliedOptionValues) {
751
- let newImplied = impliedOptionValues;
752
- if (typeof impliedOptionValues === "string") newImplied = { [impliedOptionValues]: true };
753
- this.implied = Object.assign(this.implied || {}, newImplied);
754
- return this;
755
- }
756
- /**
757
- * Set environment variable to check for option value.
758
- *
759
- * An environment variable is only used if when processed the current option value is
760
- * undefined, or the source of the current value is 'default' or 'config' or 'env'.
761
- *
762
- * @param {string} name
763
- * @return {Option}
764
- */
765
- env(name) {
766
- this.envVar = name;
767
- return this;
768
- }
769
- /**
770
- * Set the custom handler for processing CLI option arguments into option values.
771
- *
772
- * @param {Function} [fn]
773
- * @return {Option}
774
- */
775
- argParser(fn) {
776
- this.parseArg = fn;
777
- return this;
778
- }
779
- /**
780
- * Whether the option is mandatory and must have a value after parsing.
781
- *
782
- * @param {boolean} [mandatory=true]
783
- * @return {Option}
784
- */
785
- makeOptionMandatory(mandatory = true) {
786
- this.mandatory = !!mandatory;
787
- return this;
788
- }
789
- /**
790
- * Hide option in help.
791
- *
792
- * @param {boolean} [hide=true]
793
- * @return {Option}
794
- */
795
- hideHelp(hide = true) {
796
- this.hidden = !!hide;
797
- return this;
798
- }
799
- /**
800
- * @package
801
- */
802
- _collectValue(value, previous) {
803
- if (previous === this.defaultValue || !Array.isArray(previous)) return [value];
804
- previous.push(value);
805
- return previous;
806
- }
807
- /**
808
- * Only allow option value to be one of choices.
809
- *
810
- * @param {string[]} values
811
- * @return {Option}
812
- */
813
- choices(values) {
814
- this.argChoices = values.slice();
815
- this.parseArg = (arg, previous) => {
816
- if (!this.argChoices.includes(arg)) throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
817
- if (this.variadic) return this._collectValue(arg, previous);
818
- return arg;
819
- };
820
- return this;
821
- }
822
- /**
823
- * Return option name.
824
- *
825
- * @return {string}
826
- */
827
- name() {
828
- if (this.long) return this.long.replace(/^--/, "");
829
- return this.short.replace(/^-/, "");
830
- }
831
- /**
832
- * Return option name, in a camelcase format that can be used
833
- * as an object attribute key.
834
- *
835
- * @return {string}
836
- */
837
- attributeName() {
838
- if (this.negate) return camelcase(this.name().replace(/^no-/, ""));
839
- return camelcase(this.name());
840
- }
841
- /**
842
- * Set the help group heading.
843
- *
844
- * @param {string} heading
845
- * @return {Option}
846
- */
847
- helpGroup(heading) {
848
- this.helpGroupHeading = heading;
849
- return this;
850
- }
851
- /**
852
- * Check if `arg` matches the short or long flag.
853
- *
854
- * @param {string} arg
855
- * @return {boolean}
856
- * @package
857
- */
858
- is(arg) {
859
- return this.short === arg || this.long === arg;
860
- }
861
- /**
862
- * Return whether a boolean option.
863
- *
864
- * Options are one of boolean, negated, required argument, or optional argument.
865
- *
866
- * @return {boolean}
867
- * @package
868
- */
869
- isBoolean() {
870
- return !this.required && !this.optional && !this.negate;
871
- }
872
- };
873
- /**
874
- * This class is to make it easier to work with dual options, without changing the existing
875
- * implementation. We support separate dual options for separate positive and negative options,
876
- * like `--build` and `--no-build`, which share a single option value. This works nicely for some
877
- * use cases, but is tricky for others where we want separate behaviours despite
878
- * the single shared option value.
879
- */
880
- var DualOptions = class {
881
- /**
882
- * @param {Option[]} options
883
- */
884
- constructor(options) {
885
- this.positiveOptions = /* @__PURE__ */ new Map();
886
- this.negativeOptions = /* @__PURE__ */ new Map();
887
- this.dualOptions = /* @__PURE__ */ new Set();
888
- options.forEach((option) => {
889
- if (option.negate) this.negativeOptions.set(option.attributeName(), option);
890
- else this.positiveOptions.set(option.attributeName(), option);
891
- });
892
- this.negativeOptions.forEach((value, key) => {
893
- if (this.positiveOptions.has(key)) this.dualOptions.add(key);
894
- });
895
- }
896
- /**
897
- * Did the value come from the option, and not from possible matching dual option?
898
- *
899
- * @param {*} value
900
- * @param {Option} option
901
- * @returns {boolean}
902
- */
903
- valueFromOption(value, option) {
904
- const optionKey = option.attributeName();
905
- if (!this.dualOptions.has(optionKey)) return true;
906
- const preset = this.negativeOptions.get(optionKey).presetArg;
907
- const negativeValue = preset !== void 0 ? preset : false;
908
- return option.negate === (negativeValue === value);
909
- }
910
- };
911
- /**
912
- * Convert string from kebab-case to camelCase.
913
- *
914
- * @param {string} str
915
- * @return {string}
916
- * @private
917
- */
918
- function camelcase(str) {
919
- return str.split("-").reduce((str, word) => {
920
- return str + word[0].toUpperCase() + word.slice(1);
921
- });
922
- }
923
- /**
924
- * Split the short and long flag out of something like '-m,--mixed <value>'
925
- *
926
- * @private
927
- */
928
- function splitOptionFlags(flags) {
929
- let shortFlag;
930
- let longFlag;
931
- const shortFlagExp = /^-[^-]$/;
932
- const longFlagExp = /^--[^-]/;
933
- const flagParts = flags.split(/[ |,]+/).concat("guard");
934
- if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
935
- if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
936
- if (!shortFlag && shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
937
- if (!shortFlag && longFlagExp.test(flagParts[0])) {
938
- shortFlag = longFlag;
939
- longFlag = flagParts.shift();
940
- }
941
- if (flagParts[0].startsWith("-")) {
942
- const unsupportedFlag = flagParts[0];
943
- const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
944
- if (/^-[^-][^-]/.test(unsupportedFlag)) throw new Error(`${baseError}
945
- - a short flag is a single dash and a single character
946
- - either use a single dash and a single character (for a short flag)
947
- - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
948
- if (shortFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
949
- - too many short flags`);
950
- if (longFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
951
- - too many long flags`);
952
- throw new Error(`${baseError}
953
- - unrecognised flag format`);
954
- }
955
- if (shortFlag === void 0 && longFlag === void 0) throw new Error(`option creation failed due to no flags found in '${flags}'.`);
956
- return {
957
- shortFlag,
958
- longFlag
959
- };
960
- }
961
- exports.Option = Option;
962
- exports.DualOptions = DualOptions;
963
- }));
964
- //#endregion
965
- //#region node_modules/commander/lib/suggestSimilar.js
966
- var require_suggestSimilar = /* @__PURE__ */ __commonJSMin(((exports) => {
967
- const maxDistance = 3;
968
- function editDistance(a, b) {
969
- if (Math.abs(a.length - b.length) > maxDistance) return Math.max(a.length, b.length);
970
- const d = [];
971
- for (let i = 0; i <= a.length; i++) d[i] = [i];
972
- for (let j = 0; j <= b.length; j++) d[0][j] = j;
973
- for (let j = 1; j <= b.length; j++) for (let i = 1; i <= a.length; i++) {
974
- let cost = 1;
975
- if (a[i - 1] === b[j - 1]) cost = 0;
976
- else cost = 1;
977
- d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
978
- 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);
979
- }
980
- return d[a.length][b.length];
981
- }
982
- /**
983
- * Find close matches, restricted to same number of edits.
984
- *
985
- * @param {string} word
986
- * @param {string[]} candidates
987
- * @returns {string}
988
- */
989
- function suggestSimilar(word, candidates) {
990
- if (!candidates || candidates.length === 0) return "";
991
- candidates = Array.from(new Set(candidates));
992
- const searchingOptions = word.startsWith("--");
993
- if (searchingOptions) {
994
- word = word.slice(2);
995
- candidates = candidates.map((candidate) => candidate.slice(2));
996
- }
997
- let similar = [];
998
- let bestDistance = maxDistance;
999
- const minSimilarity = .4;
1000
- candidates.forEach((candidate) => {
1001
- if (candidate.length <= 1) return;
1002
- const distance = editDistance(word, candidate);
1003
- const length = Math.max(word.length, candidate.length);
1004
- if ((length - distance) / length > minSimilarity) {
1005
- if (distance < bestDistance) {
1006
- bestDistance = distance;
1007
- similar = [candidate];
1008
- } else if (distance === bestDistance) similar.push(candidate);
1009
- }
1010
- });
1011
- similar.sort((a, b) => a.localeCompare(b));
1012
- if (searchingOptions) similar = similar.map((candidate) => `--${candidate}`);
1013
- if (similar.length > 1) return `\n(Did you mean one of ${similar.join(", ")}?)`;
1014
- if (similar.length === 1) return `\n(Did you mean ${similar[0]}?)`;
1015
- return "";
1016
- }
1017
- exports.suggestSimilar = suggestSimilar;
1018
- }));
1019
- //#endregion
1020
- //#region node_modules/commander/lib/command.js
1021
- var require_command = /* @__PURE__ */ __commonJSMin(((exports) => {
1022
- const EventEmitter = __require("node:events").EventEmitter;
1023
- const childProcess = __require("node:child_process");
1024
- const path$1 = __require("node:path");
1025
- const fs$1 = __require("node:fs");
1026
- const process$1 = __require("node:process");
1027
- const { Argument, humanReadableArgName } = require_argument();
1028
- const { CommanderError } = require_error();
1029
- const { Help, stripColor } = require_help();
1030
- const { Option, DualOptions } = require_option();
1031
- const { suggestSimilar } = require_suggestSimilar();
1032
- var Command = class Command extends EventEmitter {
1033
- /**
1034
- * Initialize a new `Command`.
1035
- *
1036
- * @param {string} [name]
1037
- */
1038
- constructor(name) {
1039
- super();
1040
- /** @type {Command[]} */
1041
- this.commands = [];
1042
- /** @type {Option[]} */
1043
- this.options = [];
1044
- this.parent = null;
1045
- this._allowUnknownOption = false;
1046
- this._allowExcessArguments = false;
1047
- /** @type {Argument[]} */
1048
- this.registeredArguments = [];
1049
- this._args = this.registeredArguments;
1050
- /** @type {string[]} */
1051
- this.args = [];
1052
- this.rawArgs = [];
1053
- this.processedArgs = [];
1054
- this._scriptPath = null;
1055
- this._name = name || "";
1056
- this._optionValues = {};
1057
- this._optionValueSources = {};
1058
- this._storeOptionsAsProperties = false;
1059
- this._actionHandler = null;
1060
- this._executableHandler = false;
1061
- this._executableFile = null;
1062
- this._executableDir = null;
1063
- this._defaultCommandName = null;
1064
- this._exitCallback = null;
1065
- this._aliases = [];
1066
- this._combineFlagAndOptionalValue = true;
1067
- this._description = "";
1068
- this._summary = "";
1069
- this._argsDescription = void 0;
1070
- this._enablePositionalOptions = false;
1071
- this._passThroughOptions = false;
1072
- this._lifeCycleHooks = {};
1073
- /** @type {(boolean | string)} */
1074
- this._showHelpAfterError = false;
1075
- this._showSuggestionAfterError = true;
1076
- this._savedState = null;
1077
- this._outputConfiguration = {
1078
- writeOut: (str) => process$1.stdout.write(str),
1079
- writeErr: (str) => process$1.stderr.write(str),
1080
- outputError: (str, write) => write(str),
1081
- getOutHelpWidth: () => process$1.stdout.isTTY ? process$1.stdout.columns : void 0,
1082
- getErrHelpWidth: () => process$1.stderr.isTTY ? process$1.stderr.columns : void 0,
1083
- getOutHasColors: () => useColor() ?? (process$1.stdout.isTTY && process$1.stdout.hasColors?.()),
1084
- getErrHasColors: () => useColor() ?? (process$1.stderr.isTTY && process$1.stderr.hasColors?.()),
1085
- stripColor: (str) => stripColor(str)
1086
- };
1087
- this._hidden = false;
1088
- /** @type {(Option | null | undefined)} */
1089
- this._helpOption = void 0;
1090
- this._addImplicitHelpCommand = void 0;
1091
- /** @type {Command} */
1092
- this._helpCommand = void 0;
1093
- this._helpConfiguration = {};
1094
- /** @type {string | undefined} */
1095
- this._helpGroupHeading = void 0;
1096
- /** @type {string | undefined} */
1097
- this._defaultCommandGroup = void 0;
1098
- /** @type {string | undefined} */
1099
- this._defaultOptionGroup = void 0;
1100
- }
1101
- /**
1102
- * Copy settings that are useful to have in common across root command and subcommands.
1103
- *
1104
- * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1105
- *
1106
- * @param {Command} sourceCommand
1107
- * @return {Command} `this` command for chaining
1108
- */
1109
- copyInheritedSettings(sourceCommand) {
1110
- this._outputConfiguration = sourceCommand._outputConfiguration;
1111
- this._helpOption = sourceCommand._helpOption;
1112
- this._helpCommand = sourceCommand._helpCommand;
1113
- this._helpConfiguration = sourceCommand._helpConfiguration;
1114
- this._exitCallback = sourceCommand._exitCallback;
1115
- this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1116
- this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1117
- this._allowExcessArguments = sourceCommand._allowExcessArguments;
1118
- this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1119
- this._showHelpAfterError = sourceCommand._showHelpAfterError;
1120
- this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1121
- return this;
1122
- }
1123
- /**
1124
- * @returns {Command[]}
1125
- * @private
1126
- */
1127
- _getCommandAndAncestors() {
1128
- const result = [];
1129
- for (let command = this; command; command = command.parent) result.push(command);
1130
- return result;
1131
- }
1132
- /**
1133
- * Define a command.
1134
- *
1135
- * There are two styles of command: pay attention to where to put the description.
1136
- *
1137
- * @example
1138
- * // Command implemented using action handler (description is supplied separately to `.command`)
1139
- * program
1140
- * .command('clone <source> [destination]')
1141
- * .description('clone a repository into a newly created directory')
1142
- * .action((source, destination) => {
1143
- * console.log('clone command called');
1144
- * });
1145
- *
1146
- * // Command implemented using separate executable file (description is second parameter to `.command`)
1147
- * program
1148
- * .command('start <service>', 'start named service')
1149
- * .command('stop [service]', 'stop named service, or all if no name supplied');
1150
- *
1151
- * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1152
- * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1153
- * @param {object} [execOpts] - configuration options (for executable)
1154
- * @return {Command} returns new command for action handler, or `this` for executable command
1155
- */
1156
- command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1157
- let desc = actionOptsOrExecDesc;
1158
- let opts = execOpts;
1159
- if (typeof desc === "object" && desc !== null) {
1160
- opts = desc;
1161
- desc = null;
1162
- }
1163
- opts = opts || {};
1164
- const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1165
- const cmd = this.createCommand(name);
1166
- if (desc) {
1167
- cmd.description(desc);
1168
- cmd._executableHandler = true;
1169
- }
1170
- if (opts.isDefault) this._defaultCommandName = cmd._name;
1171
- cmd._hidden = !!(opts.noHelp || opts.hidden);
1172
- cmd._executableFile = opts.executableFile || null;
1173
- if (args) cmd.arguments(args);
1174
- this._registerCommand(cmd);
1175
- cmd.parent = this;
1176
- cmd.copyInheritedSettings(this);
1177
- if (desc) return this;
1178
- return cmd;
1179
- }
1180
- /**
1181
- * Factory routine to create a new unattached command.
1182
- *
1183
- * See .command() for creating an attached subcommand, which uses this routine to
1184
- * create the command. You can override createCommand to customise subcommands.
1185
- *
1186
- * @param {string} [name]
1187
- * @return {Command} new command
1188
- */
1189
- createCommand(name) {
1190
- return new Command(name);
1191
- }
1192
- /**
1193
- * You can customise the help with a subclass of Help by overriding createHelp,
1194
- * or by overriding Help properties using configureHelp().
1195
- *
1196
- * @return {Help}
1197
- */
1198
- createHelp() {
1199
- return Object.assign(new Help(), this.configureHelp());
1200
- }
1201
- /**
1202
- * You can customise the help by overriding Help properties using configureHelp(),
1203
- * or with a subclass of Help by overriding createHelp().
1204
- *
1205
- * @param {object} [configuration] - configuration options
1206
- * @return {(Command | object)} `this` command for chaining, or stored configuration
1207
- */
1208
- configureHelp(configuration) {
1209
- if (configuration === void 0) return this._helpConfiguration;
1210
- this._helpConfiguration = configuration;
1211
- return this;
1212
- }
1213
- /**
1214
- * The default output goes to stdout and stderr. You can customise this for special
1215
- * applications. You can also customise the display of errors by overriding outputError.
1216
- *
1217
- * The configuration properties are all functions:
1218
- *
1219
- * // change how output being written, defaults to stdout and stderr
1220
- * writeOut(str)
1221
- * writeErr(str)
1222
- * // change how output being written for errors, defaults to writeErr
1223
- * outputError(str, write) // used for displaying errors and not used for displaying help
1224
- * // specify width for wrapping help
1225
- * getOutHelpWidth()
1226
- * getErrHelpWidth()
1227
- * // color support, currently only used with Help
1228
- * getOutHasColors()
1229
- * getErrHasColors()
1230
- * stripColor() // used to remove ANSI escape codes if output does not have colors
1231
- *
1232
- * @param {object} [configuration] - configuration options
1233
- * @return {(Command | object)} `this` command for chaining, or stored configuration
1234
- */
1235
- configureOutput(configuration) {
1236
- if (configuration === void 0) return this._outputConfiguration;
1237
- this._outputConfiguration = {
1238
- ...this._outputConfiguration,
1239
- ...configuration
1240
- };
1241
- return this;
1242
- }
1243
- /**
1244
- * Display the help or a custom message after an error occurs.
1245
- *
1246
- * @param {(boolean|string)} [displayHelp]
1247
- * @return {Command} `this` command for chaining
1248
- */
1249
- showHelpAfterError(displayHelp = true) {
1250
- if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1251
- this._showHelpAfterError = displayHelp;
1252
- return this;
1253
- }
1254
- /**
1255
- * Display suggestion of similar commands for unknown commands, or options for unknown options.
1256
- *
1257
- * @param {boolean} [displaySuggestion]
1258
- * @return {Command} `this` command for chaining
1259
- */
1260
- showSuggestionAfterError(displaySuggestion = true) {
1261
- this._showSuggestionAfterError = !!displaySuggestion;
1262
- return this;
1263
- }
1264
- /**
1265
- * Add a prepared subcommand.
1266
- *
1267
- * See .command() for creating an attached subcommand which inherits settings from its parent.
1268
- *
1269
- * @param {Command} cmd - new subcommand
1270
- * @param {object} [opts] - configuration options
1271
- * @return {Command} `this` command for chaining
1272
- */
1273
- addCommand(cmd, opts) {
1274
- if (!cmd._name) throw new Error(`Command passed to .addCommand() must have a name
1275
- - specify the name in Command constructor or using .name()`);
1276
- opts = opts || {};
1277
- if (opts.isDefault) this._defaultCommandName = cmd._name;
1278
- if (opts.noHelp || opts.hidden) cmd._hidden = true;
1279
- this._registerCommand(cmd);
1280
- cmd.parent = this;
1281
- cmd._checkForBrokenPassThrough();
1282
- return this;
1283
- }
1284
- /**
1285
- * Factory routine to create a new unattached argument.
1286
- *
1287
- * See .argument() for creating an attached argument, which uses this routine to
1288
- * create the argument. You can override createArgument to return a custom argument.
1289
- *
1290
- * @param {string} name
1291
- * @param {string} [description]
1292
- * @return {Argument} new argument
1293
- */
1294
- createArgument(name, description) {
1295
- return new Argument(name, description);
1296
- }
1297
- /**
1298
- * Define argument syntax for command.
1299
- *
1300
- * The default is that the argument is required, and you can explicitly
1301
- * indicate this with <> around the name. Put [] around the name for an optional argument.
1302
- *
1303
- * @example
1304
- * program.argument('<input-file>');
1305
- * program.argument('[output-file]');
1306
- *
1307
- * @param {string} name
1308
- * @param {string} [description]
1309
- * @param {(Function|*)} [parseArg] - custom argument processing function or default value
1310
- * @param {*} [defaultValue]
1311
- * @return {Command} `this` command for chaining
1312
- */
1313
- argument(name, description, parseArg, defaultValue) {
1314
- const argument = this.createArgument(name, description);
1315
- if (typeof parseArg === "function") argument.default(defaultValue).argParser(parseArg);
1316
- else argument.default(parseArg);
1317
- this.addArgument(argument);
1318
- return this;
1319
- }
1320
- /**
1321
- * Define argument syntax for command, adding multiple at once (without descriptions).
1322
- *
1323
- * See also .argument().
1324
- *
1325
- * @example
1326
- * program.arguments('<cmd> [env]');
1327
- *
1328
- * @param {string} names
1329
- * @return {Command} `this` command for chaining
1330
- */
1331
- arguments(names) {
1332
- names.trim().split(/ +/).forEach((detail) => {
1333
- this.argument(detail);
1334
- });
1335
- return this;
1336
- }
1337
- /**
1338
- * Define argument syntax for command, adding a prepared argument.
1339
- *
1340
- * @param {Argument} argument
1341
- * @return {Command} `this` command for chaining
1342
- */
1343
- addArgument(argument) {
1344
- const previousArgument = this.registeredArguments.slice(-1)[0];
1345
- if (previousArgument?.variadic) throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
1346
- 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()}'`);
1347
- this.registeredArguments.push(argument);
1348
- return this;
1349
- }
1350
- /**
1351
- * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1352
- *
1353
- * @example
1354
- * program.helpCommand('help [cmd]');
1355
- * program.helpCommand('help [cmd]', 'show help');
1356
- * program.helpCommand(false); // suppress default help command
1357
- * program.helpCommand(true); // add help command even if no subcommands
1358
- *
1359
- * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1360
- * @param {string} [description] - custom description
1361
- * @return {Command} `this` command for chaining
1362
- */
1363
- helpCommand(enableOrNameAndArgs, description) {
1364
- if (typeof enableOrNameAndArgs === "boolean") {
1365
- this._addImplicitHelpCommand = enableOrNameAndArgs;
1366
- if (enableOrNameAndArgs && this._defaultCommandGroup) this._initCommandGroup(this._getHelpCommand());
1367
- return this;
1368
- }
1369
- const [, helpName, helpArgs] = (enableOrNameAndArgs ?? "help [command]").match(/([^ ]+) *(.*)/);
1370
- const helpDescription = description ?? "display help for command";
1371
- const helpCommand = this.createCommand(helpName);
1372
- helpCommand.helpOption(false);
1373
- if (helpArgs) helpCommand.arguments(helpArgs);
1374
- if (helpDescription) helpCommand.description(helpDescription);
1375
- this._addImplicitHelpCommand = true;
1376
- this._helpCommand = helpCommand;
1377
- if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
1378
- return this;
1379
- }
1380
- /**
1381
- * Add prepared custom help command.
1382
- *
1383
- * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1384
- * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1385
- * @return {Command} `this` command for chaining
1386
- */
1387
- addHelpCommand(helpCommand, deprecatedDescription) {
1388
- if (typeof helpCommand !== "object") {
1389
- this.helpCommand(helpCommand, deprecatedDescription);
1390
- return this;
1391
- }
1392
- this._addImplicitHelpCommand = true;
1393
- this._helpCommand = helpCommand;
1394
- this._initCommandGroup(helpCommand);
1395
- return this;
1396
- }
1397
- /**
1398
- * Lazy create help command.
1399
- *
1400
- * @return {(Command|null)}
1401
- * @package
1402
- */
1403
- _getHelpCommand() {
1404
- if (this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"))) {
1405
- if (this._helpCommand === void 0) this.helpCommand(void 0, void 0);
1406
- return this._helpCommand;
1407
- }
1408
- return null;
1409
- }
1410
- /**
1411
- * Add hook for life cycle event.
1412
- *
1413
- * @param {string} event
1414
- * @param {Function} listener
1415
- * @return {Command} `this` command for chaining
1416
- */
1417
- hook(event, listener) {
1418
- const allowedValues = [
1419
- "preSubcommand",
1420
- "preAction",
1421
- "postAction"
1422
- ];
1423
- if (!allowedValues.includes(event)) throw new Error(`Unexpected value for event passed to hook : '${event}'.
1424
- Expecting one of '${allowedValues.join("', '")}'`);
1425
- if (this._lifeCycleHooks[event]) this._lifeCycleHooks[event].push(listener);
1426
- else this._lifeCycleHooks[event] = [listener];
1427
- return this;
1428
- }
1429
- /**
1430
- * Register callback to use as replacement for calling process.exit.
1431
- *
1432
- * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1433
- * @return {Command} `this` command for chaining
1434
- */
1435
- exitOverride(fn) {
1436
- if (fn) this._exitCallback = fn;
1437
- else this._exitCallback = (err) => {
1438
- if (err.code !== "commander.executeSubCommandAsync") throw err;
1439
- };
1440
- return this;
1441
- }
1442
- /**
1443
- * Call process.exit, and _exitCallback if defined.
1444
- *
1445
- * @param {number} exitCode exit code for using with process.exit
1446
- * @param {string} code an id string representing the error
1447
- * @param {string} message human-readable description of the error
1448
- * @return never
1449
- * @private
1450
- */
1451
- _exit(exitCode, code, message) {
1452
- if (this._exitCallback) this._exitCallback(new CommanderError(exitCode, code, message));
1453
- process$1.exit(exitCode);
1454
- }
1455
- /**
1456
- * Register callback `fn` for the command.
1457
- *
1458
- * @example
1459
- * program
1460
- * .command('serve')
1461
- * .description('start service')
1462
- * .action(function() {
1463
- * // do work here
1464
- * });
1465
- *
1466
- * @param {Function} fn
1467
- * @return {Command} `this` command for chaining
1468
- */
1469
- action(fn) {
1470
- const listener = (args) => {
1471
- const expectedArgsCount = this.registeredArguments.length;
1472
- const actionArgs = args.slice(0, expectedArgsCount);
1473
- if (this._storeOptionsAsProperties) actionArgs[expectedArgsCount] = this;
1474
- else actionArgs[expectedArgsCount] = this.opts();
1475
- actionArgs.push(this);
1476
- return fn.apply(this, actionArgs);
1477
- };
1478
- this._actionHandler = listener;
1479
- return this;
1480
- }
1481
- /**
1482
- * Factory routine to create a new unattached option.
1483
- *
1484
- * See .option() for creating an attached option, which uses this routine to
1485
- * create the option. You can override createOption to return a custom option.
1486
- *
1487
- * @param {string} flags
1488
- * @param {string} [description]
1489
- * @return {Option} new option
1490
- */
1491
- createOption(flags, description) {
1492
- return new Option(flags, description);
1493
- }
1494
- /**
1495
- * Wrap parseArgs to catch 'commander.invalidArgument'.
1496
- *
1497
- * @param {(Option | Argument)} target
1498
- * @param {string} value
1499
- * @param {*} previous
1500
- * @param {string} invalidArgumentMessage
1501
- * @private
1502
- */
1503
- _callParseArg(target, value, previous, invalidArgumentMessage) {
1504
- try {
1505
- return target.parseArg(value, previous);
1506
- } catch (err) {
1507
- if (err.code === "commander.invalidArgument") {
1508
- const message = `${invalidArgumentMessage} ${err.message}`;
1509
- this.error(message, {
1510
- exitCode: err.exitCode,
1511
- code: err.code
1512
- });
1513
- }
1514
- throw err;
1515
- }
1516
- }
1517
- /**
1518
- * Check for option flag conflicts.
1519
- * Register option if no conflicts found, or throw on conflict.
1520
- *
1521
- * @param {Option} option
1522
- * @private
1523
- */
1524
- _registerOption(option) {
1525
- const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1526
- if (matchingOption) {
1527
- const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1528
- throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1529
- - already used by option '${matchingOption.flags}'`);
1530
- }
1531
- this._initOptionGroup(option);
1532
- this.options.push(option);
1533
- }
1534
- /**
1535
- * Check for command name and alias conflicts with existing commands.
1536
- * Register command if no conflicts found, or throw on conflict.
1537
- *
1538
- * @param {Command} command
1539
- * @private
1540
- */
1541
- _registerCommand(command) {
1542
- const knownBy = (cmd) => {
1543
- return [cmd.name()].concat(cmd.aliases());
1544
- };
1545
- const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
1546
- if (alreadyUsed) {
1547
- const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1548
- const newCmd = knownBy(command).join("|");
1549
- throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
1550
- }
1551
- this._initCommandGroup(command);
1552
- this.commands.push(command);
1553
- }
1554
- /**
1555
- * Add an option.
1556
- *
1557
- * @param {Option} option
1558
- * @return {Command} `this` command for chaining
1559
- */
1560
- addOption(option) {
1561
- this._registerOption(option);
1562
- const oname = option.name();
1563
- const name = option.attributeName();
1564
- if (option.negate) {
1565
- const positiveLongFlag = option.long.replace(/^--no-/, "--");
1566
- if (!this._findOption(positiveLongFlag)) this.setOptionValueWithSource(name, option.defaultValue === void 0 ? true : option.defaultValue, "default");
1567
- } else if (option.defaultValue !== void 0) this.setOptionValueWithSource(name, option.defaultValue, "default");
1568
- const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1569
- if (val == null && option.presetArg !== void 0) val = option.presetArg;
1570
- const oldValue = this.getOptionValue(name);
1571
- if (val !== null && option.parseArg) val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1572
- else if (val !== null && option.variadic) val = option._collectValue(val, oldValue);
1573
- if (val == null) if (option.negate) val = false;
1574
- else if (option.isBoolean() || option.optional) val = true;
1575
- else val = "";
1576
- this.setOptionValueWithSource(name, val, valueSource);
1577
- };
1578
- this.on("option:" + oname, (val) => {
1579
- handleOptionValue(val, `error: option '${option.flags}' argument '${val}' is invalid.`, "cli");
1580
- });
1581
- if (option.envVar) this.on("optionEnv:" + oname, (val) => {
1582
- handleOptionValue(val, `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`, "env");
1583
- });
1584
- return this;
1585
- }
1586
- /**
1587
- * Internal implementation shared by .option() and .requiredOption()
1588
- *
1589
- * @return {Command} `this` command for chaining
1590
- * @private
1591
- */
1592
- _optionEx(config, flags, description, fn, defaultValue) {
1593
- if (typeof flags === "object" && flags instanceof Option) throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
1594
- const option = this.createOption(flags, description);
1595
- option.makeOptionMandatory(!!config.mandatory);
1596
- if (typeof fn === "function") option.default(defaultValue).argParser(fn);
1597
- else if (fn instanceof RegExp) {
1598
- const regex = fn;
1599
- fn = (val, def) => {
1600
- const m = regex.exec(val);
1601
- return m ? m[0] : def;
1602
- };
1603
- option.default(defaultValue).argParser(fn);
1604
- } else option.default(fn);
1605
- return this.addOption(option);
1606
- }
1607
- /**
1608
- * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1609
- *
1610
- * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1611
- * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1612
- *
1613
- * See the README for more details, and see also addOption() and requiredOption().
1614
- *
1615
- * @example
1616
- * program
1617
- * .option('-p, --pepper', 'add pepper')
1618
- * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1619
- * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1620
- * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1621
- *
1622
- * @param {string} flags
1623
- * @param {string} [description]
1624
- * @param {(Function|*)} [parseArg] - custom option processing function or default value
1625
- * @param {*} [defaultValue]
1626
- * @return {Command} `this` command for chaining
1627
- */
1628
- option(flags, description, parseArg, defaultValue) {
1629
- return this._optionEx({}, flags, description, parseArg, defaultValue);
1630
- }
1631
- /**
1632
- * Add a required option which must have a value after parsing. This usually means
1633
- * the option must be specified on the command line. (Otherwise the same as .option().)
1634
- *
1635
- * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1636
- *
1637
- * @param {string} flags
1638
- * @param {string} [description]
1639
- * @param {(Function|*)} [parseArg] - custom option processing function or default value
1640
- * @param {*} [defaultValue]
1641
- * @return {Command} `this` command for chaining
1642
- */
1643
- requiredOption(flags, description, parseArg, defaultValue) {
1644
- return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
1645
- }
1646
- /**
1647
- * Alter parsing of short flags with optional values.
1648
- *
1649
- * @example
1650
- * // for `.option('-f,--flag [value]'):
1651
- * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1652
- * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1653
- *
1654
- * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
1655
- * @return {Command} `this` command for chaining
1656
- */
1657
- combineFlagAndOptionalValue(combine = true) {
1658
- this._combineFlagAndOptionalValue = !!combine;
1659
- return this;
1660
- }
1661
- /**
1662
- * Allow unknown options on the command line.
1663
- *
1664
- * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
1665
- * @return {Command} `this` command for chaining
1666
- */
1667
- allowUnknownOption(allowUnknown = true) {
1668
- this._allowUnknownOption = !!allowUnknown;
1669
- return this;
1670
- }
1671
- /**
1672
- * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1673
- *
1674
- * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
1675
- * @return {Command} `this` command for chaining
1676
- */
1677
- allowExcessArguments(allowExcess = true) {
1678
- this._allowExcessArguments = !!allowExcess;
1679
- return this;
1680
- }
1681
- /**
1682
- * Enable positional options. Positional means global options are specified before subcommands which lets
1683
- * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1684
- * The default behaviour is non-positional and global options may appear anywhere on the command line.
1685
- *
1686
- * @param {boolean} [positional]
1687
- * @return {Command} `this` command for chaining
1688
- */
1689
- enablePositionalOptions(positional = true) {
1690
- this._enablePositionalOptions = !!positional;
1691
- return this;
1692
- }
1693
- /**
1694
- * Pass through options that come after command-arguments rather than treat them as command-options,
1695
- * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1696
- * positional options to have been enabled on the program (parent commands).
1697
- * The default behaviour is non-positional and options may appear before or after command-arguments.
1698
- *
1699
- * @param {boolean} [passThrough] for unknown options.
1700
- * @return {Command} `this` command for chaining
1701
- */
1702
- passThroughOptions(passThrough = true) {
1703
- this._passThroughOptions = !!passThrough;
1704
- this._checkForBrokenPassThrough();
1705
- return this;
1706
- }
1707
- /**
1708
- * @private
1709
- */
1710
- _checkForBrokenPassThrough() {
1711
- 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)`);
1712
- }
1713
- /**
1714
- * Whether to store option values as properties on command object,
1715
- * or store separately (specify false). In both cases the option values can be accessed using .opts().
1716
- *
1717
- * @param {boolean} [storeAsProperties=true]
1718
- * @return {Command} `this` command for chaining
1719
- */
1720
- storeOptionsAsProperties(storeAsProperties = true) {
1721
- if (this.options.length) throw new Error("call .storeOptionsAsProperties() before adding options");
1722
- if (Object.keys(this._optionValues).length) throw new Error("call .storeOptionsAsProperties() before setting option values");
1723
- this._storeOptionsAsProperties = !!storeAsProperties;
1724
- return this;
1725
- }
1726
- /**
1727
- * Retrieve option value.
1728
- *
1729
- * @param {string} key
1730
- * @return {object} value
1731
- */
1732
- getOptionValue(key) {
1733
- if (this._storeOptionsAsProperties) return this[key];
1734
- return this._optionValues[key];
1735
- }
1736
- /**
1737
- * Store option value.
1738
- *
1739
- * @param {string} key
1740
- * @param {object} value
1741
- * @return {Command} `this` command for chaining
1742
- */
1743
- setOptionValue(key, value) {
1744
- return this.setOptionValueWithSource(key, value, void 0);
1745
- }
1746
- /**
1747
- * Store option value and where the value came from.
1748
- *
1749
- * @param {string} key
1750
- * @param {object} value
1751
- * @param {string} source - expected values are default/config/env/cli/implied
1752
- * @return {Command} `this` command for chaining
1753
- */
1754
- setOptionValueWithSource(key, value, source) {
1755
- if (this._storeOptionsAsProperties) this[key] = value;
1756
- else this._optionValues[key] = value;
1757
- this._optionValueSources[key] = source;
1758
- return this;
1759
- }
1760
- /**
1761
- * Get source of option value.
1762
- * Expected values are default | config | env | cli | implied
1763
- *
1764
- * @param {string} key
1765
- * @return {string}
1766
- */
1767
- getOptionValueSource(key) {
1768
- return this._optionValueSources[key];
1769
- }
1770
- /**
1771
- * Get source of option value. See also .optsWithGlobals().
1772
- * Expected values are default | config | env | cli | implied
1773
- *
1774
- * @param {string} key
1775
- * @return {string}
1776
- */
1777
- getOptionValueSourceWithGlobals(key) {
1778
- let source;
1779
- this._getCommandAndAncestors().forEach((cmd) => {
1780
- if (cmd.getOptionValueSource(key) !== void 0) source = cmd.getOptionValueSource(key);
1781
- });
1782
- return source;
1783
- }
1784
- /**
1785
- * Get user arguments from implied or explicit arguments.
1786
- * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
1787
- *
1788
- * @private
1789
- */
1790
- _prepareUserArgs(argv, parseOptions) {
1791
- if (argv !== void 0 && !Array.isArray(argv)) throw new Error("first parameter to parse must be array or undefined");
1792
- parseOptions = parseOptions || {};
1793
- if (argv === void 0 && parseOptions.from === void 0) {
1794
- if (process$1.versions?.electron) parseOptions.from = "electron";
1795
- const execArgv = process$1.execArgv ?? [];
1796
- if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) parseOptions.from = "eval";
1797
- }
1798
- if (argv === void 0) argv = process$1.argv;
1799
- this.rawArgs = argv.slice();
1800
- let userArgs;
1801
- switch (parseOptions.from) {
1802
- case void 0:
1803
- case "node":
1804
- this._scriptPath = argv[1];
1805
- userArgs = argv.slice(2);
1806
- break;
1807
- case "electron":
1808
- if (process$1.defaultApp) {
1809
- this._scriptPath = argv[1];
1810
- userArgs = argv.slice(2);
1811
- } else userArgs = argv.slice(1);
1812
- break;
1813
- case "user":
1814
- userArgs = argv.slice(0);
1815
- break;
1816
- case "eval":
1817
- userArgs = argv.slice(1);
1818
- break;
1819
- default: throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1820
- }
1821
- if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);
1822
- this._name = this._name || "program";
1823
- return userArgs;
1824
- }
1825
- /**
1826
- * Parse `argv`, setting options and invoking commands when defined.
1827
- *
1828
- * Use parseAsync instead of parse if any of your action handlers are async.
1829
- *
1830
- * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1831
- *
1832
- * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1833
- * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1834
- * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1835
- * - `'user'`: just user arguments
1836
- *
1837
- * @example
1838
- * program.parse(); // parse process.argv and auto-detect electron and special node flags
1839
- * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
1840
- * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1841
- *
1842
- * @param {string[]} [argv] - optional, defaults to process.argv
1843
- * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
1844
- * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
1845
- * @return {Command} `this` command for chaining
1846
- */
1847
- parse(argv, parseOptions) {
1848
- this._prepareForParse();
1849
- const userArgs = this._prepareUserArgs(argv, parseOptions);
1850
- this._parseCommand([], userArgs);
1851
- return this;
1852
- }
1853
- /**
1854
- * Parse `argv`, setting options and invoking commands when defined.
1855
- *
1856
- * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1857
- *
1858
- * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1859
- * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1860
- * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1861
- * - `'user'`: just user arguments
1862
- *
1863
- * @example
1864
- * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
1865
- * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
1866
- * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1867
- *
1868
- * @param {string[]} [argv]
1869
- * @param {object} [parseOptions]
1870
- * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
1871
- * @return {Promise}
1872
- */
1873
- async parseAsync(argv, parseOptions) {
1874
- this._prepareForParse();
1875
- const userArgs = this._prepareUserArgs(argv, parseOptions);
1876
- await this._parseCommand([], userArgs);
1877
- return this;
1878
- }
1879
- _prepareForParse() {
1880
- if (this._savedState === null) this.saveStateBeforeParse();
1881
- else this.restoreStateBeforeParse();
1882
- }
1883
- /**
1884
- * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
1885
- * Not usually called directly, but available for subclasses to save their custom state.
1886
- *
1887
- * This is called in a lazy way. Only commands used in parsing chain will have state saved.
1888
- */
1889
- saveStateBeforeParse() {
1890
- this._savedState = {
1891
- _name: this._name,
1892
- _optionValues: { ...this._optionValues },
1893
- _optionValueSources: { ...this._optionValueSources }
1894
- };
1895
- }
1896
- /**
1897
- * Restore state before parse for calls after the first.
1898
- * Not usually called directly, but available for subclasses to save their custom state.
1899
- *
1900
- * This is called in a lazy way. Only commands used in parsing chain will have state restored.
1901
- */
1902
- restoreStateBeforeParse() {
1903
- if (this._storeOptionsAsProperties) throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
1904
- - either make a new Command for each call to parse, or stop storing options as properties`);
1905
- this._name = this._savedState._name;
1906
- this._scriptPath = null;
1907
- this.rawArgs = [];
1908
- this._optionValues = { ...this._savedState._optionValues };
1909
- this._optionValueSources = { ...this._savedState._optionValueSources };
1910
- this.args = [];
1911
- this.processedArgs = [];
1912
- }
1913
- /**
1914
- * Throw if expected executable is missing. Add lots of help for author.
1915
- *
1916
- * @param {string} executableFile
1917
- * @param {string} executableDir
1918
- * @param {string} subcommandName
1919
- */
1920
- _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
1921
- if (fs$1.existsSync(executableFile)) return;
1922
- const executableMissing = `'${executableFile}' does not exist
1923
- - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1924
- - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1925
- - ${executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory"}`;
1926
- throw new Error(executableMissing);
1927
- }
1928
- /**
1929
- * Execute a sub-command executable.
1930
- *
1931
- * @private
1932
- */
1933
- _executeSubCommand(subcommand, args) {
1934
- args = args.slice();
1935
- let launchWithNode = false;
1936
- const sourceExt = [
1937
- ".js",
1938
- ".ts",
1939
- ".tsx",
1940
- ".mjs",
1941
- ".cjs"
1942
- ];
1943
- function findFile(baseDir, baseName) {
1944
- const localBin = path$1.resolve(baseDir, baseName);
1945
- if (fs$1.existsSync(localBin)) return localBin;
1946
- if (sourceExt.includes(path$1.extname(baseName))) return void 0;
1947
- const foundExt = sourceExt.find((ext) => fs$1.existsSync(`${localBin}${ext}`));
1948
- if (foundExt) return `${localBin}${foundExt}`;
1949
- }
1950
- this._checkForMissingMandatoryOptions();
1951
- this._checkForConflictingOptions();
1952
- let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1953
- let executableDir = this._executableDir || "";
1954
- if (this._scriptPath) {
1955
- let resolvedScriptPath;
1956
- try {
1957
- resolvedScriptPath = fs$1.realpathSync(this._scriptPath);
1958
- } catch {
1959
- resolvedScriptPath = this._scriptPath;
1960
- }
1961
- executableDir = path$1.resolve(path$1.dirname(resolvedScriptPath), executableDir);
1962
- }
1963
- if (executableDir) {
1964
- let localFile = findFile(executableDir, executableFile);
1965
- if (!localFile && !subcommand._executableFile && this._scriptPath) {
1966
- const legacyName = path$1.basename(this._scriptPath, path$1.extname(this._scriptPath));
1967
- if (legacyName !== this._name) localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1968
- }
1969
- executableFile = localFile || executableFile;
1970
- }
1971
- launchWithNode = sourceExt.includes(path$1.extname(executableFile));
1972
- let proc;
1973
- if (process$1.platform !== "win32") if (launchWithNode) {
1974
- args.unshift(executableFile);
1975
- args = incrementNodeInspectorPort(process$1.execArgv).concat(args);
1976
- proc = childProcess.spawn(process$1.argv[0], args, { stdio: "inherit" });
1977
- } else proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1978
- else {
1979
- this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1980
- args.unshift(executableFile);
1981
- args = incrementNodeInspectorPort(process$1.execArgv).concat(args);
1982
- proc = childProcess.spawn(process$1.execPath, args, { stdio: "inherit" });
1983
- }
1984
- if (!proc.killed) [
1985
- "SIGUSR1",
1986
- "SIGUSR2",
1987
- "SIGTERM",
1988
- "SIGINT",
1989
- "SIGHUP"
1990
- ].forEach((signal) => {
1991
- process$1.on(signal, () => {
1992
- if (proc.killed === false && proc.exitCode === null) proc.kill(signal);
1993
- });
1994
- });
1995
- const exitCallback = this._exitCallback;
1996
- proc.on("close", (code) => {
1997
- code = code ?? 1;
1998
- if (!exitCallback) process$1.exit(code);
1999
- else exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
2000
- });
2001
- proc.on("error", (err) => {
2002
- if (err.code === "ENOENT") this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
2003
- else if (err.code === "EACCES") throw new Error(`'${executableFile}' not executable`);
2004
- if (!exitCallback) process$1.exit(1);
2005
- else {
2006
- const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
2007
- wrappedError.nestedError = err;
2008
- exitCallback(wrappedError);
2009
- }
2010
- });
2011
- this.runningCommand = proc;
2012
- }
2013
- /**
2014
- * @private
2015
- */
2016
- _dispatchSubcommand(commandName, operands, unknown) {
2017
- const subCommand = this._findCommand(commandName);
2018
- if (!subCommand) this.help({ error: true });
2019
- subCommand._prepareForParse();
2020
- let promiseChain;
2021
- promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
2022
- promiseChain = this._chainOrCall(promiseChain, () => {
2023
- if (subCommand._executableHandler) this._executeSubCommand(subCommand, operands.concat(unknown));
2024
- else return subCommand._parseCommand(operands, unknown);
2025
- });
2026
- return promiseChain;
2027
- }
2028
- /**
2029
- * Invoke help directly if possible, or dispatch if necessary.
2030
- * e.g. help foo
2031
- *
2032
- * @private
2033
- */
2034
- _dispatchHelpCommand(subcommandName) {
2035
- if (!subcommandName) this.help();
2036
- const subCommand = this._findCommand(subcommandName);
2037
- if (subCommand && !subCommand._executableHandler) subCommand.help();
2038
- return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
2039
- }
2040
- /**
2041
- * Check this.args against expected this.registeredArguments.
2042
- *
2043
- * @private
2044
- */
2045
- _checkNumberOfArguments() {
2046
- this.registeredArguments.forEach((arg, i) => {
2047
- if (arg.required && this.args[i] == null) this.missingArgument(arg.name());
2048
- });
2049
- if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) return;
2050
- if (this.args.length > this.registeredArguments.length) this._excessArguments(this.args);
2051
- }
2052
- /**
2053
- * Process this.args using this.registeredArguments and save as this.processedArgs!
2054
- *
2055
- * @private
2056
- */
2057
- _processArguments() {
2058
- const myParseArg = (argument, value, previous) => {
2059
- let parsedValue = value;
2060
- if (value !== null && argument.parseArg) {
2061
- const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2062
- parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
2063
- }
2064
- return parsedValue;
2065
- };
2066
- this._checkNumberOfArguments();
2067
- const processedArgs = [];
2068
- this.registeredArguments.forEach((declaredArg, index) => {
2069
- let value = declaredArg.defaultValue;
2070
- if (declaredArg.variadic) {
2071
- if (index < this.args.length) {
2072
- value = this.args.slice(index);
2073
- if (declaredArg.parseArg) value = value.reduce((processed, v) => {
2074
- return myParseArg(declaredArg, v, processed);
2075
- }, declaredArg.defaultValue);
2076
- } else if (value === void 0) value = [];
2077
- } else if (index < this.args.length) {
2078
- value = this.args[index];
2079
- if (declaredArg.parseArg) value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2080
- }
2081
- processedArgs[index] = value;
2082
- });
2083
- this.processedArgs = processedArgs;
2084
- }
2085
- /**
2086
- * Once we have a promise we chain, but call synchronously until then.
2087
- *
2088
- * @param {(Promise|undefined)} promise
2089
- * @param {Function} fn
2090
- * @return {(Promise|undefined)}
2091
- * @private
2092
- */
2093
- _chainOrCall(promise, fn) {
2094
- if (promise?.then && typeof promise.then === "function") return promise.then(() => fn());
2095
- return fn();
2096
- }
2097
- /**
2098
- *
2099
- * @param {(Promise|undefined)} promise
2100
- * @param {string} event
2101
- * @return {(Promise|undefined)}
2102
- * @private
2103
- */
2104
- _chainOrCallHooks(promise, event) {
2105
- let result = promise;
2106
- const hooks = [];
2107
- this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
2108
- hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2109
- hooks.push({
2110
- hookedCommand,
2111
- callback
2112
- });
2113
- });
2114
- });
2115
- if (event === "postAction") hooks.reverse();
2116
- hooks.forEach((hookDetail) => {
2117
- result = this._chainOrCall(result, () => {
2118
- return hookDetail.callback(hookDetail.hookedCommand, this);
2119
- });
2120
- });
2121
- return result;
2122
- }
2123
- /**
2124
- *
2125
- * @param {(Promise|undefined)} promise
2126
- * @param {Command} subCommand
2127
- * @param {string} event
2128
- * @return {(Promise|undefined)}
2129
- * @private
2130
- */
2131
- _chainOrCallSubCommandHook(promise, subCommand, event) {
2132
- let result = promise;
2133
- if (this._lifeCycleHooks[event] !== void 0) this._lifeCycleHooks[event].forEach((hook) => {
2134
- result = this._chainOrCall(result, () => {
2135
- return hook(this, subCommand);
2136
- });
2137
- });
2138
- return result;
2139
- }
2140
- /**
2141
- * Process arguments in context of this command.
2142
- * Returns action result, in case it is a promise.
2143
- *
2144
- * @private
2145
- */
2146
- _parseCommand(operands, unknown) {
2147
- const parsed = this.parseOptions(unknown);
2148
- this._parseOptionsEnv();
2149
- this._parseOptionsImplied();
2150
- operands = operands.concat(parsed.operands);
2151
- unknown = parsed.unknown;
2152
- this.args = operands.concat(unknown);
2153
- if (operands && this._findCommand(operands[0])) return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2154
- if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) return this._dispatchHelpCommand(operands[1]);
2155
- if (this._defaultCommandName) {
2156
- this._outputHelpIfRequested(unknown);
2157
- return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
2158
- }
2159
- if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) this.help({ error: true });
2160
- this._outputHelpIfRequested(parsed.unknown);
2161
- this._checkForMissingMandatoryOptions();
2162
- this._checkForConflictingOptions();
2163
- const checkForUnknownOptions = () => {
2164
- if (parsed.unknown.length > 0) this.unknownOption(parsed.unknown[0]);
2165
- };
2166
- const commandEvent = `command:${this.name()}`;
2167
- if (this._actionHandler) {
2168
- checkForUnknownOptions();
2169
- this._processArguments();
2170
- let promiseChain;
2171
- promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2172
- promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
2173
- if (this.parent) promiseChain = this._chainOrCall(promiseChain, () => {
2174
- this.parent.emit(commandEvent, operands, unknown);
2175
- });
2176
- promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2177
- return promiseChain;
2178
- }
2179
- if (this.parent?.listenerCount(commandEvent)) {
2180
- checkForUnknownOptions();
2181
- this._processArguments();
2182
- this.parent.emit(commandEvent, operands, unknown);
2183
- } else if (operands.length) {
2184
- if (this._findCommand("*")) return this._dispatchSubcommand("*", operands, unknown);
2185
- if (this.listenerCount("command:*")) this.emit("command:*", operands, unknown);
2186
- else if (this.commands.length) this.unknownCommand();
2187
- else {
2188
- checkForUnknownOptions();
2189
- this._processArguments();
2190
- }
2191
- } else if (this.commands.length) {
2192
- checkForUnknownOptions();
2193
- this.help({ error: true });
2194
- } else {
2195
- checkForUnknownOptions();
2196
- this._processArguments();
2197
- }
2198
- }
2199
- /**
2200
- * Find matching command.
2201
- *
2202
- * @private
2203
- * @return {Command | undefined}
2204
- */
2205
- _findCommand(name) {
2206
- if (!name) return void 0;
2207
- return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
2208
- }
2209
- /**
2210
- * Return an option matching `arg` if any.
2211
- *
2212
- * @param {string} arg
2213
- * @return {Option}
2214
- * @package
2215
- */
2216
- _findOption(arg) {
2217
- return this.options.find((option) => option.is(arg));
2218
- }
2219
- /**
2220
- * Display an error message if a mandatory option does not have a value.
2221
- * Called after checking for help flags in leaf subcommand.
2222
- *
2223
- * @private
2224
- */
2225
- _checkForMissingMandatoryOptions() {
2226
- this._getCommandAndAncestors().forEach((cmd) => {
2227
- cmd.options.forEach((anOption) => {
2228
- if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) cmd.missingMandatoryOptionValue(anOption);
2229
- });
2230
- });
2231
- }
2232
- /**
2233
- * Display an error message if conflicting options are used together in this.
2234
- *
2235
- * @private
2236
- */
2237
- _checkForConflictingLocalOptions() {
2238
- const definedNonDefaultOptions = this.options.filter((option) => {
2239
- const optionKey = option.attributeName();
2240
- if (this.getOptionValue(optionKey) === void 0) return false;
2241
- return this.getOptionValueSource(optionKey) !== "default";
2242
- });
2243
- definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0).forEach((option) => {
2244
- const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
2245
- if (conflictingAndDefined) this._conflictingOption(option, conflictingAndDefined);
2246
- });
2247
- }
2248
- /**
2249
- * Display an error message if conflicting options are used together.
2250
- * Called after checking for help flags in leaf subcommand.
2251
- *
2252
- * @private
2253
- */
2254
- _checkForConflictingOptions() {
2255
- this._getCommandAndAncestors().forEach((cmd) => {
2256
- cmd._checkForConflictingLocalOptions();
2257
- });
2258
- }
2259
- /**
2260
- * Parse options from `argv` removing known options,
2261
- * and return argv split into operands and unknown arguments.
2262
- *
2263
- * Side effects: modifies command by storing options. Does not reset state if called again.
2264
- *
2265
- * Examples:
2266
- *
2267
- * argv => operands, unknown
2268
- * --known kkk op => [op], []
2269
- * op --known kkk => [op], []
2270
- * sub --unknown uuu op => [sub], [--unknown uuu op]
2271
- * sub -- --unknown uuu op => [sub --unknown uuu op], []
2272
- *
2273
- * @param {string[]} args
2274
- * @return {{operands: string[], unknown: string[]}}
2275
- */
2276
- parseOptions(args) {
2277
- const operands = [];
2278
- const unknown = [];
2279
- let dest = operands;
2280
- function maybeOption(arg) {
2281
- return arg.length > 1 && arg[0] === "-";
2282
- }
2283
- const negativeNumberArg = (arg) => {
2284
- if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
2285
- return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short)));
2286
- };
2287
- let activeVariadicOption = null;
2288
- let activeGroup = null;
2289
- let i = 0;
2290
- while (i < args.length || activeGroup) {
2291
- const arg = activeGroup ?? args[i++];
2292
- activeGroup = null;
2293
- if (arg === "--") {
2294
- if (dest === unknown) dest.push(arg);
2295
- dest.push(...args.slice(i));
2296
- break;
2297
- }
2298
- if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
2299
- this.emit(`option:${activeVariadicOption.name()}`, arg);
2300
- continue;
2301
- }
2302
- activeVariadicOption = null;
2303
- if (maybeOption(arg)) {
2304
- const option = this._findOption(arg);
2305
- if (option) {
2306
- if (option.required) {
2307
- const value = args[i++];
2308
- if (value === void 0) this.optionMissingArgument(option);
2309
- this.emit(`option:${option.name()}`, value);
2310
- } else if (option.optional) {
2311
- let value = null;
2312
- if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) value = args[i++];
2313
- this.emit(`option:${option.name()}`, value);
2314
- } else this.emit(`option:${option.name()}`);
2315
- activeVariadicOption = option.variadic ? option : null;
2316
- continue;
2317
- }
2318
- }
2319
- if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2320
- const option = this._findOption(`-${arg[1]}`);
2321
- if (option) {
2322
- if (option.required || option.optional && this._combineFlagAndOptionalValue) this.emit(`option:${option.name()}`, arg.slice(2));
2323
- else {
2324
- this.emit(`option:${option.name()}`);
2325
- activeGroup = `-${arg.slice(2)}`;
2326
- }
2327
- continue;
2328
- }
2329
- }
2330
- if (/^--[^=]+=/.test(arg)) {
2331
- const index = arg.indexOf("=");
2332
- const option = this._findOption(arg.slice(0, index));
2333
- if (option && (option.required || option.optional)) {
2334
- this.emit(`option:${option.name()}`, arg.slice(index + 1));
2335
- continue;
2336
- }
2337
- }
2338
- if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) dest = unknown;
2339
- if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2340
- if (this._findCommand(arg)) {
2341
- operands.push(arg);
2342
- unknown.push(...args.slice(i));
2343
- break;
2344
- } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2345
- operands.push(arg, ...args.slice(i));
2346
- break;
2347
- } else if (this._defaultCommandName) {
2348
- unknown.push(arg, ...args.slice(i));
2349
- break;
2350
- }
2351
- }
2352
- if (this._passThroughOptions) {
2353
- dest.push(arg, ...args.slice(i));
2354
- break;
2355
- }
2356
- dest.push(arg);
2357
- }
2358
- return {
2359
- operands,
2360
- unknown
2361
- };
2362
- }
2363
- /**
2364
- * Return an object containing local option values as key-value pairs.
2365
- *
2366
- * @return {object}
2367
- */
2368
- opts() {
2369
- if (this._storeOptionsAsProperties) {
2370
- const result = {};
2371
- const len = this.options.length;
2372
- for (let i = 0; i < len; i++) {
2373
- const key = this.options[i].attributeName();
2374
- result[key] = key === this._versionOptionName ? this._version : this[key];
2375
- }
2376
- return result;
2377
- }
2378
- return this._optionValues;
2379
- }
2380
- /**
2381
- * Return an object containing merged local and global option values as key-value pairs.
2382
- *
2383
- * @return {object}
2384
- */
2385
- optsWithGlobals() {
2386
- return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
2387
- }
2388
- /**
2389
- * Display error message and exit (or call exitOverride).
2390
- *
2391
- * @param {string} message
2392
- * @param {object} [errorOptions]
2393
- * @param {string} [errorOptions.code] - an id string representing the error
2394
- * @param {number} [errorOptions.exitCode] - used with process.exit
2395
- */
2396
- error(message, errorOptions) {
2397
- this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);
2398
- if (typeof this._showHelpAfterError === "string") this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);
2399
- else if (this._showHelpAfterError) {
2400
- this._outputConfiguration.writeErr("\n");
2401
- this.outputHelp({ error: true });
2402
- }
2403
- const config = errorOptions || {};
2404
- const exitCode = config.exitCode || 1;
2405
- const code = config.code || "commander.error";
2406
- this._exit(exitCode, code, message);
2407
- }
2408
- /**
2409
- * Apply any option related environment variables, if option does
2410
- * not have a value from cli or client code.
2411
- *
2412
- * @private
2413
- */
2414
- _parseOptionsEnv() {
2415
- this.options.forEach((option) => {
2416
- if (option.envVar && option.envVar in process$1.env) {
2417
- const optionKey = option.attributeName();
2418
- if (this.getOptionValue(optionKey) === void 0 || [
2419
- "default",
2420
- "config",
2421
- "env"
2422
- ].includes(this.getOptionValueSource(optionKey))) if (option.required || option.optional) this.emit(`optionEnv:${option.name()}`, process$1.env[option.envVar]);
2423
- else this.emit(`optionEnv:${option.name()}`);
2424
- }
2425
- });
2426
- }
2427
- /**
2428
- * Apply any implied option values, if option is undefined or default value.
2429
- *
2430
- * @private
2431
- */
2432
- _parseOptionsImplied() {
2433
- const dualHelper = new DualOptions(this.options);
2434
- const hasCustomOptionValue = (optionKey) => {
2435
- return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2436
- };
2437
- this.options.filter((option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
2438
- Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2439
- this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
2440
- });
2441
- });
2442
- }
2443
- /**
2444
- * Argument `name` is missing.
2445
- *
2446
- * @param {string} name
2447
- * @private
2448
- */
2449
- missingArgument(name) {
2450
- const message = `error: missing required argument '${name}'`;
2451
- this.error(message, { code: "commander.missingArgument" });
2452
- }
2453
- /**
2454
- * `Option` is missing an argument.
2455
- *
2456
- * @param {Option} option
2457
- * @private
2458
- */
2459
- optionMissingArgument(option) {
2460
- const message = `error: option '${option.flags}' argument missing`;
2461
- this.error(message, { code: "commander.optionMissingArgument" });
2462
- }
2463
- /**
2464
- * `Option` does not have a value, and is a mandatory option.
2465
- *
2466
- * @param {Option} option
2467
- * @private
2468
- */
2469
- missingMandatoryOptionValue(option) {
2470
- const message = `error: required option '${option.flags}' not specified`;
2471
- this.error(message, { code: "commander.missingMandatoryOptionValue" });
2472
- }
2473
- /**
2474
- * `Option` conflicts with another option.
2475
- *
2476
- * @param {Option} option
2477
- * @param {Option} conflictingOption
2478
- * @private
2479
- */
2480
- _conflictingOption(option, conflictingOption) {
2481
- const findBestOptionFromValue = (option) => {
2482
- const optionKey = option.attributeName();
2483
- const optionValue = this.getOptionValue(optionKey);
2484
- const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
2485
- const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
2486
- if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) return negativeOption;
2487
- return positiveOption || option;
2488
- };
2489
- const getErrorMessage = (option) => {
2490
- const bestOption = findBestOptionFromValue(option);
2491
- const optionKey = bestOption.attributeName();
2492
- if (this.getOptionValueSource(optionKey) === "env") return `environment variable '${bestOption.envVar}'`;
2493
- return `option '${bestOption.flags}'`;
2494
- };
2495
- const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2496
- this.error(message, { code: "commander.conflictingOption" });
2497
- }
2498
- /**
2499
- * Unknown option `flag`.
2500
- *
2501
- * @param {string} flag
2502
- * @private
2503
- */
2504
- unknownOption(flag) {
2505
- if (this._allowUnknownOption) return;
2506
- let suggestion = "";
2507
- if (flag.startsWith("--") && this._showSuggestionAfterError) {
2508
- let candidateFlags = [];
2509
- let command = this;
2510
- do {
2511
- const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2512
- candidateFlags = candidateFlags.concat(moreFlags);
2513
- command = command.parent;
2514
- } while (command && !command._enablePositionalOptions);
2515
- suggestion = suggestSimilar(flag, candidateFlags);
2516
- }
2517
- const message = `error: unknown option '${flag}'${suggestion}`;
2518
- this.error(message, { code: "commander.unknownOption" });
2519
- }
2520
- /**
2521
- * Excess arguments, more than expected.
2522
- *
2523
- * @param {string[]} receivedArgs
2524
- * @private
2525
- */
2526
- _excessArguments(receivedArgs) {
2527
- if (this._allowExcessArguments) return;
2528
- const expected = this.registeredArguments.length;
2529
- const s = expected === 1 ? "" : "s";
2530
- const message = `error: too many arguments${this.parent ? ` for '${this.name()}'` : ""}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2531
- this.error(message, { code: "commander.excessArguments" });
2532
- }
2533
- /**
2534
- * Unknown command.
2535
- *
2536
- * @private
2537
- */
2538
- unknownCommand() {
2539
- const unknownName = this.args[0];
2540
- let suggestion = "";
2541
- if (this._showSuggestionAfterError) {
2542
- const candidateNames = [];
2543
- this.createHelp().visibleCommands(this).forEach((command) => {
2544
- candidateNames.push(command.name());
2545
- if (command.alias()) candidateNames.push(command.alias());
2546
- });
2547
- suggestion = suggestSimilar(unknownName, candidateNames);
2548
- }
2549
- const message = `error: unknown command '${unknownName}'${suggestion}`;
2550
- this.error(message, { code: "commander.unknownCommand" });
2551
- }
2552
- /**
2553
- * Get or set the program version.
2554
- *
2555
- * This method auto-registers the "-V, --version" option which will print the version number.
2556
- *
2557
- * You can optionally supply the flags and description to override the defaults.
2558
- *
2559
- * @param {string} [str]
2560
- * @param {string} [flags]
2561
- * @param {string} [description]
2562
- * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2563
- */
2564
- version(str, flags, description) {
2565
- if (str === void 0) return this._version;
2566
- this._version = str;
2567
- flags = flags || "-V, --version";
2568
- description = description || "output the version number";
2569
- const versionOption = this.createOption(flags, description);
2570
- this._versionOptionName = versionOption.attributeName();
2571
- this._registerOption(versionOption);
2572
- this.on("option:" + versionOption.name(), () => {
2573
- this._outputConfiguration.writeOut(`${str}\n`);
2574
- this._exit(0, "commander.version", str);
2575
- });
2576
- return this;
2577
- }
2578
- /**
2579
- * Set the description.
2580
- *
2581
- * @param {string} [str]
2582
- * @param {object} [argsDescription]
2583
- * @return {(string|Command)}
2584
- */
2585
- description(str, argsDescription) {
2586
- if (str === void 0 && argsDescription === void 0) return this._description;
2587
- this._description = str;
2588
- if (argsDescription) this._argsDescription = argsDescription;
2589
- return this;
2590
- }
2591
- /**
2592
- * Set the summary. Used when listed as subcommand of parent.
2593
- *
2594
- * @param {string} [str]
2595
- * @return {(string|Command)}
2596
- */
2597
- summary(str) {
2598
- if (str === void 0) return this._summary;
2599
- this._summary = str;
2600
- return this;
2601
- }
2602
- /**
2603
- * Set an alias for the command.
2604
- *
2605
- * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2606
- *
2607
- * @param {string} [alias]
2608
- * @return {(string|Command)}
2609
- */
2610
- alias(alias) {
2611
- if (alias === void 0) return this._aliases[0];
2612
- /** @type {Command} */
2613
- let command = this;
2614
- if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) command = this.commands[this.commands.length - 1];
2615
- if (alias === command._name) throw new Error("Command alias can't be the same as its name");
2616
- const matchingCommand = this.parent?._findCommand(alias);
2617
- if (matchingCommand) {
2618
- const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
2619
- throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
2620
- }
2621
- command._aliases.push(alias);
2622
- return this;
2623
- }
2624
- /**
2625
- * Set aliases for the command.
2626
- *
2627
- * Only the first alias is shown in the auto-generated help.
2628
- *
2629
- * @param {string[]} [aliases]
2630
- * @return {(string[]|Command)}
2631
- */
2632
- aliases(aliases) {
2633
- if (aliases === void 0) return this._aliases;
2634
- aliases.forEach((alias) => this.alias(alias));
2635
- return this;
2636
- }
2637
- /**
2638
- * Set / get the command usage `str`.
2639
- *
2640
- * @param {string} [str]
2641
- * @return {(string|Command)}
2642
- */
2643
- usage(str) {
2644
- if (str === void 0) {
2645
- if (this._usage) return this._usage;
2646
- const args = this.registeredArguments.map((arg) => {
2647
- return humanReadableArgName(arg);
2648
- });
2649
- return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
2650
- }
2651
- this._usage = str;
2652
- return this;
2653
- }
2654
- /**
2655
- * Get or set the name of the command.
2656
- *
2657
- * @param {string} [str]
2658
- * @return {(string|Command)}
2659
- */
2660
- name(str) {
2661
- if (str === void 0) return this._name;
2662
- this._name = str;
2663
- return this;
2664
- }
2665
- /**
2666
- * Set/get the help group heading for this subcommand in parent command's help.
2667
- *
2668
- * @param {string} [heading]
2669
- * @return {Command | string}
2670
- */
2671
- helpGroup(heading) {
2672
- if (heading === void 0) return this._helpGroupHeading ?? "";
2673
- this._helpGroupHeading = heading;
2674
- return this;
2675
- }
2676
- /**
2677
- * Set/get the default help group heading for subcommands added to this command.
2678
- * (This does not override a group set directly on the subcommand using .helpGroup().)
2679
- *
2680
- * @example
2681
- * program.commandsGroup('Development Commands:);
2682
- * program.command('watch')...
2683
- * program.command('lint')...
2684
- * ...
2685
- *
2686
- * @param {string} [heading]
2687
- * @returns {Command | string}
2688
- */
2689
- commandsGroup(heading) {
2690
- if (heading === void 0) return this._defaultCommandGroup ?? "";
2691
- this._defaultCommandGroup = heading;
2692
- return this;
2693
- }
2694
- /**
2695
- * Set/get the default help group heading for options added to this command.
2696
- * (This does not override a group set directly on the option using .helpGroup().)
2697
- *
2698
- * @example
2699
- * program
2700
- * .optionsGroup('Development Options:')
2701
- * .option('-d, --debug', 'output extra debugging')
2702
- * .option('-p, --profile', 'output profiling information')
2703
- *
2704
- * @param {string} [heading]
2705
- * @returns {Command | string}
2706
- */
2707
- optionsGroup(heading) {
2708
- if (heading === void 0) return this._defaultOptionGroup ?? "";
2709
- this._defaultOptionGroup = heading;
2710
- return this;
2711
- }
2712
- /**
2713
- * @param {Option} option
2714
- * @private
2715
- */
2716
- _initOptionGroup(option) {
2717
- if (this._defaultOptionGroup && !option.helpGroupHeading) option.helpGroup(this._defaultOptionGroup);
2718
- }
2719
- /**
2720
- * @param {Command} cmd
2721
- * @private
2722
- */
2723
- _initCommandGroup(cmd) {
2724
- if (this._defaultCommandGroup && !cmd.helpGroup()) cmd.helpGroup(this._defaultCommandGroup);
2725
- }
2726
- /**
2727
- * Set the name of the command from script filename, such as process.argv[1],
2728
- * or require.main.filename, or __filename.
2729
- *
2730
- * (Used internally and public although not documented in README.)
2731
- *
2732
- * @example
2733
- * program.nameFromFilename(require.main.filename);
2734
- *
2735
- * @param {string} filename
2736
- * @return {Command}
2737
- */
2738
- nameFromFilename(filename) {
2739
- this._name = path$1.basename(filename, path$1.extname(filename));
2740
- return this;
2741
- }
2742
- /**
2743
- * Get or set the directory for searching for executable subcommands of this command.
2744
- *
2745
- * @example
2746
- * program.executableDir(__dirname);
2747
- * // or
2748
- * program.executableDir('subcommands');
2749
- *
2750
- * @param {string} [path]
2751
- * @return {(string|null|Command)}
2752
- */
2753
- executableDir(path) {
2754
- if (path === void 0) return this._executableDir;
2755
- this._executableDir = path;
2756
- return this;
2757
- }
2758
- /**
2759
- * Return program help documentation.
2760
- *
2761
- * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
2762
- * @return {string}
2763
- */
2764
- helpInformation(contextOptions) {
2765
- const helper = this.createHelp();
2766
- const context = this._getOutputContext(contextOptions);
2767
- helper.prepareContext({
2768
- error: context.error,
2769
- helpWidth: context.helpWidth,
2770
- outputHasColors: context.hasColors
2771
- });
2772
- const text = helper.formatHelp(this, helper);
2773
- if (context.hasColors) return text;
2774
- return this._outputConfiguration.stripColor(text);
2775
- }
2776
- /**
2777
- * @typedef HelpContext
2778
- * @type {object}
2779
- * @property {boolean} error
2780
- * @property {number} helpWidth
2781
- * @property {boolean} hasColors
2782
- * @property {function} write - includes stripColor if needed
2783
- *
2784
- * @returns {HelpContext}
2785
- * @private
2786
- */
2787
- _getOutputContext(contextOptions) {
2788
- contextOptions = contextOptions || {};
2789
- const error = !!contextOptions.error;
2790
- let baseWrite;
2791
- let hasColors;
2792
- let helpWidth;
2793
- if (error) {
2794
- baseWrite = (str) => this._outputConfiguration.writeErr(str);
2795
- hasColors = this._outputConfiguration.getErrHasColors();
2796
- helpWidth = this._outputConfiguration.getErrHelpWidth();
2797
- } else {
2798
- baseWrite = (str) => this._outputConfiguration.writeOut(str);
2799
- hasColors = this._outputConfiguration.getOutHasColors();
2800
- helpWidth = this._outputConfiguration.getOutHelpWidth();
2801
- }
2802
- const write = (str) => {
2803
- if (!hasColors) str = this._outputConfiguration.stripColor(str);
2804
- return baseWrite(str);
2805
- };
2806
- return {
2807
- error,
2808
- write,
2809
- hasColors,
2810
- helpWidth
2811
- };
2812
- }
2813
- /**
2814
- * Output help information for this command.
2815
- *
2816
- * Outputs built-in help, and custom text added using `.addHelpText()`.
2817
- *
2818
- * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2819
- */
2820
- outputHelp(contextOptions) {
2821
- let deprecatedCallback;
2822
- if (typeof contextOptions === "function") {
2823
- deprecatedCallback = contextOptions;
2824
- contextOptions = void 0;
2825
- }
2826
- const outputContext = this._getOutputContext(contextOptions);
2827
- /** @type {HelpTextEventContext} */
2828
- const eventContext = {
2829
- error: outputContext.error,
2830
- write: outputContext.write,
2831
- command: this
2832
- };
2833
- this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
2834
- this.emit("beforeHelp", eventContext);
2835
- let helpInformation = this.helpInformation({ error: outputContext.error });
2836
- if (deprecatedCallback) {
2837
- helpInformation = deprecatedCallback(helpInformation);
2838
- if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) throw new Error("outputHelp callback must return a string or a Buffer");
2839
- }
2840
- outputContext.write(helpInformation);
2841
- if (this._getHelpOption()?.long) this.emit(this._getHelpOption().long);
2842
- this.emit("afterHelp", eventContext);
2843
- this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
2844
- }
2845
- /**
2846
- * You can pass in flags and a description to customise the built-in help option.
2847
- * Pass in false to disable the built-in help option.
2848
- *
2849
- * @example
2850
- * program.helpOption('-?, --help' 'show help'); // customise
2851
- * program.helpOption(false); // disable
2852
- *
2853
- * @param {(string | boolean)} flags
2854
- * @param {string} [description]
2855
- * @return {Command} `this` command for chaining
2856
- */
2857
- helpOption(flags, description) {
2858
- if (typeof flags === "boolean") {
2859
- if (flags) {
2860
- if (this._helpOption === null) this._helpOption = void 0;
2861
- if (this._defaultOptionGroup) this._initOptionGroup(this._getHelpOption());
2862
- } else this._helpOption = null;
2863
- return this;
2864
- }
2865
- this._helpOption = this.createOption(flags ?? "-h, --help", description ?? "display help for command");
2866
- if (flags || description) this._initOptionGroup(this._helpOption);
2867
- return this;
2868
- }
2869
- /**
2870
- * Lazy create help option.
2871
- * Returns null if has been disabled with .helpOption(false).
2872
- *
2873
- * @returns {(Option | null)} the help option
2874
- * @package
2875
- */
2876
- _getHelpOption() {
2877
- if (this._helpOption === void 0) this.helpOption(void 0, void 0);
2878
- return this._helpOption;
2879
- }
2880
- /**
2881
- * Supply your own option to use for the built-in help option.
2882
- * This is an alternative to using helpOption() to customise the flags and description etc.
2883
- *
2884
- * @param {Option} option
2885
- * @return {Command} `this` command for chaining
2886
- */
2887
- addHelpOption(option) {
2888
- this._helpOption = option;
2889
- this._initOptionGroup(option);
2890
- return this;
2891
- }
2892
- /**
2893
- * Output help information and exit.
2894
- *
2895
- * Outputs built-in help, and custom text added using `.addHelpText()`.
2896
- *
2897
- * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2898
- */
2899
- help(contextOptions) {
2900
- this.outputHelp(contextOptions);
2901
- let exitCode = Number(process$1.exitCode ?? 0);
2902
- if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) exitCode = 1;
2903
- this._exit(exitCode, "commander.help", "(outputHelp)");
2904
- }
2905
- /**
2906
- * // Do a little typing to coordinate emit and listener for the help text events.
2907
- * @typedef HelpTextEventContext
2908
- * @type {object}
2909
- * @property {boolean} error
2910
- * @property {Command} command
2911
- * @property {function} write
2912
- */
2913
- /**
2914
- * Add additional text to be displayed with the built-in help.
2915
- *
2916
- * Position is 'before' or 'after' to affect just this command,
2917
- * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
2918
- *
2919
- * @param {string} position - before or after built-in help
2920
- * @param {(string | Function)} text - string to add, or a function returning a string
2921
- * @return {Command} `this` command for chaining
2922
- */
2923
- addHelpText(position, text) {
2924
- const allowedValues = [
2925
- "beforeAll",
2926
- "before",
2927
- "after",
2928
- "afterAll"
2929
- ];
2930
- if (!allowedValues.includes(position)) throw new Error(`Unexpected value for position to addHelpText.
2931
- Expecting one of '${allowedValues.join("', '")}'`);
2932
- const helpEvent = `${position}Help`;
2933
- this.on(helpEvent, (context) => {
2934
- let helpStr;
2935
- if (typeof text === "function") helpStr = text({
2936
- error: context.error,
2937
- command: context.command
2938
- });
2939
- else helpStr = text;
2940
- if (helpStr) context.write(`${helpStr}\n`);
2941
- });
2942
- return this;
2943
- }
2944
- /**
2945
- * Output help information if help flags specified
2946
- *
2947
- * @param {Array} args - array of options to search for help flags
2948
- * @private
2949
- */
2950
- _outputHelpIfRequested(args) {
2951
- const helpOption = this._getHelpOption();
2952
- if (helpOption && args.find((arg) => helpOption.is(arg))) {
2953
- this.outputHelp();
2954
- this._exit(0, "commander.helpDisplayed", "(outputHelp)");
2955
- }
2956
- }
2957
- };
2958
- /**
2959
- * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
2960
- *
2961
- * @param {string[]} args - array of arguments from node.execArgv
2962
- * @returns {string[]}
2963
- * @private
2964
- */
2965
- function incrementNodeInspectorPort(args) {
2966
- return args.map((arg) => {
2967
- if (!arg.startsWith("--inspect")) return arg;
2968
- let debugOption;
2969
- let debugHost = "127.0.0.1";
2970
- let debugPort = "9229";
2971
- let match;
2972
- if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) debugOption = match[1];
2973
- else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2974
- debugOption = match[1];
2975
- if (/^\d+$/.test(match[3])) debugPort = match[3];
2976
- else debugHost = match[3];
2977
- } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
2978
- debugOption = match[1];
2979
- debugHost = match[3];
2980
- debugPort = match[4];
2981
- }
2982
- if (debugOption && debugPort !== "0") return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2983
- return arg;
2984
- });
2985
- }
2986
- /**
2987
- * @returns {boolean | undefined}
2988
- * @package
2989
- */
2990
- function useColor() {
2991
- if (process$1.env.NO_COLOR || process$1.env.FORCE_COLOR === "0" || process$1.env.FORCE_COLOR === "false") return false;
2992
- if (process$1.env.FORCE_COLOR || process$1.env.CLICOLOR_FORCE !== void 0) return true;
2993
- }
2994
- exports.Command = Command;
2995
- exports.useColor = useColor;
2996
- }));
2997
- const { program: program$1, createCommand, createArgument, createOption, CommanderError, InvalidArgumentError, InvalidOptionArgumentError, Command, Argument, Option, Help } = (/* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports) => {
2998
- const { Argument } = require_argument();
2999
- const { Command } = require_command();
3000
- const { CommanderError, InvalidArgumentError } = require_error();
3001
- const { Help } = require_help();
3002
- const { Option } = require_option();
3003
- exports.program = new Command();
3004
- exports.createCommand = (name) => new Command(name);
3005
- exports.createOption = (flags, description) => new Option(flags, description);
3006
- exports.createArgument = (name, description) => new Argument(name, description);
3007
- /**
3008
- * Expose classes
3009
- */
3010
- exports.Command = Command;
3011
- exports.Option = Option;
3012
- exports.Argument = Argument;
3013
- exports.Help = Help;
3014
- exports.CommanderError = CommanderError;
3015
- exports.InvalidArgumentError = InvalidArgumentError;
3016
- exports.InvalidOptionArgumentError = InvalidArgumentError;
3017
- })))(), 1)).default;
3018
- //#endregion
3019
- //#region src/runtime/diagnose-run.ts
3020
- async function startDiagnosticRun(cwd, logicalRunId) {
3021
- const index = await readRunIndex(cwd, logicalRunId);
3022
- const dir = runDir(logicalRunId, cwd);
3023
- const spec = WorkflowSpecSchema.parse(JSON.parse(await fs.readFile(path.join(dir, "workflow.spec.json"), "utf8")));
3024
- const role = recoveryRole(spec.roles);
3025
- const diagnosticId = `diagnostic-${index.agentUsage.recoveryCalls + 1}`;
3026
- const output = {
3027
- status: "completed",
3028
- summary: "Diagnostic prompt prepared. Run recovery review as a normal workflow stage in a follow-up run if needed.",
3029
- artifacts: [{
3030
- kind: "prompt",
3031
- path: `prompts/${diagnosticId}.md`,
3032
- label: "Diagnostic prompt"
3033
- }],
3034
- nextFocus: "review recovery plan",
3035
- data: {
3036
- role,
3037
- contract: getOutputContract("diagnostic").schemaForPrompt
3038
- }
3039
- };
3040
- await fs.mkdir(path.join(dir, "prompts"), { recursive: true });
3041
- const diagnostics = await buildRunDiagnosticsView(cwd, index, { eventTailLimit: 50 });
3042
- await fs.writeFile(path.join(dir, "prompts", `${diagnosticId}.md`), diagnosticPrompt({
3043
- workflowName: spec.name,
3044
- runSnapshot: index,
3045
- outputs: await readExistingOutputs(dir),
3046
- diagnostics: diagnostics.diagnostics,
3047
- eventTail: diagnostics.eventTail
3048
- }), "utf8");
3049
- await fs.mkdir(path.join(dir, "diagnostics"), { recursive: true });
3050
- await fs.writeFile(path.join(dir, "diagnostics", `${diagnosticId}.json`), `${JSON.stringify(output, null, 2)}\n`, "utf8");
3051
- const next = {
3052
- ...index,
3053
- status: index.status === "blocked" || index.status === "failed" ? "diagnosed_blocked" : index.status,
3054
- agentUsage: {
3055
- ...index.agentUsage,
3056
- recoveryCalls: index.agentUsage.recoveryCalls + 1
3057
- }
3058
- };
3059
- await writeRunIndex(cwd, next);
3060
- await appendEvent(cwd, logicalRunId, {
3061
- type: "diagnostic_prepared",
3062
- diagnosticId
3063
- });
3064
- return next;
3065
- }
3066
- function recoveryRole(roles) {
3067
- return roles.recovery_reviewer ?? Object.values(roles).find((role) => role.category === "validation" || role.category === "review") ?? {
3068
- category: "review",
3069
- agent: "aiden",
3070
- mode: "readOnly"
3071
- };
3072
- }
3073
- async function readExistingOutputs(dir) {
3074
- const outputDir = path.join(dir, "outputs");
3075
- const outputs = {};
3076
- try {
3077
- const entries = await fs.readdir(outputDir);
3078
- for (const entry of entries) {
3079
- if (!entry.endsWith(".json")) continue;
3080
- outputs[path.basename(entry, ".json")] = JSON.parse(await fs.readFile(path.join(outputDir, entry), "utf8"));
3081
- }
3082
- } catch {}
3083
- return outputs;
3084
- }
3085
- function diagnosticPrompt(input) {
3086
- return `You are the recovery reviewer for a blocked acpus workflow.
3087
-
3088
- Workflow: ${input.workflowName}
3089
-
3090
- Run snapshot:
3091
- \`\`\`json
3092
- ${JSON.stringify(input.runSnapshot, null, 2)}
3093
- \`\`\`
3094
-
3095
- Author stage outputs:
3096
- \`\`\`json
3097
- ${JSON.stringify(input.outputs, null, 2)}
3098
- \`\`\`
3099
-
3100
- Runtime diagnostics:
3101
- \`\`\`json
3102
- ${JSON.stringify(input.diagnostics, null, 2)}
3103
- \`\`\`
3104
-
3105
- Recent runtime events:
3106
- \`\`\`json
3107
- ${JSON.stringify(input.eventTail, null, 2)}
3108
- \`\`\`
3109
-
3110
- Diagnose why the run is blocked and recommend the smallest safe recovery plan. Do not edit files. Do not rerun prior edit work.
3111
-
3112
- End the response with exactly one valid, parseable JSON object matching the diagnostic contract. Do not wrap the final JSON object in Markdown code fences. Do not use \`\`\`json.`;
3113
- }
3114
- //#endregion
3115
- //#region src/commands/common.ts
3116
- async function loadAndLint(specPath) {
3117
- const loaded = await loadWorkflowSpec(specPath);
3118
- if (!loaded.spec) return { result: resultFromIssues("validate", loaded.issues) };
3119
- const issues = [...loaded.issues, ...lintWorkflowSpec(loaded.spec)];
3120
- return {
3121
- spec: loaded.spec,
3122
- result: resultFromIssues("validate", issues)
3123
- };
3124
- }
3125
- function printJson(value) {
3126
- process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
3127
- }
3128
- function printIssues(result) {
3129
- if (result.ok) process.stdout.write("ok\n");
3130
- for (const warning of result.warnings) process.stdout.write(`warning ${warning.code} ${warning.path}: ${warning.message}\n`);
3131
- for (const error of result.errors) {
3132
- process.stderr.write(`${error.severity} ${error.code} ${error.path}: ${error.message}\n`);
3133
- for (const suggestion of error.suggestions ?? []) process.stderr.write(` suggestion: ${suggestion}\n`);
3134
- }
3135
- }
3136
- async function ensureEmptyOrOverwrite(target, overwrite) {
3137
- try {
3138
- await fs.stat(target);
3139
- if (!overwrite) throw new Error(`Target already exists: ${target}. Use --overwrite.`);
3140
- await fs.rm(target, {
3141
- recursive: true,
3142
- force: true
3143
- });
3144
- } catch (error) {
3145
- if (error.code !== "ENOENT") throw error;
3146
- }
3147
- }
3148
- async function readJsonFile(filePath) {
3149
- return JSON.parse(await fs.readFile(filePath, "utf8"));
3150
- }
3151
- function resolveSpecPath(options) {
3152
- if (options.spec && options.workflow) throw new Error("Use only one of --spec or --workflow.");
3153
- if (options.spec) return options.spec;
3154
- if (options.workflow) return path.join(options.global ? globalWorkflowsDir() : projectWorkflowsDir(), options.workflow, "workflow.spec.json");
3155
- throw new Error("Provide --spec <path> or --workflow <name>.");
3156
- }
3157
- //#endregion
3158
- //#region src/commands/diagnose.ts
3159
- function registerDiagnose(program) {
3160
- program.command("diagnose").argument("<run>", "logical run id or run directory").option("--wait", "wait until diagnostic preparation is reflected in the run index").option("--json", "print JSON").action(async (runArg, options) => {
3161
- const locator = await resolveRunLocator(runArg);
3162
- const started = await startDiagnosticRun(locator.cwd, locator.runId);
3163
- const index = options.wait ? await waitForDiagnostic(locator.cwd, locator.runId) : started;
3164
- const diagnostics = await buildRunDiagnosticsView(locator.cwd, index, { eventTailLimit: 50 });
3165
- const output = {
3166
- ok: true,
3167
- runId: locator.runId,
3168
- diagnosticId: `diagnostic-${index.agentUsage.recoveryCalls}`,
3169
- status: index.status,
3170
- message: options.wait ? "Diagnostic preparation finished." : "Diagnostic preparation started.",
3171
- diagnostics
3172
- };
3173
- if (options.json) printJson(output);
3174
- else process.stdout.write(`${output.message}\n`);
3175
- });
3176
- }
3177
- async function waitForDiagnostic(cwd, runId) {
3178
- return syncRun(cwd, runId, { startPending: false });
3179
- }
3180
- //#endregion
3181
- //#region src/commands/follow.ts
3182
- function registerFollow(program) {
3183
- program.command("follow").argument("<run>", "logical run id or run directory").option("--json", "print JSON").action(async (runArg, options) => {
3184
- const locator = await resolveRunLocator(runArg);
3185
- const index = await syncRun(locator.cwd, locator.runId, { startPending: false });
3186
- const spec = WorkflowSpecSchema.parse(JSON.parse(await fs.readFile(path.join(runDir(locator.runId, locator.cwd), "workflow.spec.json"), "utf8")));
3187
- if (options.json) printJson(await buildRunMonitorView(locator.cwd, spec, index));
3188
- else {
3189
- const view = await runViewFromIndex(locator.cwd, spec, index);
3190
- process.stdout.write(`run ${locator.runId} status=${view.status} workflow=${view.workflowName}${view.gateVerdict ? ` verdict=${view.gateVerdict}` : ""}\n`);
3191
- }
3192
- });
3193
- }
3194
- //#endregion
3195
- //#region src/commands/generate.ts
3196
- function registerGenerate(program) {
3197
- program.command("generate").option("--name <name>", "draft name", "draft-workflow").option("--json", "print JSON").action(async (options) => {
3198
- const dir = draftsDir();
3199
- await fs.mkdir(dir, { recursive: true });
3200
- const file = path.join(dir, `${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}-${options.name}.workflow.spec.json`);
3201
- const spec = {
3202
- schemaVersion: "acpus.workflow/v1",
3203
- name: options.name,
3204
- description: "Draft workflow scaffold. Main Agent should edit before running.",
3205
- root: "plan",
3206
- inputs: {
3207
- task: {
3208
- type: "string",
3209
- default: ""
3210
- },
3211
- cwd: {
3212
- type: "path",
3213
- default: "."
3214
- }
3215
- },
3216
- roles: { planner: {
3217
- category: "planning",
3218
- agent: "claude",
3219
- mode: "readOnly"
3220
- } },
3221
- limits: { stageTimeoutMinutes: 30 },
3222
- stages: [{
3223
- id: "plan",
3224
- kind: "agentTask",
3225
- role: "planner",
3226
- prompt: "Plan the requested workflow task: ${task}",
3227
- variables: [{
3228
- name: "task",
3229
- source: "input.task"
3230
- }]
3231
- }, {
3232
- id: "gate",
3233
- kind: "gate",
3234
- dependsOn: ["plan"]
3235
- }]
3236
- };
3237
- await fs.writeFile(file, `${JSON.stringify(spec, null, 2)}\n`, "utf8");
3238
- if (options.json) printJson({
3239
- ok: true,
3240
- path: file
3241
- });
3242
- else process.stdout.write(`${file}\n`);
3243
- });
3244
- }
3245
- //#endregion
3246
- //#region src/commands/list.ts
3247
- function registerList(program) {
3248
- program.command("list").argument("<kind>", "workflows|runs|drafts").option("--global", "list global workflows").option("--json", "print JSON").action(async (kind, options) => {
3249
- const dir = kind === "workflows" ? options.global ? globalWorkflowsDir() : projectWorkflowsDir() : kind === "runs" ? runsDir() : kind === "drafts" ? draftsDir() : "";
3250
- if (!dir) throw new Error("kind must be workflows, runs, or drafts");
3251
- const entries = await safeList(dir);
3252
- const output = {
3253
- kind,
3254
- dir,
3255
- entries
3256
- };
3257
- if (options.json) printJson(output);
3258
- else {
3259
- process.stdout.write(`${kind} in ${dir}\n`);
3260
- for (const entry of entries) process.stdout.write(`- ${entry}\n`);
3261
- }
3262
- });
3263
- }
3264
- async function safeList(dir) {
3265
- try {
3266
- return (await fs.readdir(dir, { withFileTypes: true })).filter((entry) => entry.isDirectory() || entry.isFile()).map((entry) => entry.name).sort();
3267
- } catch (error) {
3268
- if (error.code === "ENOENT") return [];
3269
- throw error;
3270
- }
3271
- }
3272
- //#endregion
3273
- //#region src/commands/monitor.ts
3274
- function registerMonitor(program) {
3275
- program.command("monitor").argument("<run>", "logical run id or run directory").option("--json", "print JSON").action(async (runArg, options) => {
3276
- if (!optionJson(options)) {
3277
- const { MonitorApp } = await import("./monitor-app-CSjUPe9j.mjs");
3278
- await render(React.createElement(MonitorApp, { runArg })).waitUntilExit();
3279
- return;
3280
- }
3281
- const { locator, spec, index } = await loadObservedRun(runArg);
3282
- printJson(await buildRunMonitorView(locator.cwd, spec, index));
3283
- }).command("detail").argument("<run>", "logical run id or run directory").argument("<task-id>", "Stage Task id").option("--json", "print JSON").action(async (runArg, taskId, options) => {
3284
- if (!optionJson(options)) throw new Error("Usage: monitor detail <run> <task-id> --json");
3285
- const { locator, spec, index } = await loadObservedRun(runArg);
3286
- printJson(await buildTaskDetailView(locator.cwd, spec, index, taskId));
3287
- });
3288
- }
3289
- function optionJson(options) {
3290
- if ("json" in options && typeof options.json === "boolean") return options.json;
3291
- if ("opts" in options && typeof options.opts === "function") {
3292
- if (options.opts().json) return true;
3293
- if (options.getOptionValue?.("json")) return true;
3294
- if (options.parent?.opts().json) return true;
3295
- }
3296
- return process.argv.includes("--json");
3297
- }
3298
- async function loadObservedRun(runArg) {
3299
- const locator = await resolveRunLocator(runArg);
3300
- return {
3301
- locator,
3302
- index: await syncRun(locator.cwd, locator.runId, { startPending: false }),
3303
- spec: WorkflowSpecSchema.parse(JSON.parse(await fs.readFile(path.join(runDir(locator.runId, locator.cwd), "workflow.spec.json"), "utf8")))
3304
- };
3305
- }
3306
- //#endregion
3307
- //#region src/commands/preview.ts
3308
- function registerPreview(program) {
3309
- program.command("preview").option("--spec <path>", "workflow spec path").option("--workflow <name>", "saved workflow name").option("--global", "resolve saved workflow from global directory").option("--json", "print JSON").action(async (options) => {
3310
- const specPath = resolveSpecPath(options);
3311
- const { spec, result } = await loadAndLint(specPath);
3312
- if (!spec) {
3313
- if (options.json) printJson(result);
3314
- else printIssues(result);
3315
- process.exitCode = 1;
3316
- return;
3317
- }
3318
- const view = previewRunView(spec, [...result.warnings, ...result.errors], {
3319
- validate: `acpus validate --spec ${specPath}`,
3320
- run: `acpus run --spec ${specPath}`
3321
- });
3322
- if (options.json) printJson(view);
3323
- else {
3324
- process.stdout.write(`Workflow: ${view.workflowName}\n`);
3325
- process.stdout.write(`Status: ${view.status}\n`);
3326
- process.stdout.write(`Planned agent calls: ${view.agentUsage.planned}\n`);
3327
- for (const fanout of view.fanout) process.stdout.write(`Fanout ${fanout.stageId}: up to ${fanout.estimatedWorkUnits} lane work unit(s) from ${fanout.maxItems} item(s)\n`);
3328
- process.stdout.write("Risks:\n");
3329
- for (const risk of view.risks) process.stdout.write(`- ${risk}\n`);
3330
- process.stdout.write("Stages:\n");
3331
- for (const stage of view.stages) process.stdout.write(`- ${stage.id} (${stage.kind})\n`);
3332
- process.stdout.write("Audit:\n");
3333
- process.stdout.write("- Run snapshot: .acpus/runs/<logicalRunId>/\n");
3334
- process.stdout.write("- Saved workflow snapshot: .acpus/workflows/<name>/ after explicit save\n");
3335
- printIssues(result);
3336
- }
3337
- if (!result.ok) process.exitCode = 1;
3338
- });
3339
- }
3340
- //#endregion
3341
- //#region src/commands/recover.ts
3342
- function registerRecover(program) {
3343
- program.command("recover").argument("<run>", "logical run id or run directory").option("--json", "print JSON").action(async (runArg, options) => {
3344
- const recovered = await recoverDriver(runArg);
3345
- const output = {
3346
- ok: true,
3347
- runId: recovered.runId,
3348
- runDir: recovered.runDir,
3349
- worker: recovered.worker,
3350
- message: "Run worker recovered."
3351
- };
3352
- if (options.json) printJson(output);
3353
- else {
3354
- process.stdout.write(`${output.message}\n`);
3355
- process.stdout.write(`runId=${output.runId}\n`);
3356
- process.stdout.write(`runDir=${output.runDir}\n`);
3357
- process.stdout.write(`worker=${output.worker.pid} status=${output.worker.status}\n`);
3358
- }
3359
- });
3360
- }
3361
- //#endregion
3362
- //#region src/runtime/resume-policy.ts
3363
- function parseResumePolicyOptions(options) {
3364
- const fanout = {};
3365
- const issues = [];
3366
- for (const stage of options.allowPartialFanout ?? []) fanout[stage] = {
3367
- ...fanout[stage] ?? {},
3368
- allowPartial: true
3369
- };
3370
- for (let index = 0; index < (options.maxFanoutItems ?? []).length; index += 1) {
3371
- const item = options.maxFanoutItems?.[index] ?? "";
3372
- const parsed = parseStageInteger(item);
3373
- if (!parsed) {
3374
- issues.push(issue({
3375
- code: "RESUME_POLICY_INVALID_MAX_ITEMS",
3376
- severity: "error",
3377
- path: `/resumePolicy/maxFanoutItems/${index}`,
3378
- message: `Invalid --max-fanout-items value: ${item}.`,
3379
- suggestions: ["Use stage=count with a non-negative integer count, for example review_files=4."]
3380
- }));
3381
- continue;
3382
- }
3383
- fanout[parsed.stage] = {
3384
- ...fanout[parsed.stage] ?? {},
3385
- maxItems: parsed.value
3386
- };
3387
- }
3388
- for (let index = 0; index < (options.skipFanoutItem ?? []).length; index += 1) {
3389
- const item = options.skipFanoutItem?.[index] ?? "";
3390
- const parsed = parseStageInteger(item);
3391
- if (!parsed) {
3392
- issues.push(issue({
3393
- code: "RESUME_POLICY_INVALID_SKIP_ITEM",
3394
- severity: "error",
3395
- path: `/resumePolicy/skipFanoutItem/${index}`,
3396
- message: `Invalid --skip-fanout-item value: ${item}.`,
3397
- suggestions: ["Use stage=index with a non-negative zero-based item index, for example review_files=2."]
3398
- }));
3399
- continue;
3400
- }
3401
- const existing = fanout[parsed.stage] ?? {};
3402
- fanout[parsed.stage] = {
3403
- ...existing,
3404
- skipItemIndexes: [...existing.skipItemIndexes ?? [], parsed.value]
3405
- };
3406
- }
3407
- return {
3408
- policy: { fanout },
3409
- issues
3410
- };
3411
- }
3412
- function validateResumePolicy(spec, policy) {
3413
- const issues = [];
3414
- const stageIds = spec.stages.map((stage) => stage.id);
3415
- for (const [stageId, fanoutPolicy] of Object.entries(policy.fanout)) {
3416
- const stageIndex = spec.stages.findIndex((stage) => stage.id === stageId);
3417
- const stage = spec.stages[stageIndex];
3418
- const policyPath = `/resumePolicy/fanout/${stageId}`;
3419
- if (!stage) {
3420
- issues.push(issue({
3421
- code: "RESUME_POLICY_STAGE_UNKNOWN",
3422
- severity: "error",
3423
- path: policyPath,
3424
- message: `Resume policy references unknown stage ${stageId}.`,
3425
- suggestions: [`Use one of the declared stage ids: ${stageIds.join(", ")}.`]
3426
- }));
3427
- continue;
3428
- }
3429
- if (stage.kind !== "fanout") {
3430
- issues.push(issue({
3431
- code: "RESUME_POLICY_STAGE_NOT_FANOUT",
3432
- severity: "error",
3433
- path: policyPath,
3434
- message: `Resume policy stage ${stageId} is ${stage.kind}, not fanout.`,
3435
- suggestions: ["Use a fanout stage id for fanout resume policy overrides."]
3436
- }));
3437
- continue;
3438
- }
3439
- const hasEditLane = stage.laneGroups.some((group) => group.lanes.some((lane) => spec.roles[lane.role]?.mode === "edit"));
3440
- if (fanoutPolicy.allowPartial && hasEditLane) issues.push(issue({
3441
- code: "RESUME_POLICY_PARTIAL_REQUIRES_READONLY",
3442
- severity: "error",
3443
- path: `${policyPath}/allowPartial`,
3444
- message: `Resume cannot enable partial results for edit fanout stage ${stageId}.`,
3445
- suggestions: ["Use diagnose for recovery advice, then start a new run if edit recovery is needed."]
3446
- }));
3447
- const compiledMaxItems = stage.limits?.maxFanoutItems ?? 1;
3448
- if (fanoutPolicy.maxItems !== void 0 && fanoutPolicy.maxItems > compiledMaxItems) issues.push(issue({
3449
- code: "RESUME_POLICY_MAX_ITEMS_NOT_TIGHTENING",
3450
- severity: "error",
3451
- path: `${policyPath}/maxItems`,
3452
- message: `Resume maxItems ${fanoutPolicy.maxItems} exceeds compiled fanout cap ${compiledMaxItems} for stage ${stageId}.`,
3453
- suggestions: [`Use a value between 0 and ${compiledMaxItems}, or start a new run from an updated spec.`]
3454
- }));
3455
- for (const [index, itemIndex] of (fanoutPolicy.skipItemIndexes ?? []).entries()) if (itemIndex >= compiledMaxItems) issues.push(issue({
3456
- code: "RESUME_POLICY_SKIP_ITEM_OUT_OF_RANGE",
3457
- severity: "error",
3458
- path: `${policyPath}/skipItemIndexes/${index}`,
3459
- message: `Resume skip item index ${itemIndex} is outside compiled fanout cap ${compiledMaxItems} for stage ${stageId}.`,
3460
- suggestions: [`Use an item index from 0 to ${Math.max(0, compiledMaxItems - 1)}.`]
3461
- }));
3462
- }
3463
- return issues;
3464
- }
3465
- function mergeResumePolicy(existing, next) {
3466
- const current = existing && typeof existing === "object" ? existing : { fanout: {} };
3467
- return { fanout: {
3468
- ...current.fanout ?? {},
3469
- ...Object.fromEntries(Object.entries(next.fanout).map(([stage, policy]) => [stage, {
3470
- ...current.fanout?.[stage] ?? {},
3471
- ...policy,
3472
- skipItemIndexes: [...current.fanout?.[stage]?.skipItemIndexes ?? [], ...policy.skipItemIndexes ?? []]
3473
- }]))
3474
- } };
3475
- }
3476
- function parseStageInteger(value) {
3477
- const separator = value.indexOf("=");
3478
- if (separator <= 0 || separator === value.length - 1) return void 0;
3479
- const stage = value.slice(0, separator);
3480
- const rawValue = value.slice(separator + 1);
3481
- const parsed = Number(rawValue);
3482
- if (!Number.isInteger(parsed) || parsed < 0) return void 0;
3483
- return {
3484
- stage,
3485
- value: parsed
3486
- };
3487
- }
3488
- //#endregion
3489
- //#region src/commands/resume.ts
3490
- function registerResume(program) {
3491
- program.command("resume").argument("<run>", "logical run id or run directory").option("--allow-partial-fanout <stage...>", "allow partial results for read-only fanout stage(s) on resume").option("--max-fanout-items <stage=count...>", "tighten max fanout items for stage(s), bounded by the compiled snapshot").option("--skip-fanout-item <stage=index...>", "skip zero-based fanout item index(es) on resume").option("--wait", "advance until terminal").option("--json", "print JSON").action(async (runArg, options) => {
3492
- const locator = await resolveRunLocator(runArg);
3493
- const spec = await readRunSpec(locator.cwd, locator.runId);
3494
- const parsedPolicy = parseResumePolicyOptions(options);
3495
- const policyIssues = [...parsedPolicy.issues, ...validateResumePolicy(spec, parsedPolicy.policy)];
3496
- if (policyIssues.some((entry) => entry.severity !== "warning")) {
3497
- printResumeIssues(options.json, policyIssues);
3498
- process.exitCode = 2;
3499
- return;
3500
- }
3501
- const index = await readRunIndex(locator.cwd, locator.runId);
3502
- if (index.status !== "blocked" && index.status !== "failed" && index.status !== "diagnosed_blocked") {
3503
- printResumeIssues(options.json, [issue({
3504
- code: "RESUME_POLICY_INVALID",
3505
- severity: "error",
3506
- path: "/",
3507
- message: `Run ${locator.runId} is ${index.status}; resume is only for blocked, failed, or diagnosed_blocked runs.`,
3508
- suggestions: [index.status === "running" || index.status === "pending" ? "Use monitor to observe the active run, or recover if its worker is stale." : "Start a new run for completed workflows."]
3509
- })]);
3510
- process.exitCode = 2;
3511
- return;
3512
- }
3513
- if (workerIsActive(index.worker)) {
3514
- printResumeIssues(options.json, [issue({
3515
- code: "RESUME_POLICY_INVALID",
3516
- severity: "error",
3517
- path: "/",
3518
- message: `Run ${locator.runId} already has an active worker pid=${index.worker?.pid}; resume cannot take ownership.`,
3519
- suggestions: ["Use monitor to observe the active run, or recover after the worker becomes stale."]
3520
- })]);
3521
- process.exitCode = 2;
3522
- return;
3523
- }
3524
- const reset = resetRecoverableStages({
3525
- ...index,
3526
- resumePolicy: mergeResumePolicy(index.resumePolicy, parsedPolicy.policy)
3527
- }, spec);
3528
- await writeRunIndex(locator.cwd, reset);
3529
- let finalIndex;
3530
- try {
3531
- finalIndex = options.wait ? await runWorkflowWorker(locator.cwd, locator.runId) : await readRunIndex(locator.cwd, locator.runId);
3532
- const worker = options.wait ? finalIndex.worker : await spawnBackgroundWorker(locator.cwd, locator.runId);
3533
- if (!options.wait) finalIndex = {
3534
- ...await readRunIndex(locator.cwd, locator.runId),
3535
- worker
3536
- };
3537
- } catch (error) {
3538
- await markKnownRunFatal$1(locator.cwd, locator.runId, error);
3539
- throw error;
3540
- }
3541
- const output = {
3542
- ok: true,
3543
- runId: locator.runId,
3544
- status: finalIndex.status,
3545
- worker: finalIndex.worker,
3546
- message: options.wait ? "Run resume reached a terminal state." : "Run resume started a background worker."
3547
- };
3548
- if (options.json) printJson(output);
3549
- else process.stdout.write(`${output.message}\n`);
3550
- });
3551
- }
3552
- async function readRunSpec(cwd, runId) {
3553
- return WorkflowSpecSchema.parse(JSON.parse(await fs.readFile(path.join(runDir(runId, cwd), "workflow.spec.json"), "utf8")));
3554
- }
3555
- function resetRecoverableStages(index, spec) {
3556
- const kindByStage = new Map(spec.stages.map((stage) => [stage.id, stage.kind]));
3557
- const shouldRecomputeGate = index.gateVerdict === "blocked" || index.gateVerdict === "failed" || index.gateVerdict === "unknown";
3558
- let gateVerdict = index.gateVerdict;
3559
- let resetGate = false;
3560
- const stages = Object.fromEntries(Object.entries(index.stages).map(([id, stage]) => {
3561
- const stageKind = kindByStage.get(id);
3562
- if (!(stage.status === "failed" || stage.status === "blocked") && !(stageKind === "gate" && shouldRecomputeGate)) return [id, stage];
3563
- if (stageKind === "gate") {
3564
- gateVerdict = void 0;
3565
- resetGate = true;
3566
- }
3567
- return [id, {
3568
- ...stage,
3569
- status: stage.fanout ? "running" : "pending",
3570
- blockedReason: void 0,
3571
- completedAt: void 0,
3572
- outputPath: stageKind === "gate" ? void 0 : stage.outputPath
3573
- }];
3574
- }));
3575
- return {
3576
- ...index,
3577
- status: "running",
3578
- stages,
3579
- blockedReason: void 0,
3580
- gateVerdict: resetGate ? gateVerdict : index.gateVerdict
3581
- };
3582
- }
3583
- function printResumeIssues(json, issues) {
3584
- const result = resultFromIssues("resume", issues.map(issue));
3585
- if (json) printJson(result);
3586
- else printIssues(result);
3587
- }
3588
- async function markKnownRunFatal$1(cwd, runId, error) {
3589
- const message = error instanceof Error ? error.message : String(error);
3590
- try {
3591
- await writeRunIndex(cwd, {
3592
- ...await readRunIndex(cwd, runId),
3593
- status: "failed",
3594
- blockedReason: `RUNTIME_COMMAND_ERROR: ${message}`
3595
- });
3596
- await appendEvent(cwd, runId, {
3597
- type: "runtime_fatal",
3598
- code: "RUNTIME_COMMAND_ERROR",
3599
- status: "failed",
3600
- errorMessage: message,
3601
- errorMetadata: error instanceof Error && "metadata" in error ? error.metadata : void 0
3602
- });
3603
- } catch {}
3604
- }
3605
- //#endregion
3606
- //#region src/commands/run.ts
3607
- function registerRun(program) {
3608
- program.command("run").option("--spec <path>", "workflow spec path").option("--workflow <name>", "saved workflow name").option("--global", "resolve saved workflow from global directory").option("--input-json <path>", "raw workflow input JSON file").option("--wait", "run in the foreground until the workflow reaches a terminal state").option("--json", "print JSON").action(async (options) => {
3609
- const specPath = resolveSpecPath(options);
3610
- const { spec, result } = await loadAndLint(specPath);
3611
- if (!spec || !result.ok) {
3612
- if (options.json) printJson(result);
3613
- else printIssues(result);
3614
- process.exitCode = 1;
3615
- return;
3616
- }
3617
- const input = applyInputDefaults(spec, options.inputJson ? await readJsonFile(options.inputJson) : {});
3618
- const inputResult = resultFromIssues("input", validateWorkflowInput(spec, input));
3619
- if (!inputResult.ok) {
3620
- if (options.json) printJson(inputResult);
3621
- else printIssues(inputResult);
3622
- process.exitCode = 1;
3623
- return;
3624
- }
3625
- const prepared = await prepareRun(spec, {
3626
- cwd: process.cwd(),
3627
- input,
3628
- sourcePath: specPath
3629
- });
3630
- try {
3631
- if (options.wait) {
3632
- const finalIndex = await runWorkflowWorker(process.cwd(), prepared.logicalRunId, { reporter: waitReporter(options.json) });
3633
- emitTerminalSummary(options.json, prepared.logicalRunId, prepared.dir, finalIndex);
3634
- return;
3635
- }
3636
- const worker = await spawnBackgroundWorker(process.cwd(), prepared.logicalRunId);
3637
- const output = {
3638
- ok: true,
3639
- logicalRunId: prepared.logicalRunId,
3640
- runDir: prepared.dir,
3641
- status: "running",
3642
- worker,
3643
- note: "Run started in a background worker."
3644
- };
3645
- if (options.json) printJson(output);
3646
- else {
3647
- process.stdout.write(`run started: ${prepared.logicalRunId}\n`);
3648
- process.stdout.write(`status: running worker=${worker.pid}\n`);
3649
- process.stdout.write(`${prepared.dir}\n`);
3650
- }
3651
- } catch (error) {
3652
- await markKnownRunFatal(process.cwd(), prepared.logicalRunId, error);
3653
- throw error;
3654
- }
3655
- });
3656
- }
3657
- function waitReporter(json) {
3658
- return async (event) => {
3659
- if (json) {
3660
- process.stdout.write(`${JSON.stringify(event)}\n`);
3661
- return;
3662
- }
3663
- if (event.type === "worker_started") process.stdout.write(`worker started pid=${event.pid} run=${event.runId}\n`);
3664
- else if (event.type === "run_progress") {
3665
- const stages = event.changedStages.map((stage) => `${stage.id}=${stage.status}`).join(" ");
3666
- process.stdout.write(`progress status=${event.status}${stages ? ` ${stages}` : ""}\n`);
3667
- } else process.stdout.write(`worker exited pid=${event.pid} status=${event.status} exit=${event.exitCode ?? ""}\n`);
3668
- };
3669
- }
3670
- function emitTerminalSummary(json, runId, dir, index) {
3671
- const summary = {
3672
- type: "terminal_summary",
3673
- ok: index.status !== "failed" && index.status !== "cancelled",
3674
- logicalRunId: runId,
3675
- runDir: dir,
3676
- status: index.status,
3677
- blockedReason: index.blockedReason,
3678
- gateVerdict: index.gateVerdict
3679
- };
3680
- if (json) process.stdout.write(`${JSON.stringify(summary)}\n`);
3681
- else process.stdout.write(`terminal status=${summary.status}${summary.gateVerdict ? ` verdict=${summary.gateVerdict}` : ""}\n`);
3682
- }
3683
- async function markKnownRunFatal(cwd, runId, error) {
3684
- const message = error instanceof Error ? error.message : String(error);
3685
- try {
3686
- await writeRunIndex(cwd, {
3687
- ...await readRunIndex(cwd, runId),
3688
- status: "failed",
3689
- blockedReason: `RUNTIME_COMMAND_ERROR: ${message}`
3690
- });
3691
- await appendEvent(cwd, runId, {
3692
- type: "runtime_fatal",
3693
- code: "RUNTIME_COMMAND_ERROR",
3694
- status: "failed",
3695
- errorMessage: message,
3696
- errorMetadata: error instanceof Error && "metadata" in error ? error.metadata : void 0
3697
- });
3698
- } catch {}
3699
- }
3700
- //#endregion
3701
- //#region src/commands/run-worker.ts
3702
- function registerRunWorker(program) {
3703
- program.command("_run-worker", { hidden: true }).description("internal background workflow worker").argument("<run>", "logical run id").allowUnknownOption(false).action(async (runId) => {
3704
- await runWorkflowWorker(process.cwd(), runId);
3705
- });
3706
- }
3707
- //#endregion
3708
- //#region src/commands/save.ts
3709
- function registerSave(program) {
3710
- program.command("save").argument("<name>", "workflow name").requiredOption("--spec <path>", "workflow spec path").option("--overwrite", "overwrite existing workflow").option("--global", "save to global workflow directory").option("--json", "print JSON").action(async (name, options) => {
3711
- const { spec, result } = await loadAndLint(options.spec);
3712
- if (!spec || !result.ok) {
3713
- if (options.json) printJson(result);
3714
- else printIssues(result);
3715
- process.exitCode = 1;
3716
- return;
3717
- }
3718
- const root = options.global ? globalWorkflowsDir() : projectWorkflowsDir();
3719
- const target = path.join(root, name);
3720
- await ensureEmptyOrOverwrite(target, options.overwrite);
3721
- await fs.mkdir(target, { recursive: true });
3722
- const plan = compileExecutionPlan(spec);
3723
- await fs.writeFile(path.join(target, "workflow.spec.json"), `${JSON.stringify(spec, null, 2)}\n`, "utf8");
3724
- await fs.writeFile(path.join(target, "execution-plan.json"), `${JSON.stringify(plan, null, 2)}\n`, "utf8");
3725
- await writeHelperSnapshot(target);
3726
- await fs.writeFile(path.join(target, "README.md"), `# ${name}\n\n${spec.description || "Saved acpus workflow."}\n\nThis directory is a saved runtime-driven workflow snapshot. The stable authoring interface is workflow.spec.json; execution-plan.json is the derived runtime plan and should normally be regenerated from the spec.\n\nRun with acpus using workflow.spec.json.\n`, "utf8");
3727
- const output = {
3728
- ok: true,
3729
- workflow: name,
3730
- path: target
3731
- };
3732
- if (options.json) printJson(output);
3733
- else process.stdout.write(`saved ${name} -> ${target}\n`);
3734
- });
3735
- }
3736
- async function writeHelperSnapshot(target) {
3737
- const root = await findPackageRoot();
3738
- const helperDir = path.join(target, "helper");
3739
- await assertBuiltHelperAvailable(root);
3740
- await fs.mkdir(helperDir, { recursive: true });
3741
- await copyIfExists(path.join(root, "package.json"), path.join(helperDir, "package.json"));
3742
- await copyIfExists(path.join(root, "package-lock.json"), path.join(helperDir, "package-lock.json"));
3743
- await copyIfExists(path.join(root, "schemas"), path.join(helperDir, "schemas"));
3744
- await copyIfExists(path.join(root, "docs", "workflow-spec.md"), path.join(helperDir, "docs", "workflow-spec.md"));
3745
- await copyIfExists(path.join(root, "docs", "cli.md"), path.join(helperDir, "docs", "cli.md"));
3746
- await copyIfExists(path.join(root, "docs", "error-codes.md"), path.join(helperDir, "docs", "error-codes.md"));
3747
- await copyIfExists(path.join(root, "scripts", "acpus"), path.join(helperDir, "scripts", "acpus"));
3748
- await fs.chmod(path.join(helperDir, "scripts", "acpus"), 493).catch(() => void 0);
3749
- await copyIfExists(path.join(root, "dist"), path.join(helperDir, "dist"));
3750
- }
3751
- async function assertBuiltHelperAvailable(root) {
3752
- let hasCli = false;
3753
- try {
3754
- await fs.access(path.join(root, "dist", "cli.mjs"));
3755
- hasCli = true;
3756
- } catch {}
3757
- if (!hasCli) try {
3758
- await fs.access(path.join(root, "dist", "cli.js"));
3759
- hasCli = true;
3760
- } catch {}
3761
- if (!hasCli) throw new Error(`Cannot save a self-contained helper snapshot because ${path.join(root, "dist")} is missing a built CLI. Run npm run build in ${root} first.`);
3762
- }
3763
- async function copyIfExists(source, target) {
3764
- try {
3765
- const stat = await fs.stat(source);
3766
- await fs.mkdir(path.dirname(target), { recursive: true });
3767
- if (stat.isDirectory()) await fs.cp(source, target, {
3768
- recursive: true,
3769
- force: true
3770
- });
3771
- else await fs.copyFile(source, target);
3772
- } catch (error) {
3773
- if (error.code !== "ENOENT") throw error;
3774
- }
3775
- }
3776
- async function findPackageRoot() {
3777
- const candidates = [
3778
- path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", ".."),
3779
- path.resolve(path.dirname(process.argv[1] ?? "."), ".."),
3780
- process.cwd()
3781
- ];
3782
- for (const candidate of candidates) {
3783
- const found = await ascendToPackageRoot(candidate);
3784
- if (found) return found;
3785
- }
3786
- return process.cwd();
3787
- }
3788
- async function ascendToPackageRoot(start) {
3789
- let current = path.resolve(start);
3790
- while (true) {
3791
- try {
3792
- if (JSON.parse(await fs.readFile(path.join(current, "package.json"), "utf8")).name === "acpus") return current;
3793
- } catch {}
3794
- const parent = path.dirname(current);
3795
- if (parent === current) return void 0;
3796
- current = parent;
3797
- }
3798
- }
3799
- //#endregion
3800
- //#region src/commands/show.ts
3801
- function registerShow(program) {
3802
- program.command("show").argument("<kind>", "workflow|run|draft").argument("<name>", "name or run id").option("--global", "show global workflow").option("--json", "print JSON").action(async (kind, name, options) => {
3803
- const file = await resolveShowFile(kind, name, options.global);
3804
- if (!file) throw new Error("kind must be workflow, run, or draft");
3805
- const text = await fs.readFile(file, "utf8");
3806
- if (options.json) printJson(JSON.parse(text));
3807
- else process.stdout.write(text);
3808
- });
3809
- }
3810
- async function resolveShowFile(kind, name, global) {
3811
- if (kind === "workflow") return path.join(global ? globalWorkflowsDir() : projectWorkflowsDir(), name, "workflow.spec.json");
3812
- if (kind === "run") {
3813
- const locator = await resolveRunLocator(name);
3814
- return path.join(runDir(locator.runId, locator.cwd), "run.json");
3815
- }
3816
- if (kind === "draft") return path.join(draftsDir(), name);
3817
- return "";
3818
- }
3819
- //#endregion
3820
- //#region src/commands/validate.ts
3821
- function registerValidate(program) {
3822
- program.command("validate").option("--spec <path>", "workflow spec path").option("--workflow <name>", "saved workflow name").option("--global", "resolve saved workflow from global directory").option("--json", "print JSON").action(async (options) => {
3823
- const { result } = await loadAndLint(resolveSpecPath(options));
3824
- if (options.json) printJson(result);
3825
- else printIssues(result);
3826
- if (!result.ok) process.exitCode = 1;
3827
- });
3828
- }
3829
- //#endregion
3830
- //#region src/cli.ts
3831
- const program = new Command();
3832
- program.name("acpus").description("Acpus — compose, conduct, recover, catalogue.").version("0.1.0");
3833
- registerValidate(program);
3834
- registerPreview(program);
3835
- registerSave(program);
3836
- registerGenerate(program);
3837
- registerRun(program);
3838
- registerFollow(program);
3839
- registerMonitor(program);
3840
- registerResume(program);
3841
- registerRunWorker(program);
3842
- registerRecover(program);
3843
- registerDiagnose(program);
3844
- registerList(program);
3845
- registerShow(program);
3846
- program.parseAsync(process.argv).catch((error) => {
3847
- const message = error instanceof Error ? error.message : String(error);
3848
- const result = resultFromIssues("cli", [issue({
3849
- code: "RUNTIME_COMMAND_ERROR",
3850
- severity: "fatal",
3851
- path: "/",
3852
- message,
3853
- suggestions: ["Check the command arguments with acpus --help."]
3854
- })]);
3855
- if (process.argv.includes("--json")) process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
3856
- else process.stderr.write(`fatal RUNTIME_COMMAND_ERROR /: ${message}\n`);
3857
- process.exitCode = 1;
3858
- });
3859
- //#endregion
3860
- export {};