@bemoje/cli 4.0.1 → 5.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,1445 +1,1572 @@
1
- import C from 'ansi-colors'
2
- import humanizeDuration from 'humanize-duration'
3
- import { inspect } from 'util'
4
- import { isFunction } from 'es-toolkit/predicate'
5
- import { isPrimitive } from 'es-toolkit/predicate'
6
- import { isPromise } from 'util/types'
7
- import { isString } from 'es-toolkit/predicate'
8
- import { kebabCase } from 'es-toolkit/string'
9
- import { last } from 'es-toolkit/array'
10
- import memoizee from 'memoizee'
11
- import { ms } from 'enhanced-ms'
12
- import { parseArgs } from 'util'
13
- import { uniq } from 'es-toolkit/array'
14
- import { upperFirst } from 'es-toolkit/string'
1
+ import C from 'ansi-colors';
2
+ import { isFunction, isString, isPrimitive } from 'es-toolkit/predicate';
3
+ import memoizee from 'memoizee';
4
+ import { ms } from 'enhanced-ms';
5
+ import { inspect, parseArgs } from 'util';
6
+ import { kebabCase, upperFirst } from 'es-toolkit/string';
7
+ import { uniq, last } from 'es-toolkit/array';
8
+ import humanizeDuration from 'humanize-duration';
9
+ import { isPromise } from 'util/types';
15
10
 
16
- var __defProp = Object.defineProperty
17
- var __name = (target, value) => __defProp(target, 'name', { value, configurable: true })
11
+ var __defProp = Object.defineProperty;
12
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
18
13
 
19
14
  // src/lib/helpers/parseOptionFlags.ts
20
15
  function parseOptionFlags(flags) {
21
- const match = flags.match(/^-(.+?), --([A-Za-z][\w-]*)(?:\s*(<(.+?)>|\[(.+?)]))?$/)
16
+ const match = flags.match(/^-(.+?), --([A-Za-z][\w-]*)(?:\s*(<(.+?)>|\[(.+?)]))?$/);
22
17
  if (!match) {
23
- throw new Error(`Invalid option format: ${flags}`)
18
+ throw new Error(`Invalid option format: ${flags}`);
24
19
  }
25
- const short = match[1]
20
+ const short = match[1];
26
21
  if (short.length !== 1) {
27
- throw new Error(`Expected short name to be a single character. Got: -${short}`)
22
+ throw new Error(`Expected short name to be a single character. Got: -${short}`);
28
23
  }
29
- const long = match[2]
30
- const argName = (match[4] || match[5])?.replace(/\.{3}$/, '') || void 0
31
- const name = long.split('-').reduce((str, word) => str + word[0].toUpperCase() + word.slice(1))
24
+ const long = match[2];
25
+ const argName = (match[4] || match[5])?.replace(/\.{3}$/, "") || void 0;
26
+ const name = long.split("-").reduce((str, word) => str + word[0].toUpperCase() + word.slice(1));
32
27
  return {
33
28
  short,
34
29
  long,
35
30
  name,
36
- argName,
37
- }
31
+ argName
32
+ };
38
33
  }
39
- __name(parseOptionFlags, 'parseOptionFlags')
34
+ __name(parseOptionFlags, "parseOptionFlags");
40
35
 
41
36
  // src/lib/helpers/getCommandAndAncestors.ts
42
37
  function getCommandAndAncestors(cmd) {
43
- const result = []
44
- let command = cmd
38
+ const result = [];
39
+ let command = cmd;
45
40
  for (; command; command = command.parent) {
46
- result.push(command)
41
+ result.push(command);
47
42
  }
48
- return result
43
+ return result;
49
44
  }
50
- __name(getCommandAndAncestors, 'getCommandAndAncestors')
45
+ __name(getCommandAndAncestors, "getCommandAndAncestors");
51
46
 
52
47
  // src/lib/helpers/getCommandAncestors.ts
53
48
  function getCommandAncestors(cmd) {
54
- return getCommandAndAncestors(cmd).slice(1)
49
+ return getCommandAndAncestors(cmd).slice(1);
55
50
  }
56
- __name(getCommandAncestors, 'getCommandAncestors')
51
+ __name(getCommandAncestors, "getCommandAncestors");
57
52
 
58
53
  // src/lib/helpers/findOption.ts
59
54
  function findOption(cmd, nameOrShortOrLong) {
60
- return nameOrShortOrLong.startsWith('--')
61
- ? cmd.options.find((o) => o.long === nameOrShortOrLong.slice(2))
62
- : nameOrShortOrLong.startsWith('-')
63
- ? cmd.options.find((o) => o.short === nameOrShortOrLong.slice(1))
64
- : cmd.options.find((o) => o.name === nameOrShortOrLong)
55
+ return nameOrShortOrLong.startsWith("--") ? cmd.options.find((o) => o.long === nameOrShortOrLong.slice(2)) : nameOrShortOrLong.startsWith("-") ? cmd.options.find((o) => o.short === nameOrShortOrLong.slice(1)) : cmd.options.find((o) => o.name === nameOrShortOrLong);
65
56
  }
66
- __name(findOption, 'findOption')
57
+ __name(findOption, "findOption");
67
58
 
68
59
  // ../object/src/entriesOf.ts
69
60
  function entriesOf(obj) {
70
- return Object.entries(obj)
61
+ return Object.entries(obj);
71
62
  }
72
- __name(entriesOf, 'entriesOf')
63
+ __name(entriesOf, "entriesOf");
73
64
 
74
65
  // ../object/src/keysOf.ts
75
66
  function keysOf(obj) {
76
- return Object.keys(obj)
67
+ return Object.keys(obj);
77
68
  }
78
- __name(keysOf, 'keysOf')
69
+ __name(keysOf, "keysOf");
79
70
 
80
71
  // ../object/src/filterObject.ts
81
72
  function filterObject(obj, predicate) {
82
- const accum = {}
73
+ const accum = {};
83
74
  for (const key of keysOf(obj)) {
84
75
  if (predicate(obj[key], key, obj)) {
85
- accum[key] = obj[key]
76
+ accum[key] = obj[key];
86
77
  }
87
78
  }
88
- return accum
79
+ return accum;
89
80
  }
90
- __name(filterObject, 'filterObject')
81
+ __name(filterObject, "filterObject");
91
82
 
92
83
  // ../object/src/objSortKeys.ts
93
84
  function objSortKeys(o, compare) {
94
- const entries = Object.entries(o)
85
+ const entries = Object.entries(o);
95
86
  if (compare) {
96
- entries.sort(compare)
87
+ entries.sort(compare);
97
88
  } else {
98
- entries.sort((a, b) => a[0].localeCompare(b[0]))
89
+ entries.sort((a, b) => a[0].localeCompare(b[0]));
99
90
  }
100
- return Object.fromEntries(entries)
91
+ return Object.fromEntries(entries);
101
92
  }
102
- __name(objSortKeys, 'objSortKeys')
93
+ __name(objSortKeys, "objSortKeys");
103
94
 
104
95
  // ../object/src/valuesOf.ts
105
96
  function valuesOf(obj) {
106
- return Object.values(obj)
97
+ return Object.values(obj);
107
98
  }
108
- __name(valuesOf, 'valuesOf')
99
+ __name(valuesOf, "valuesOf");
109
100
 
110
101
  // src/lib/helpers/findCommand.ts
111
102
  function findCommand(cmd, nameOrAlias) {
112
- return cmd.commands[nameOrAlias] ?? valuesOf(cmd.commands).find((c) => c.aliases.includes(nameOrAlias))
103
+ return cmd.commands[nameOrAlias] ?? valuesOf(cmd.commands).find((c) => c.aliases.includes(nameOrAlias));
113
104
  }
114
- __name(findCommand, 'findCommand')
105
+ __name(findCommand, "findCommand");
115
106
 
116
107
  // ../decorators/src/assertDescriptorValueIsFunction.ts
117
108
  function assertDescriptorValueIsFunction(key, descriptor) {
118
- if (!(typeof descriptor.value === 'function' && descriptor.value !== Function.prototype)) {
119
- throw new TypeError(`"value" not a function for ${key} with descriptor: ${JSON.stringify(descriptor)}.`)
109
+ if (!(typeof descriptor.value === "function" && descriptor.value !== Function.prototype)) {
110
+ throw new TypeError(`"value" not a function for ${key} with descriptor: ${JSON.stringify(descriptor)}.`);
120
111
  }
121
112
  }
122
- __name(assertDescriptorValueIsFunction, 'assertDescriptorValueIsFunction')
113
+ __name(assertDescriptorValueIsFunction, "assertDescriptorValueIsFunction");
123
114
 
124
115
  // ../map/src/mapGetOrDefault.ts
125
116
  function mapGetOrDefault(map, key, factory) {
126
- let value = map.get(key)
117
+ let value = map.get(key);
127
118
  if (value !== void 0 || map.has(key)) {
128
- return value
119
+ return value;
129
120
  }
130
- value = factory(key, map)
131
- map.set(key, value)
132
- return value
121
+ value = factory(key, map);
122
+ map.set(key, value);
123
+ return value;
133
124
  }
134
- __name(mapGetOrDefault, 'mapGetOrDefault')
125
+ __name(mapGetOrDefault, "mapGetOrDefault");
135
126
 
136
127
  // ../map/src/TimeoutWeakMap.ts
137
128
  var TimeoutWeakMap = class {
138
129
  static {
139
- __name(this, 'TimeoutWeakMap')
130
+ __name(this, "TimeoutWeakMap");
140
131
  }
141
- timeoutMs
142
- wmap = /* @__PURE__ */ new WeakMap()
132
+ timeoutMs;
133
+ wmap = /* @__PURE__ */ new WeakMap();
143
134
  /**
144
- * @param timeoutMs Default timeout in milliseconds for entries
145
- */
135
+ * @param timeoutMs Default timeout in milliseconds for entries
136
+ */
146
137
  constructor(timeoutMs) {
147
- this.timeoutMs = timeoutMs
138
+ this.timeoutMs = timeoutMs;
148
139
  }
149
140
  /**
150
- * Retrieves the value for the given key and refreshes its timeout.
151
- *
152
- * @param key The key to retrieve
153
- * @returns The value if found, undefined otherwise
154
- */
141
+ * Retrieves the value for the given key and refreshes its timeout.
142
+ *
143
+ * @param key The key to retrieve
144
+ * @returns The value if found, undefined otherwise
145
+ */
155
146
  get(key) {
156
- const vt = this.wmap.get(key)
147
+ const vt = this.wmap.get(key);
157
148
  if (!vt) {
158
- return void 0
149
+ return void 0;
159
150
  }
160
- const [value, timeout] = vt
161
- timeout.refresh()
162
- return value
151
+ const [value, timeout] = vt;
152
+ timeout.refresh();
153
+ return value;
163
154
  }
164
155
  /**
165
- * Sets a key-value pair with an optional custom timeout.
166
- *
167
- * @param key The key to set
168
- * @param value The value to associate with the key
169
- * @param timeoutMs Optional timeout override for this entry
170
- * @returns This instance for chaining
171
- */
156
+ * Sets a key-value pair with an optional custom timeout.
157
+ *
158
+ * @param key The key to set
159
+ * @param value The value to associate with the key
160
+ * @param timeoutMs Optional timeout override for this entry
161
+ * @returns This instance for chaining
162
+ */
172
163
  set(key, value, timeoutMs) {
173
164
  this.wmap.set(key, [
174
165
  value,
175
166
  setTimeout(() => {
176
- this.delete(key)
177
- }, timeoutMs ?? this.timeoutMs).unref(),
178
- ])
179
- return this
167
+ this.delete(key);
168
+ }, timeoutMs ?? this.timeoutMs).unref()
169
+ ]);
170
+ return this;
180
171
  }
181
172
  /**
182
- * Removes a key-value pair and clears its timeout.
183
- *
184
- * @param key The key to delete
185
- * @returns True if the key existed and was deleted, false otherwise
186
- */
173
+ * Removes a key-value pair and clears its timeout.
174
+ *
175
+ * @param key The key to delete
176
+ * @returns True if the key existed and was deleted, false otherwise
177
+ */
187
178
  delete(key) {
188
- const vt = this.wmap.get(key)
179
+ const vt = this.wmap.get(key);
189
180
  if (!vt) {
190
- return false
181
+ return false;
191
182
  }
192
- const timeout = vt[1]
193
- clearTimeout(timeout)
194
- return this.wmap.delete(key)
183
+ const timeout = vt[1];
184
+ clearTimeout(timeout);
185
+ return this.wmap.delete(key);
195
186
  }
196
187
  /**
197
- * Checks if a key exists in the map.
198
- * Does not refresh the timeout.
199
- *
200
- * @param key The key to check
201
- * @returns True if the key exists, false otherwise
202
- */
188
+ * Checks if a key exists in the map.
189
+ * Does not refresh the timeout.
190
+ *
191
+ * @param key The key to check
192
+ * @returns True if the key exists, false otherwise
193
+ */
203
194
  has(key) {
204
- return this.wmap.has(key)
195
+ return this.wmap.has(key);
205
196
  }
206
197
  /**
207
- * Loads multiple key-value pairs into the map.
208
- *
209
- * @param entries Iterable of key-value pairs to load
210
- * @param timeoutMs Optional timeout override for all entries
211
- * @returns This instance for chaining
212
- */
198
+ * Loads multiple key-value pairs into the map.
199
+ *
200
+ * @param entries Iterable of key-value pairs to load
201
+ * @param timeoutMs Optional timeout override for all entries
202
+ * @returns This instance for chaining
203
+ */
213
204
  load(entries, timeoutMs) {
214
205
  for (const [key, value] of entries) {
215
- this.set(key, value, timeoutMs)
206
+ this.set(key, value, timeoutMs);
216
207
  }
217
- return this
208
+ return this;
218
209
  }
219
210
  /**
220
- * Updates an existing value or creates a new one using an update function.
221
- *
222
- * @param key The key to update
223
- * @param update Function that receives the current value and returns the new value
224
- * @returns This instance for chaining
225
- */
211
+ * Updates an existing value or creates a new one using an update function.
212
+ *
213
+ * @param key The key to update
214
+ * @param update Function that receives the current value and returns the new value
215
+ * @returns This instance for chaining
216
+ */
226
217
  update(key, update) {
227
- return this.set(key, update(this.get(key), key, this))
218
+ return this.set(key, update(this.get(key), key, this));
228
219
  }
229
220
  /**
230
- * Gets a value or creates it using a factory function if it doesn't exist.
231
- * Refreshes timeout if the value exists.
232
- *
233
- * @param key The key to get or create
234
- * @param factory Function to create the value if it doesn't exist
235
- * @param timeoutMs Optional timeout override for new entries
236
- * @returns The existing or newly created value
237
- */
221
+ * Gets a value or creates it using a factory function if it doesn't exist.
222
+ * Refreshes timeout if the value exists.
223
+ *
224
+ * @param key The key to get or create
225
+ * @param factory Function to create the value if it doesn't exist
226
+ * @param timeoutMs Optional timeout override for new entries
227
+ * @returns The existing or newly created value
228
+ */
238
229
  getOrDefault(key, factory, timeoutMs) {
239
- const vt = this.wmap.get(key)
230
+ const vt = this.wmap.get(key);
240
231
  if (vt) {
241
- const [value, timeout] = vt
242
- timeout.refresh()
243
- return value
232
+ const [value, timeout] = vt;
233
+ timeout.refresh();
234
+ return value;
244
235
  } else {
245
- const value = factory(key, this)
246
- this.set(key, value, timeoutMs)
247
- return value
236
+ const value = factory(key, this);
237
+ this.set(key, value, timeoutMs);
238
+ return value;
248
239
  }
249
240
  }
250
- }
241
+ };
251
242
  function memoizeSync(arg = {}) {
252
- const opts =
253
- typeof arg === 'object'
254
- ? arg
255
- : {
256
- maxAge: typeof arg === 'number' ? arg : ms(arg),
257
- }
243
+ const opts = typeof arg === "object" ? arg : {
244
+ maxAge: typeof arg === "number" ? arg : ms(arg)
245
+ };
258
246
  return /* @__PURE__ */ __name(function decorator(target, key, descriptor) {
259
247
  if (!descriptor) {
260
- throw new TypeError('descriptor is undefined')
248
+ throw new TypeError("descriptor is undefined");
261
249
  }
262
- const orig = descriptor.value
263
- assertDescriptorValueIsFunction(key, descriptor)
250
+ const orig = descriptor.value;
251
+ assertDescriptorValueIsFunction(key, descriptor);
264
252
  const options = {
265
253
  length: false,
266
- ...opts,
267
- }
254
+ ...opts
255
+ };
268
256
  if (opts.instancesShareCache) {
269
- Reflect.deleteProperty(options, 'instancesShareCache')
270
- descriptor.value = memoizee(orig, options)
257
+ Reflect.deleteProperty(options, "instancesShareCache");
258
+ descriptor.value = memoizee(orig, options);
271
259
  } else {
272
- const wmap = /* @__PURE__ */ new WeakMap()
273
- descriptor.value = function (...args) {
274
- const memoized = mapGetOrDefault(wmap, this, () => memoizee(orig, options))
275
- return memoized.apply(this, args)
276
- }
260
+ const wmap = /* @__PURE__ */ new WeakMap();
261
+ descriptor.value = function(...args) {
262
+ const memoized = mapGetOrDefault(wmap, this, () => memoizee(orig, options));
263
+ return memoized.apply(this, args);
264
+ };
277
265
  }
278
- return descriptor
279
- }, 'decorator')
266
+ return descriptor;
267
+ }, "decorator");
280
268
  }
281
- __name(memoizeSync, 'memoizeSync')
269
+ __name(memoizeSync, "memoizeSync");
282
270
  function lazyProp(targetOrTimeout, key, descriptor) {
283
- if (typeof targetOrTimeout === 'number' || typeof targetOrTimeout === 'string') {
284
- const maxAge = typeof targetOrTimeout === 'number' ? targetOrTimeout : ms(targetOrTimeout)
285
- return createLazyPropDecorator(new TimeoutWeakMap(maxAge))
271
+ if (typeof targetOrTimeout === "number" || typeof targetOrTimeout === "string") {
272
+ const maxAge = typeof targetOrTimeout === "number" ? targetOrTimeout : ms(targetOrTimeout);
273
+ return createLazyPropDecorator(new TimeoutWeakMap(maxAge));
286
274
  } else {
287
- const decorator = createLazyPropDecorator(/* @__PURE__ */ new WeakMap())
288
- return decorator(targetOrTimeout, key, descriptor)
275
+ const decorator = createLazyPropDecorator(/* @__PURE__ */ new WeakMap());
276
+ return decorator(targetOrTimeout, key, descriptor);
289
277
  }
290
278
  }
291
- __name(lazyProp, 'lazyProp')
279
+ __name(lazyProp, "lazyProp");
292
280
  function createLazyPropDecorator(map) {
293
- return function (target, key, descriptor) {
294
- const { get, value } = descriptor
281
+ return function(target, key, descriptor) {
282
+ const { get, value } = descriptor;
295
283
  if (isFunction(get)) {
296
- descriptor.get = function () {
297
- return mapGetOrDefault(map, this, () => get.call(this))
298
- }
299
- return descriptor
284
+ descriptor.get = function() {
285
+ return mapGetOrDefault(map, this, () => get.call(this));
286
+ };
287
+ return descriptor;
300
288
  }
301
289
  if (isFunction(value)) {
302
- return memoizeSync()(target, key, descriptor)
290
+ return memoizeSync()(target, key, descriptor);
303
291
  }
304
- throw new TypeError('neither "get" nor "value" are functions')
305
- }
292
+ throw new TypeError('neither "get" nor "value" are functions');
293
+ };
306
294
  }
307
- __name(createLazyPropDecorator, 'createLazyPropDecorator')
295
+ __name(createLazyPropDecorator, "createLazyPropDecorator");
308
296
 
309
297
  // src/lib/Help.ts
310
298
  function _ts_decorate(decorators, target, key, desc) {
311
- var c = arguments.length,
312
- r = c < 3 ? target : desc === null ? (desc = Object.getOwnPropertyDescriptor(target, key)) : desc,
313
- d
314
- if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function')
315
- r = Reflect.decorate(decorators, target, key, desc)
316
- else
317
- for (var i = decorators.length - 1; i >= 0; i--)
318
- if ((d = decorators[i])) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r
319
- return (c > 3 && r && Object.defineProperty(target, key, r), r)
299
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
300
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
301
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
302
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
320
303
  }
321
- __name(_ts_decorate, '_ts_decorate')
304
+ __name(_ts_decorate, "_ts_decorate");
322
305
  function _ts_metadata(k, v) {
323
- if (typeof Reflect === 'object' && typeof Reflect.metadata === 'function') return Reflect.metadata(k, v)
306
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
324
307
  }
325
- __name(_ts_metadata, '_ts_metadata')
308
+ __name(_ts_metadata, "_ts_metadata");
326
309
  var Help = class {
327
310
  static {
328
- __name(this, 'Help')
311
+ __name(this, "Help");
329
312
  }
330
- cmd
313
+ cmd;
331
314
  /** output helpWidth, long lines are wrapped to fit */
332
- helpWidth = process.stdout.isTTY ? process.stdout.columns : 80
333
- minWidthToWrap = 40
334
- sortSubcommands = true
335
- sortOptions = true
336
- usageDisplayOptionsAs = '[opts]'
337
- usageDisplaySubcommandAs = '[cmd]'
315
+ helpWidth = process.stdout.isTTY ? process.stdout.columns : 80;
316
+ minWidthToWrap = 40;
317
+ sortSubcommands = true;
318
+ sortOptions = true;
319
+ usageDisplayOptionsAs = "[opts]";
320
+ usageDisplaySubcommandAs = "[cmd]";
338
321
  constructor(cmd) {
339
- this.cmd = cmd
340
- Object.defineProperty(this, 'cmd', {
341
- enumerable: false,
342
- })
322
+ this.cmd = cmd;
323
+ Object.defineProperty(this, "cmd", {
324
+ enumerable: false
325
+ });
343
326
  }
344
327
  /**
345
- * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
346
- */
328
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
329
+ */
347
330
  visibleCommands() {
348
- const res = Object.values(this.cmd.commands).filter((c) => !c.hidden)
331
+ const res = Object.values(this.cmd.commands).filter((c) => !c.hidden);
349
332
  if (this.sortSubcommands) {
350
- res.sort((a, b) => a.name.localeCompare(b.name))
333
+ res.sort((a, b) => a.name.localeCompare(b.name));
351
334
  }
352
- return res
335
+ return res;
353
336
  }
354
337
  /**
355
- * Compare options for sort.
356
- */
338
+ * Compare options for sort.
339
+ */
357
340
  compareOptions(a, b) {
358
- const getSortKey = /* @__PURE__ */ __name(
359
- (option) => (option.short ? option.short.replace(/^-/, '') : option.long.replace(/^--/, '')),
360
- 'getSortKey'
361
- )
362
- return getSortKey(a).localeCompare(getSortKey(b))
341
+ const getSortKey = /* @__PURE__ */ __name((option) => (
342
+ // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated.
343
+ option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "")
344
+ ), "getSortKey");
345
+ return getSortKey(a).localeCompare(getSortKey(b));
363
346
  }
364
347
  /**
365
- * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
366
- */
348
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
349
+ */
367
350
  visibleOptions() {
368
- const res = this.cmd.options.filter((option) => !option.hidden)
351
+ const res = this.cmd.options.filter((option) => !option.hidden);
369
352
  if (this.sortOptions) {
370
- res.sort(this.compareOptions)
353
+ res.sort(this.compareOptions);
371
354
  }
372
- return res
355
+ return res;
373
356
  }
374
357
  /**
375
- * Get an array of the arguments if any have a description.
376
- */
358
+ * Get an array of the arguments if any have a description.
359
+ */
377
360
  visibleArguments() {
378
- return this.cmd.arguments.slice()
361
+ return this.cmd.arguments.slice();
379
362
  }
380
363
  /**
381
- * Get the command term to show in the list of subcommands.
382
- */
364
+ * Get the command term to show in the list of subcommands.
365
+ */
383
366
  subcommandTerm(sub) {
384
- const args = sub.arguments.map((arg) => arg.usage).join(' ')
385
- return (
386
- (sub.aliases[0] ? `${sub.aliases[0].padEnd(this.longestSubcommandAliasLength(), ' ')} | ` : '') +
387
- sub.name +
388
- (sub.options.length ? ` ${this.usageDisplayOptionsAs}` : '') + // simplistic check for non-help option
389
- (args ? ` ${args}` : '')
390
- )
367
+ const args = sub.arguments.map((arg) => arg.usage).join(" ");
368
+ return (sub.aliases[0] ? `${sub.aliases[0].padEnd(this.longestSubcommandAliasLength(), " ")} | ` : "") + sub.name + (sub.options.length ? ` ${this.usageDisplayOptionsAs}` : "") + // simplistic check for non-help option
369
+ (args ? ` ${args}` : "");
391
370
  }
392
371
  /**
393
- * Get the option term to show in the list of options.
394
- */
372
+ * Get the option term to show in the list of options.
373
+ */
395
374
  optionTerm(option) {
396
- return option.flags
375
+ return option.flags;
397
376
  }
398
377
  /**
399
- * Get the argument term to show in the list of arguments.
400
- */
378
+ * Get the argument term to show in the list of arguments.
379
+ */
401
380
  argumentTerm(argument) {
402
- return argument.usage
381
+ return argument.usage;
403
382
  }
404
383
  /**
405
- * Get the longest subcommand primary alias length.
406
- */
384
+ * Get the longest subcommand primary alias length.
385
+ */
407
386
  longestSubcommandAliasLength() {
408
- return Math.max(0, ...this.visibleCommands().map((c) => c.aliases[0]?.length || 0))
387
+ return Math.max(0, ...this.visibleCommands().map((c) => c.aliases[0]?.length || 0));
409
388
  }
410
389
  /**
411
- * Get the longest subcommand term length.
412
- */
390
+ * Get the longest subcommand term length.
391
+ */
413
392
  longestSubcommandTermLength() {
414
- return this.visibleCommands().reduce(
415
- (max, command) => Math.max(max, this.displayWidth(this.styleSubcommandTerm(this.subcommandTerm(command)))),
416
- 0
417
- )
393
+ return this.visibleCommands().reduce((max, command) => Math.max(max, this.displayWidth(this.styleSubcommandTerm(this.subcommandTerm(command)))), 0);
418
394
  }
419
395
  /**
420
- * Get the longest option term length.
421
- */
396
+ * Get the longest option term length.
397
+ */
422
398
  longestOptionTermLength() {
423
- return this.visibleOptions().reduce(
424
- (max, option) => Math.max(max, this.displayWidth(this.styleOptionTerm(this.optionTerm(option)))),
425
- 0
426
- )
399
+ return this.visibleOptions().reduce((max, option) => Math.max(max, this.displayWidth(this.styleOptionTerm(this.optionTerm(option)))), 0);
427
400
  }
428
401
  /**
429
- * Get the longest argument term length.
430
- */
402
+ * Get the longest argument term length.
403
+ */
431
404
  longestArgumentTermLength() {
432
- return this.visibleArguments().reduce(
433
- (max, argument) => Math.max(max, this.displayWidth(this.styleArgumentTerm(this.argumentTerm(argument)))),
434
- 0
435
- )
405
+ return this.visibleArguments().reduce((max, argument) => Math.max(max, this.displayWidth(this.styleArgumentTerm(this.argumentTerm(argument)))), 0);
436
406
  }
437
407
  /**
438
- * Get the command usage to be displayed at the top of the built-in help.
439
- */
408
+ * Get the command usage to be displayed at the top of the built-in help.
409
+ */
440
410
  commandUsage() {
441
- let path = ''
411
+ let path = "";
442
412
  for (let ancestor = this.cmd.parent; ancestor; ancestor = ancestor.parent) {
443
- path = `${ancestor.name} ${path}`
413
+ path = `${ancestor.name} ${path}`;
444
414
  }
445
415
  return `${path + this.cmd.name} ${[
446
- ...(Object.keys(this.cmd.commands).length ? [this.usageDisplaySubcommandAs] : []),
447
- ...(this.cmd.options.length ? [this.usageDisplayOptionsAs] : []),
448
- ...this.cmd.arguments.map((arg) =>
449
- arg.required
450
- ? arg.variadic
451
- ? `<${arg.name}...>`
452
- : `<${arg.name}>`
453
- : arg.variadic
454
- ? `[${arg.name}...]`
455
- : `[${arg.name}]`
456
- ),
457
- ].join(' ')}`.trim()
416
+ ...Object.keys(this.cmd.commands).length ? [
417
+ this.usageDisplaySubcommandAs
418
+ ] : [],
419
+ ...this.cmd.options.length ? [
420
+ this.usageDisplayOptionsAs
421
+ ] : [],
422
+ ...this.cmd.arguments.map((arg) => arg.required ? arg.variadic ? `<${arg.name}...>` : `<${arg.name}>` : arg.variadic ? `[${arg.name}...]` : `[${arg.name}]`)
423
+ ].join(" ")}`.trim();
458
424
  }
459
425
  /**
460
- * Get the description for the command.
461
- */
426
+ * Get the description for the command.
427
+ */
462
428
  commandDescription() {
463
- let res = ''
429
+ let res = "";
464
430
  if (this.cmd.aliases.length) {
465
- res += `Aliases: ${this.cmd.aliases.join(', ')}`
466
- res += '\n\n'
431
+ res += `Aliases: ${this.cmd.aliases.join(", ")}`;
432
+ res += "\n\n";
467
433
  }
468
- res += this.cmd.description
469
- return res
434
+ res += this.cmd.description;
435
+ return res;
470
436
  }
471
437
  /**
472
- * Get the subcommand summary to show in the list of subcommands.
473
- * (Fallback to description for backwards compatibility.)
474
- */
438
+ * Get the subcommand summary to show in the list of subcommands.
439
+ * (Fallback to description for backwards compatibility.)
440
+ */
475
441
  subcommandDescription(sub) {
476
- return (
477
- sub.summary ||
478
- (sub.description?.includes('\n') ? sub.description.trim().split('\n')[0] : sub.description.trim())
479
- )
442
+ return sub.summary || (sub.description?.includes("\n") ? sub.description.trim().split("\n")[0] : sub.description.trim());
480
443
  }
481
444
  /**
482
- * Get the option description to show in the list of options.
483
- */
445
+ * Get the option description to show in the list of options.
446
+ */
484
447
  optionDescription(option) {
485
- const extraInfo = []
448
+ const extraInfo = [];
486
449
  if (option.choices) {
487
- const choices = option.choices.length > 5 ? option.choices.slice(0, 5).concat(['...']) : option.choices
450
+ const choices = option.choices.length > 5 ? option.choices.slice(0, 5).concat([
451
+ "..."
452
+ ]) : option.choices;
488
453
  extraInfo.push(
489
454
  // use stringify to match the display of the default value
490
- `choices: ${choices.join(', ')}`
491
- )
455
+ `choices: ${choices.join(", ")}`
456
+ );
492
457
  }
493
458
  if (option.defaultValue && !(Array.isArray(option.defaultValue) && option.defaultValue.length === 0)) {
494
- extraInfo.push(
495
- `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue).replaceAll('"', '')}`
496
- )
459
+ extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue).replaceAll('"', "")}`);
497
460
  }
498
461
  if (option.env !== void 0) {
499
- extraInfo.push(`env: ${option.env}`)
462
+ extraInfo.push(`env: ${option.env}`);
500
463
  }
501
464
  if (extraInfo.length > 0) {
502
- const extraDescription = `(${extraInfo.join(', ')})`
465
+ const extraDescription = `(${extraInfo.join(", ")})`;
503
466
  if (option.description) {
504
- return `${option.description} ${extraDescription}`
467
+ return `${option.description} ${extraDescription}`;
505
468
  }
506
- return extraDescription
469
+ return extraDescription;
507
470
  }
508
- return option.description ?? ''
471
+ return option.description ?? "";
509
472
  }
510
473
  /**
511
- * Get the argument description to show in the list of arguments.
512
- */
474
+ * Get the argument description to show in the list of arguments.
475
+ */
513
476
  argumentDescription(argument) {
514
- const extraInfo = []
477
+ const extraInfo = [];
515
478
  if (argument.choices) {
516
- const choices = argument.choices.length > 5 ? argument.choices.slice(0, 5).concat(['...']) : argument.choices
479
+ const choices = argument.choices.length > 5 ? argument.choices.slice(0, 5).concat([
480
+ "..."
481
+ ]) : argument.choices;
517
482
  extraInfo.push(
518
483
  // use stringify to match the display of the default value
519
- `choices: ${choices.join(', ')}`
520
- )
484
+ `choices: ${choices.join(", ")}`
485
+ );
521
486
  }
522
487
  if (argument.defaultValue && !(Array.isArray(argument.defaultValue) && argument.defaultValue.length === 0)) {
523
- extraInfo.push(
524
- `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue).replaceAll('"', '')}`
525
- )
488
+ extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue).replaceAll('"', "")}`);
526
489
  }
527
490
  if (extraInfo.length > 0) {
528
- const extraDescription = `(${extraInfo.join(', ')})`
491
+ const extraDescription = `(${extraInfo.join(", ")})`;
529
492
  if (argument.description) {
530
- return `${argument.description} ${extraDescription}`
493
+ return `${argument.description} ${extraDescription}`;
531
494
  }
532
- return extraDescription
495
+ return extraDescription;
533
496
  }
534
- return argument.description ?? ''
497
+ return argument.description ?? "";
535
498
  }
536
499
  /**
537
- * Format a list of items, given a heading and an array of formatted items.
538
- */
500
+ * Format a list of items, given a heading and an array of formatted items.
501
+ */
539
502
  formatItemList(heading, items) {
540
503
  if (items.length === 0) {
541
- return []
504
+ return [];
542
505
  }
543
- return [this.styleTitle(heading), ...items, '']
506
+ return [
507
+ this.styleTitle(heading),
508
+ ...items,
509
+ ""
510
+ ];
544
511
  }
545
512
  /**
546
- * Group items by their help group heading.
547
- */
513
+ * Group items by their help group heading.
514
+ */
548
515
  groupItems(unsortedItems, visibleItems, getGroup) {
549
- const result = /* @__PURE__ */ new Map()
516
+ const result = /* @__PURE__ */ new Map();
550
517
  unsortedItems.forEach((item) => {
551
- const group = getGroup(item)
518
+ const group = getGroup(item);
552
519
  if (!result.has(group)) {
553
- result.set(group, [])
520
+ result.set(group, []);
554
521
  }
555
- })
522
+ });
556
523
  visibleItems.forEach((item) => {
557
- const group = getGroup(item)
524
+ const group = getGroup(item);
558
525
  if (!result.has(group)) {
559
- result.set(group, [])
526
+ result.set(group, []);
560
527
  }
561
- result.get(group).push(item)
562
- })
563
- return result
528
+ result.get(group).push(item);
529
+ });
530
+ return result;
564
531
  }
565
532
  /**
566
- * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
567
- */
533
+ * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
534
+ */
568
535
  displayWidth(str) {
569
- const sgrPattern = /\u001b\[\d*(;\d*)*m/g
570
- return str.replaceAll(sgrPattern, '').length
536
+ const sgrPattern = /\u001b\[\d*(;\d*)*m/g;
537
+ return str.replaceAll(sgrPattern, "").length;
571
538
  }
572
539
  /**
573
- * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
574
- */
540
+ * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
541
+ */
575
542
  styleTitle(str) {
576
- return C.yellow(str)
543
+ return C.yellow(str);
577
544
  }
578
545
  /**
579
- * Style the usage line for displaying in the help. Applies specific styling to different parts like options, commands, and arguments.
580
- */
546
+ * Style the usage line for displaying in the help. Applies specific styling to different parts like options, commands, and arguments.
547
+ */
581
548
  styleUsage(str) {
582
- return str
583
- .split(' ')
584
- .map((word, index, arr) => {
585
- if (word === this.usageDisplaySubcommandAs) {
586
- return C.green(word)
587
- }
588
- if (word === this.usageDisplayOptionsAs) {
589
- return C.blue(word)
590
- }
591
- if (word[0] === '<') {
592
- return C.red(word)
593
- }
594
- if (word[0] === '[') {
595
- return C.cyan(word)
596
- }
597
- if (arr[index + 1]?.startsWith('[')) {
598
- return C.magenta(word)
599
- }
600
- return this.styleCommandText(word)
601
- })
602
- .join(' ')
549
+ return str.split(" ").map((word, index, arr) => {
550
+ if (word === this.usageDisplaySubcommandAs) {
551
+ return C.green(word);
552
+ }
553
+ if (word === this.usageDisplayOptionsAs) {
554
+ return C.blue(word);
555
+ }
556
+ if (word[0] === "<") {
557
+ return C.red(word);
558
+ }
559
+ if (word[0] === "[") {
560
+ return C.cyan(word);
561
+ }
562
+ if (arr[index + 1]?.startsWith("[")) {
563
+ return C.magenta(word);
564
+ }
565
+ return this.styleCommandText(word);
566
+ }).join(" ");
603
567
  }
604
568
  /**
605
- * Style command descriptions for display in help output.
606
- */
569
+ * Style command descriptions for display in help output.
570
+ */
607
571
  styleCommandDescription(str) {
608
- return this.styleDescriptionText(str)
572
+ return this.styleDescriptionText(str);
609
573
  }
610
574
  /**
611
- * Style option descriptions for display in help output.
612
- */
575
+ * Style option descriptions for display in help output.
576
+ */
613
577
  styleOptionDescription(str) {
614
- return C.gray(this.styleDescriptionText(str))
578
+ return C.gray(this.styleDescriptionText(str));
615
579
  }
616
580
  /**
617
- * Style subcommand descriptions for display in help output.
618
- */
581
+ * Style subcommand descriptions for display in help output.
582
+ */
619
583
  styleSubcommandDescription(str) {
620
- return this.styleDescriptionText(str)
584
+ return this.styleDescriptionText(str);
621
585
  }
622
586
  /**
623
- * Style argument descriptions for display in help output.
624
- */
587
+ * Style argument descriptions for display in help output.
588
+ */
625
589
  styleArgumentDescription(str) {
626
- return C.gray(this.styleDescriptionText(str))
590
+ return C.gray(this.styleDescriptionText(str));
627
591
  }
628
592
  /**
629
- * Base style used by descriptions. Override in subclass to apply custom formatting.
630
- */
593
+ * Base style used by descriptions. Override in subclass to apply custom formatting.
594
+ */
631
595
  styleDescriptionText(str) {
632
- return C.gray(str)
596
+ return C.gray(str);
633
597
  }
634
598
  /**
635
- * Style option terms (flags) for display in help output.
636
- */
599
+ * Style option terms (flags) for display in help output.
600
+ */
637
601
  styleOptionTerm(str) {
638
- return this.styleOptionText(str)
602
+ return this.styleOptionText(str);
639
603
  }
640
604
  /**
641
- * Style subcommand terms for display in help output. Applies specific styling to different parts like options and arguments.
642
- */
605
+ * Style subcommand terms for display in help output. Applies specific styling to different parts like options and arguments.
606
+ */
643
607
  styleSubcommandTerm(str) {
644
- const res = str
645
- .split(' ')
646
- .map((word) => {
647
- if (word === this.usageDisplayOptionsAs) {
648
- return C.dim(word)
649
- }
650
- if (word[0] === '[' || word[0] === '<') {
651
- return C.dim(word)
652
- }
653
- return this.styleSubcommandText(word)
654
- })
655
- .join(' ')
656
- const split = res.split('|')
608
+ const res = str.split(" ").map((word) => {
609
+ if (word === this.usageDisplayOptionsAs) {
610
+ return C.dim(word);
611
+ }
612
+ if (word[0] === "[" || word[0] === "<") {
613
+ return C.dim(word);
614
+ }
615
+ return this.styleSubcommandText(word);
616
+ }).join(" ");
617
+ const split = res.split("|");
657
618
  if (split.length === 1) {
658
- return res
619
+ return res;
659
620
  }
660
- split[0] = C.green(split[0])
661
- return split.join('|')
621
+ split[0] = C.green(split[0]);
622
+ return split.join("|");
662
623
  }
663
624
  /**
664
- * Style argument terms for display in help output.
665
- */
625
+ * Style argument terms for display in help output.
626
+ */
666
627
  styleArgumentTerm(str) {
667
- return this.styleArgumentText(str)
628
+ return this.styleArgumentText(str);
668
629
  }
669
630
  /**
670
- * Base style used in terms and usage for options. Override in subclass to apply custom formatting.
671
- */
631
+ * Base style used in terms and usage for options. Override in subclass to apply custom formatting.
632
+ */
672
633
  styleOptionText(str) {
673
- return str
634
+ return str;
674
635
  }
675
636
  /**
676
- * Base style used in terms and usage for arguments. Override in subclass to apply custom formatting.
677
- */
637
+ * Base style used in terms and usage for arguments. Override in subclass to apply custom formatting.
638
+ */
678
639
  styleArgumentText(str) {
679
- return str
640
+ return str;
680
641
  }
681
642
  /**
682
- * Base style used in terms and usage for subcommands. Override in subclass to apply custom formatting.
683
- */
643
+ * Base style used in terms and usage for subcommands. Override in subclass to apply custom formatting.
644
+ */
684
645
  styleSubcommandText(str) {
685
- return str
646
+ return str;
686
647
  }
687
648
  /**
688
- * Base style used in terms and usage for commands. Override in subclass to apply custom formatting.
689
- */
649
+ * Base style used in terms and usage for commands. Override in subclass to apply custom formatting.
650
+ */
690
651
  styleCommandText(str) {
691
- return str
652
+ return str;
692
653
  }
693
654
  /**
694
- * Calculate the pad width from the maximum term length.
695
- */
655
+ * Calculate the pad width from the maximum term length.
656
+ */
696
657
  padWidth() {
697
- return Math.max(
698
- this.longestOptionTermLength(),
699
- this.longestSubcommandTermLength(),
700
- this.longestArgumentTermLength()
701
- )
658
+ return Math.max(this.longestOptionTermLength(), this.longestSubcommandTermLength(), this.longestArgumentTermLength());
702
659
  }
703
660
  /**
704
- * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
705
- */
661
+ * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
662
+ */
706
663
  preformatted(str) {
707
- return /\n[^\S\n\r]/.test(str)
664
+ return /\n[^\S\n\r]/.test(str);
708
665
  }
709
666
  /**
710
- * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
711
- *
712
- * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
713
- * TTT DDD DDDD
714
- * DD DDD
715
- */
667
+ * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
668
+ *
669
+ * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
670
+ * TTT DDD DDDD
671
+ * DD DDD
672
+ */
716
673
  formatItem(term, termWidth, description) {
717
- const itemIndent = 2
718
- const itemIndentStr = ' '.repeat(itemIndent)
674
+ const itemIndent = 2;
675
+ const itemIndentStr = " ".repeat(itemIndent);
719
676
  if (!description) {
720
- return itemIndentStr + term
677
+ return itemIndentStr + term;
721
678
  }
722
- const paddedTerm = term.padEnd(termWidth + term.length - this.displayWidth(term))
723
- const spacerWidth = 2
724
- const helpWidth = this.helpWidth
725
- const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent
726
- let formattedDescription
679
+ const paddedTerm = term.padEnd(termWidth + term.length - this.displayWidth(term));
680
+ const spacerWidth = 2;
681
+ const helpWidth = this.helpWidth;
682
+ const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
683
+ let formattedDescription;
727
684
  if (remainingWidth < this.minWidthToWrap || this.preformatted(description)) {
728
- formattedDescription = description
685
+ formattedDescription = description;
729
686
  } else {
730
- const wrappedDescription = this.boxWrap(description, remainingWidth)
731
- formattedDescription = wrappedDescription.replaceAll(
732
- '\n',
733
- `
734
- ${' '.repeat(termWidth + spacerWidth)}`
735
- )
736
- }
737
- return (
738
- itemIndentStr +
739
- paddedTerm +
740
- ' '.repeat(spacerWidth) +
741
- formattedDescription.replaceAll(
742
- '\n',
743
- `
744
- ${itemIndentStr}`
745
- )
746
- )
687
+ const wrappedDescription = this.boxWrap(description, remainingWidth);
688
+ formattedDescription = wrappedDescription.replaceAll("\n", `
689
+ ${" ".repeat(termWidth + spacerWidth)}`);
690
+ }
691
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replaceAll("\n", `
692
+ ${itemIndentStr}`);
747
693
  }
748
694
  /**
749
- * Wrap a string at whitespace, preserving existing line breaks.
750
- * Wrapping is skipped if the width is less than `minWidthToWrap`.
751
- */
695
+ * Wrap a string at whitespace, preserving existing line breaks.
696
+ * Wrapping is skipped if the width is less than `minWidthToWrap`.
697
+ */
752
698
  boxWrap(str, width) {
753
699
  if (width < this.minWidthToWrap) {
754
- return str
700
+ return str;
755
701
  }
756
- const rawLines = str.split(/\r\n|\n/)
757
- const chunkPattern = /\s*\S+/g
758
- const wrappedLines = []
702
+ const rawLines = str.split(/\r\n|\n/);
703
+ const chunkPattern = /\s*\S+/g;
704
+ const wrappedLines = [];
759
705
  rawLines.forEach((line) => {
760
- const chunks = line.match(chunkPattern)
706
+ const chunks = line.match(chunkPattern);
761
707
  if (chunks === null) {
762
- wrappedLines.push('')
763
- return
708
+ wrappedLines.push("");
709
+ return;
764
710
  }
765
- let sumChunks = [chunks.shift()]
766
- let sumWidth = this.displayWidth(sumChunks[0])
711
+ let sumChunks = [
712
+ chunks.shift()
713
+ ];
714
+ let sumWidth = this.displayWidth(sumChunks[0]);
767
715
  chunks.forEach((chunk) => {
768
- const visibleWidth = this.displayWidth(chunk)
716
+ const visibleWidth = this.displayWidth(chunk);
769
717
  if (sumWidth + visibleWidth <= width) {
770
- sumChunks.push(chunk)
771
- sumWidth += visibleWidth
772
- return
718
+ sumChunks.push(chunk);
719
+ sumWidth += visibleWidth;
720
+ return;
773
721
  }
774
- wrappedLines.push(sumChunks.join(''))
775
- const nextChunk = chunk.trimStart()
776
- sumChunks = [nextChunk]
777
- sumWidth = this.displayWidth(nextChunk)
778
- })
779
- wrappedLines.push(sumChunks.join(''))
780
- })
781
- return wrappedLines.join('\n')
722
+ wrappedLines.push(sumChunks.join(""));
723
+ const nextChunk = chunk.trimStart();
724
+ sumChunks = [
725
+ nextChunk
726
+ ];
727
+ sumWidth = this.displayWidth(nextChunk);
728
+ });
729
+ wrappedLines.push(sumChunks.join(""));
730
+ });
731
+ return wrappedLines.join("\n");
782
732
  }
783
733
  /**
784
- * Generate the built-in help text.
785
- */
734
+ * Generate the built-in help text.
735
+ */
786
736
  render() {
787
- let output = [`${this.styleTitle('Usage:')} ${this.styleUsage(this.commandUsage())}`, '']
788
- const des = this.commandDescription()
737
+ let output = [
738
+ `${this.styleTitle("Usage:")} ${this.styleUsage(this.commandUsage())}`,
739
+ ""
740
+ ];
741
+ const des = this.commandDescription();
789
742
  if (des.length > 0) {
790
- output = output.concat([this.boxWrap(this.styleCommandDescription(des), this.helpWidth), ''])
791
- }
792
- const argumentList = this.visibleArguments().map((argument) =>
793
- this.formatItem(
794
- this.styleArgumentTerm(this.argumentTerm(argument)),
795
- this.padWidth(),
796
- this.styleArgumentDescription(this.argumentDescription(argument))
797
- )
798
- )
799
- output = output.concat(this.formatItemList('Arguments:', argumentList))
800
- const optionGroups = this.groupItems(
801
- this.cmd.options,
802
- this.visibleOptions(),
803
- (option) => option.group ?? 'Options:'
804
- )
743
+ output = output.concat([
744
+ this.boxWrap(this.styleCommandDescription(des), this.helpWidth),
745
+ ""
746
+ ]);
747
+ }
748
+ const argumentList = this.visibleArguments().map((argument) => this.formatItem(this.styleArgumentTerm(this.argumentTerm(argument)), this.padWidth(), this.styleArgumentDescription(this.argumentDescription(argument))));
749
+ output = output.concat(this.formatItemList("Arguments:", argumentList));
750
+ const optionGroups = this.groupItems(this.cmd.options, this.visibleOptions(), (option) => option.group ?? "Options:");
805
751
  optionGroups.forEach((options, group) => {
806
- const optionList = options.map((option) =>
807
- this.formatItem(
808
- this.styleOptionTerm(this.optionTerm(option)),
809
- this.padWidth(),
810
- this.styleOptionDescription(this.optionDescription(option))
811
- )
812
- )
813
- output = output.concat(this.formatItemList(group, optionList))
814
- })
815
- const commandGroups = this.groupItems(
816
- Object.values(this.cmd.commands),
817
- this.visibleCommands(),
818
- (sub) => sub.group || 'Commands:'
819
- )
752
+ const optionList = options.map((option) => this.formatItem(this.styleOptionTerm(this.optionTerm(option)), this.padWidth(), this.styleOptionDescription(this.optionDescription(option))));
753
+ output = output.concat(this.formatItemList(group, optionList));
754
+ });
755
+ const commandGroups = this.groupItems(Object.values(this.cmd.commands), this.visibleCommands(), (sub) => sub.group || "Commands:");
820
756
  commandGroups.forEach((commands, group) => {
821
- const commandList = commands.map((sub) =>
822
- this.formatItem(
823
- this.styleSubcommandTerm(this.subcommandTerm(sub)),
824
- this.padWidth(),
825
- this.styleSubcommandDescription(this.subcommandDescription(sub))
826
- )
827
- )
828
- output = output.concat(this.formatItemList(group, commandList))
829
- })
830
- return output.join('\n')
757
+ const commandList = commands.map((sub) => this.formatItem(this.styleSubcommandTerm(this.subcommandTerm(sub)), this.padWidth(), this.styleSubcommandDescription(this.subcommandDescription(sub))));
758
+ output = output.concat(this.formatItemList(group, commandList));
759
+ });
760
+ return output.join("\n");
761
+ }
762
+ };
763
+ _ts_decorate([
764
+ lazyProp,
765
+ _ts_metadata("design:type", Function),
766
+ _ts_metadata("design:paramtypes", []),
767
+ _ts_metadata("design:returntype", Array)
768
+ ], Help.prototype, "visibleCommands", null);
769
+ _ts_decorate([
770
+ lazyProp,
771
+ _ts_metadata("design:type", Function),
772
+ _ts_metadata("design:paramtypes", []),
773
+ _ts_metadata("design:returntype", Array)
774
+ ], Help.prototype, "visibleOptions", null);
775
+ _ts_decorate([
776
+ lazyProp,
777
+ _ts_metadata("design:type", Function),
778
+ _ts_metadata("design:paramtypes", []),
779
+ _ts_metadata("design:returntype", Array)
780
+ ], Help.prototype, "visibleArguments", null);
781
+ _ts_decorate([
782
+ lazyProp,
783
+ _ts_metadata("design:type", Function),
784
+ _ts_metadata("design:paramtypes", []),
785
+ _ts_metadata("design:returntype", Number)
786
+ ], Help.prototype, "longestSubcommandAliasLength", null);
787
+ _ts_decorate([
788
+ lazyProp,
789
+ _ts_metadata("design:type", Function),
790
+ _ts_metadata("design:paramtypes", []),
791
+ _ts_metadata("design:returntype", Number)
792
+ ], Help.prototype, "longestSubcommandTermLength", null);
793
+ _ts_decorate([
794
+ lazyProp,
795
+ _ts_metadata("design:type", Function),
796
+ _ts_metadata("design:paramtypes", []),
797
+ _ts_metadata("design:returntype", Number)
798
+ ], Help.prototype, "longestOptionTermLength", null);
799
+ _ts_decorate([
800
+ lazyProp,
801
+ _ts_metadata("design:type", Function),
802
+ _ts_metadata("design:paramtypes", []),
803
+ _ts_metadata("design:returntype", Number)
804
+ ], Help.prototype, "longestArgumentTermLength", null);
805
+ _ts_decorate([
806
+ lazyProp,
807
+ _ts_metadata("design:type", Function),
808
+ _ts_metadata("design:paramtypes", []),
809
+ _ts_metadata("design:returntype", Number)
810
+ ], Help.prototype, "padWidth", null);
811
+
812
+ // src/lib/internal/isOptionLike.ts
813
+ function isOptionLike(word) {
814
+ return word.startsWith("-") && word !== "-" && !/^-(\d+\.?\d*|\.\d+)$/.test(word);
815
+ }
816
+ __name(isOptionLike, "isOptionLike");
817
+
818
+ // src/lib/internal/checkOptionValues.ts
819
+ function checkOptionValues(argv, options) {
820
+ const out = [];
821
+ const report = {
822
+ errors: [],
823
+ invalid: /* @__PURE__ */ new Set()
824
+ };
825
+ for (let i = 0; i < argv.length; i++) {
826
+ const word = argv[i];
827
+ if (word === "--") {
828
+ out.push(...argv.slice(i));
829
+ break;
830
+ }
831
+ const { keep, read } = word.startsWith("--") ? checkLong(word, argv[i + 1], options, report) : isOptionLike(word) ? checkShort(word, argv[i + 1], options, report) : {
832
+ keep: [
833
+ word
834
+ ],
835
+ read: 1
836
+ };
837
+ out.push(...keep);
838
+ i += read - 1;
831
839
  }
840
+ return {
841
+ argv: out,
842
+ ...report
843
+ };
832
844
  }
833
- _ts_decorate(
834
- [
835
- lazyProp,
836
- _ts_metadata('design:type', Function),
837
- _ts_metadata('design:paramtypes', []),
838
- _ts_metadata('design:returntype', Array),
839
- ],
840
- Help.prototype,
841
- 'visibleCommands',
842
- null
843
- )
844
- _ts_decorate(
845
- [
846
- lazyProp,
847
- _ts_metadata('design:type', Function),
848
- _ts_metadata('design:paramtypes', []),
849
- _ts_metadata('design:returntype', Array),
850
- ],
851
- Help.prototype,
852
- 'visibleOptions',
853
- null
854
- )
855
- _ts_decorate(
856
- [
857
- lazyProp,
858
- _ts_metadata('design:type', Function),
859
- _ts_metadata('design:paramtypes', []),
860
- _ts_metadata('design:returntype', Array),
861
- ],
862
- Help.prototype,
863
- 'visibleArguments',
864
- null
865
- )
866
- _ts_decorate(
867
- [
868
- lazyProp,
869
- _ts_metadata('design:type', Function),
870
- _ts_metadata('design:paramtypes', []),
871
- _ts_metadata('design:returntype', Number),
872
- ],
873
- Help.prototype,
874
- 'longestSubcommandAliasLength',
875
- null
876
- )
877
- _ts_decorate(
878
- [
879
- lazyProp,
880
- _ts_metadata('design:type', Function),
881
- _ts_metadata('design:paramtypes', []),
882
- _ts_metadata('design:returntype', Number),
883
- ],
884
- Help.prototype,
885
- 'longestSubcommandTermLength',
886
- null
887
- )
888
- _ts_decorate(
889
- [
890
- lazyProp,
891
- _ts_metadata('design:type', Function),
892
- _ts_metadata('design:paramtypes', []),
893
- _ts_metadata('design:returntype', Number),
894
- ],
895
- Help.prototype,
896
- 'longestOptionTermLength',
897
- null
898
- )
899
- _ts_decorate(
900
- [
901
- lazyProp,
902
- _ts_metadata('design:type', Function),
903
- _ts_metadata('design:paramtypes', []),
904
- _ts_metadata('design:returntype', Number),
905
- ],
906
- Help.prototype,
907
- 'longestArgumentTermLength',
908
- null
909
- )
910
- _ts_decorate(
911
- [
912
- lazyProp,
913
- _ts_metadata('design:type', Function),
914
- _ts_metadata('design:paramtypes', []),
915
- _ts_metadata('design:returntype', Number),
916
- ],
917
- Help.prototype,
918
- 'padWidth',
919
- null
920
- )
845
+ __name(checkOptionValues, "checkOptionValues");
846
+ function needsValue(def) {
847
+ return def.type === "string" && !(def.variadic && !def.required);
848
+ }
849
+ __name(needsValue, "needsValue");
850
+ function isNoValue(next) {
851
+ return next === void 0 || isOptionLike(next);
852
+ }
853
+ __name(isNoValue, "isNoValue");
854
+ function reportMissingValue(def, report) {
855
+ report.errors.push(`Option --${def.long} requires a value`);
856
+ report.invalid.add(def.name);
857
+ }
858
+ __name(reportMissingValue, "reportMissingValue");
859
+ function checkLong(word, next, options, report) {
860
+ const eq = word.indexOf("=");
861
+ const name = eq === -1 ? word.slice(2) : word.slice(2, eq);
862
+ const def = options.find((o) => o.name === name);
863
+ const negated = !def && name.startsWith("no-") ? options.find((o) => o.name === name.slice(3)) : void 0;
864
+ if (def?.type === "boolean" && eq !== -1) {
865
+ report.errors.push(`Option --${def.long} does not take a value: --${def.long}${word.slice(eq)}`);
866
+ report.invalid.add(def.name);
867
+ return {
868
+ keep: [],
869
+ read: 1
870
+ };
871
+ }
872
+ if (negated?.type === "string") {
873
+ report.errors.push(`Option --${negated.long} takes a value and cannot be negated: --no-${negated.long}`);
874
+ report.invalid.add(negated.name);
875
+ return {
876
+ keep: [],
877
+ read: 1
878
+ };
879
+ }
880
+ if (def?.type !== "string" || eq !== -1) {
881
+ return {
882
+ keep: [
883
+ word
884
+ ],
885
+ read: 1
886
+ };
887
+ }
888
+ if (!isNoValue(next)) {
889
+ return {
890
+ keep: [
891
+ word,
892
+ next
893
+ ],
894
+ read: 2
895
+ };
896
+ }
897
+ if (needsValue(def)) {
898
+ reportMissingValue(def, report);
899
+ return {
900
+ keep: [],
901
+ read: 1
902
+ };
903
+ }
904
+ return {
905
+ keep: [
906
+ word
907
+ ],
908
+ read: 1
909
+ };
910
+ }
911
+ __name(checkLong, "checkLong");
912
+ function checkShort(word, next, options, report) {
913
+ for (let j = 1; j < word.length; j++) {
914
+ const def = options.find((o) => o.short === word[j]);
915
+ if (def?.type !== "string") {
916
+ continue;
917
+ }
918
+ const before = j > 1 ? [
919
+ word.slice(0, j)
920
+ ] : [];
921
+ if (j < word.length - 1) {
922
+ return word[j + 1] === "=" ? {
923
+ keep: [
924
+ ...before,
925
+ `--${def.name}${word.slice(j + 1)}`
926
+ ],
927
+ read: 1
928
+ } : {
929
+ keep: [
930
+ word
931
+ ],
932
+ read: 1
933
+ };
934
+ }
935
+ if (!isNoValue(next)) {
936
+ return {
937
+ keep: [
938
+ word,
939
+ next
940
+ ],
941
+ read: 2
942
+ };
943
+ }
944
+ if (needsValue(def)) {
945
+ reportMissingValue(def, report);
946
+ return {
947
+ keep: before,
948
+ read: 1
949
+ };
950
+ }
951
+ break;
952
+ }
953
+ return {
954
+ keep: [
955
+ word
956
+ ],
957
+ read: 1
958
+ };
959
+ }
960
+ __name(checkShort, "checkShort");
921
961
 
922
962
  // src/lib/internal/collectVariadicOptionValues.ts
923
963
  function collectVariadicOptionValues(parsed, options) {
964
+ const taken = /* @__PURE__ */ new Set();
965
+ const collected = /* @__PURE__ */ new Map();
924
966
  for (let i = 0; i < parsed.tokens.length; i++) {
925
- const token = parsed.tokens[i]
926
- if (token.kind !== 'option') {
927
- continue
928
- }
929
- const def = options.find((o) => o.name === token.name)
930
- if (!def?.variadic || def.type !== 'string') {
931
- continue
932
- }
933
- const values = [token.value]
934
- let j = i + 1
935
- while (j < parsed.tokens.length && parsed.tokens[j].kind === 'positional') {
936
- const positionalToken = parsed.tokens[j]
937
- values.push(positionalToken.value)
938
- const posIndex = parsed.positionals.indexOf(positionalToken.value)
939
- if (posIndex !== -1) {
940
- parsed.positionals.splice(posIndex, 1)
967
+ const token = parsed.tokens[i];
968
+ if (token.kind !== "option") {
969
+ continue;
970
+ }
971
+ const def = options.find((o) => o.name === token.name);
972
+ if (!def?.variadic || def.type !== "string") {
973
+ continue;
974
+ }
975
+ const values = collected.get(token.name) ?? [];
976
+ collected.set(token.name, values);
977
+ if (token.value !== void 0) {
978
+ values.push(token.value);
979
+ }
980
+ let j = i + 1;
981
+ while (j < parsed.tokens.length && parsed.tokens[j].kind === "positional") {
982
+ values.push(parsed.tokens[j].value);
983
+ taken.add(j);
984
+ j++;
985
+ }
986
+ }
987
+ if (taken.size) {
988
+ parsed.positionals = parsed.tokens.filter((token, index) => token.kind === "positional" && !taken.has(index)).map((token) => token.value);
989
+ }
990
+ for (const [name, values] of collected) {
991
+ Reflect.set(parsed.values, name, values);
992
+ }
993
+ }
994
+ __name(collectVariadicOptionValues, "collectVariadicOptionValues");
995
+
996
+ // src/lib/internal/createOption.ts
997
+ function createOption(flags, opts = {}) {
998
+ const ins = {};
999
+ const { short, long, name, argName } = parseOptionFlags(flags);
1000
+ ins.flags = flags;
1001
+ ins.short = short;
1002
+ ins.long = long;
1003
+ ins.name = name;
1004
+ ins.description = "";
1005
+ if (argName) {
1006
+ ins.type = "string";
1007
+ ins.argName = argName;
1008
+ if (flags.endsWith(">")) {
1009
+ if (flags.endsWith("...>")) {
1010
+ ins.required = true;
1011
+ ins.variadic = true;
1012
+ } else {
1013
+ ins.required = true;
1014
+ }
1015
+ } else if (flags.endsWith("]") && flags.endsWith("...]")) {
1016
+ ins.variadic = true;
1017
+ ins.defaultValue = opts.defaultValue ?? [];
1018
+ }
1019
+ } else {
1020
+ ins.type = "boolean";
1021
+ }
1022
+ for (const [key, value] of Object.entries(opts)) {
1023
+ if (value !== void 0) {
1024
+ Reflect.set(ins, key, value);
1025
+ }
1026
+ }
1027
+ if (ins.env && ins.defaultValue === void 0 && typeof process.env[ins.env] === "string") {
1028
+ ins.required = false;
1029
+ ins.flags = ins.flags.replace("<", "[").replace(">", "]");
1030
+ if (ins.type === "boolean") {
1031
+ ins.defaultValue = /^(t(rue)?|y(es)?|1)$/i.test(process.env[ins.env]);
1032
+ } else if (ins.variadic) {
1033
+ ins.defaultValue = process.env[ins.env].replace(/\[]/, "").split(",").map((v) => v.trim());
1034
+ } else {
1035
+ ins.defaultValue = process.env[ins.env];
1036
+ }
1037
+ }
1038
+ return ins;
1039
+ }
1040
+ __name(createOption, "createOption");
1041
+
1042
+ // src/lib/internal/findSubcommandIndex.ts
1043
+ function findSubcommandIndex(cmd, argv) {
1044
+ const takesNext = /* @__PURE__ */ __name((next) => next !== void 0 && !isOptionLike(next) ? 1 : 0, "takesNext");
1045
+ for (let i = 0; i < argv.length; i++) {
1046
+ const word = argv[i];
1047
+ if (word === "--") {
1048
+ return -1;
1049
+ }
1050
+ if (!isOptionLike(word)) {
1051
+ return findCommand(cmd, word) ? i : -1;
1052
+ }
1053
+ if (word.startsWith("--")) {
1054
+ const name = word.slice(2);
1055
+ const def = cmd.options.find((o) => o.long === name || o.name === name);
1056
+ if (def?.type === "string") {
1057
+ if (def.variadic) {
1058
+ return -1;
1059
+ }
1060
+ i += takesNext(argv[i + 1]);
1061
+ }
1062
+ continue;
1063
+ }
1064
+ for (let j = 1; j < word.length; j++) {
1065
+ const def = cmd.options.find((o) => o.short === word[j]);
1066
+ if (def?.type === "string") {
1067
+ if (j === word.length - 1) {
1068
+ if (def.variadic) {
1069
+ return -1;
1070
+ }
1071
+ i += takesNext(argv[i + 1]);
1072
+ }
1073
+ break;
941
1074
  }
942
- j++
943
1075
  }
944
- Reflect.set(
945
- parsed.values,
946
- token.name,
947
- values.filter((v) => v !== void 0)
948
- )
949
1076
  }
1077
+ return -1;
950
1078
  }
951
- __name(collectVariadicOptionValues, 'collectVariadicOptionValues')
1079
+ __name(findSubcommandIndex, "findSubcommandIndex");
952
1080
 
953
1081
  // src/lib/internal/mergeOptionDefaults.ts
954
1082
  function mergeOptionDefaults(values, options) {
955
1083
  for (const option of options) {
956
1084
  if (option.defaultValue !== void 0 && option.name in values) {
957
- values[option.name] ??= option.defaultValue
1085
+ values[option.name] ??= option.defaultValue;
958
1086
  }
959
1087
  }
960
1088
  }
961
- __name(mergeOptionDefaults, 'mergeOptionDefaults')
1089
+ __name(mergeOptionDefaults, "mergeOptionDefaults");
962
1090
 
963
1091
  // src/lib/internal/normalizeArgv.ts
964
1092
  function normalizeArgv(argv, options) {
1093
+ const end = argv.includes("--") ? argv.indexOf("--") : argv.length;
1094
+ const head = argv.slice(0, end);
965
1095
  for (const o of options) {
966
1096
  if (o.long === o.name) {
967
- continue
1097
+ continue;
968
1098
  }
969
- argv = argv.map((a) => {
970
- if (a === `--${o.long}`) {
971
- return `--${o.name}`
1099
+ for (let i = 0; i < head.length; i++) {
1100
+ const a = head[i];
1101
+ if (a === `--${o.long}` || a.startsWith(`--${o.long}=`)) {
1102
+ head[i] = `--${o.name}${a.slice(2 + o.long.length)}`;
1103
+ } else if (a === `--no-${o.long}`) {
1104
+ head[i] = `--no-${o.name}`;
972
1105
  }
973
- if (a === `--no-${o.long}`) {
974
- return `--no-${o.name}`
975
- }
976
- return a
977
- })
1106
+ }
978
1107
  }
979
- return argv
1108
+ return head.concat(argv.slice(end));
980
1109
  }
981
- __name(normalizeArgv, 'normalizeArgv')
1110
+ __name(normalizeArgv, "normalizeArgv");
982
1111
  function resolveArguments(positionals, args) {
983
1112
  const result = args.map((arg, index) => {
984
1113
  if (arg.variadic) {
985
- const remaining = positionals.slice(index)
986
- return remaining.length > 0 ? remaining : arg.defaultValue
1114
+ const remaining = positionals.slice(index);
1115
+ return remaining.length > 0 ? remaining : arg.defaultValue;
987
1116
  }
988
- return positionals[index] ?? arg.defaultValue
989
- })
1117
+ return positionals[index] ?? arg.defaultValue;
1118
+ });
990
1119
  while (result.length && last(result) === void 0) {
991
- result.pop()
1120
+ result.pop();
992
1121
  }
993
- return result
1122
+ return result;
994
1123
  }
995
- __name(resolveArguments, 'resolveArguments')
1124
+ __name(resolveArguments, "resolveArguments");
996
1125
 
997
1126
  // ../fn/src/setName.ts
998
1127
  function setName(name, target) {
999
- return Object.defineProperty(target, 'name', {
1000
- value: typeof name === 'string' ? name : name.name,
1128
+ return Object.defineProperty(target, "name", {
1129
+ value: typeof name === "string" ? name : name.name,
1001
1130
  configurable: true,
1002
- enumerable: false,
1003
- })
1131
+ enumerable: false
1132
+ });
1004
1133
  }
1005
- __name(setName, 'setName')
1134
+ __name(setName, "setName");
1006
1135
  function createLogger(name) {
1007
- const NAME = name ? C.dim.cyan(name) : name
1008
- const START = [NAME, C.dim.gray('[START]')].filter(Boolean)
1009
- const DEBUG = [NAME, C.dim.magenta('[DEBUG]')].filter(Boolean)
1010
- const INFO = [NAME, C.dim.gray('[INFO]')].filter(Boolean)
1011
- const DONE = [NAME, C.dim.green('[DONE] ')].filter(Boolean)
1012
- const WARN = [NAME, C.dim.yellow('[WARN] ')].filter(Boolean)
1013
- const ERROR = [NAME, C.dim.red('[ERROR]')].filter(Boolean)
1014
- const grayArgs = createColoredArgs(C.gray)
1015
- const cyanArgs = createColoredArgs(C.cyan)
1016
- const yellowArgs = createColoredArgs(C.yellow)
1136
+ const NAME = name ? C.dim.cyan(name) : name;
1137
+ const START = [
1138
+ NAME,
1139
+ C.dim.gray("[START]")
1140
+ ].filter(Boolean);
1141
+ const DEBUG = [
1142
+ NAME,
1143
+ C.dim.magenta("[DEBUG]")
1144
+ ].filter(Boolean);
1145
+ const INFO = [
1146
+ NAME,
1147
+ C.dim.gray("[INFO]")
1148
+ ].filter(Boolean);
1149
+ const DONE = [
1150
+ NAME,
1151
+ C.dim.green("[DONE] ")
1152
+ ].filter(Boolean);
1153
+ const WARN = [
1154
+ NAME,
1155
+ C.dim.yellow("[WARN] ")
1156
+ ].filter(Boolean);
1157
+ const ERROR = [
1158
+ NAME,
1159
+ C.dim.red("[ERROR]")
1160
+ ].filter(Boolean);
1161
+ const grayArgs = createColoredArgs(C.gray);
1162
+ const cyanArgs = createColoredArgs(C.cyan);
1163
+ const yellowArgs = createColoredArgs(C.yellow);
1017
1164
  return {
1018
- start: /* @__PURE__ */ __name((...args) => console.info(...START, ...args), 'start'),
1019
- done: /* @__PURE__ */ __name((...args) => console.info(...DONE, ...args), 'done'),
1020
- info: /* @__PURE__ */ __name((...args) => console.info(...INFO, ...grayArgs(args)), 'info'),
1021
- log: /* @__PURE__ */ __name((...args) => console.log(...(NAME ? [NAME, ...args] : args)), 'log'),
1022
- warn: /* @__PURE__ */ __name((...args) => console.warn(...WARN, ...yellowArgs(args)), 'warn'),
1023
- debug: /* @__PURE__ */ __name((...args) => console.debug(...DEBUG, ...cyanArgs(args)), 'debug'),
1024
- error: /* @__PURE__ */ __name((...args) => args.forEach((arg) => console.error(...ERROR, arg)), 'error'),
1025
- }
1165
+ start: /* @__PURE__ */ __name((...args) => console.info(...START, ...args), "start"),
1166
+ done: /* @__PURE__ */ __name((...args) => console.info(...DONE, ...args), "done"),
1167
+ info: /* @__PURE__ */ __name((...args) => console.info(...INFO, ...grayArgs(args)), "info"),
1168
+ log: /* @__PURE__ */ __name((...args) => console.log(...NAME ? [
1169
+ NAME,
1170
+ ...args
1171
+ ] : args), "log"),
1172
+ warn: /* @__PURE__ */ __name((...args) => console.warn(...WARN, ...yellowArgs(args)), "warn"),
1173
+ debug: /* @__PURE__ */ __name((...args) => console.debug(...DEBUG, ...cyanArgs(args)), "debug"),
1174
+ error: /* @__PURE__ */ __name((...args) => args.forEach((arg) => console.error(...ERROR, arg)), "error")
1175
+ };
1026
1176
  }
1027
- __name(createLogger, 'createLogger')
1177
+ __name(createLogger, "createLogger");
1028
1178
  function createColoredArgs(colorFn) {
1029
- return (args) =>
1030
- args.map((arg) => {
1031
- if (isString(arg)) {
1032
- return arg === C.stripColor(arg) ? colorFn(arg) : arg
1033
- } else if (isPrimitive(arg)) {
1034
- return colorFn(String(arg))
1035
- } else {
1036
- return arg
1037
- }
1038
- })
1179
+ return (args) => args.map((arg) => {
1180
+ if (isString(arg)) {
1181
+ return arg === C.stripColor(arg) ? colorFn(arg) : arg;
1182
+ } else if (isPrimitive(arg)) {
1183
+ return colorFn(String(arg));
1184
+ } else {
1185
+ return arg;
1186
+ }
1187
+ });
1039
1188
  }
1040
- __name(createColoredArgs, 'createColoredArgs')
1189
+ __name(createColoredArgs, "createColoredArgs");
1041
1190
  function timer(arg, task) {
1042
- const t0 = process.hrtime.bigint()
1043
- const [name, description] = Array.isArray(arg) ? arg : [arg, '']
1044
- const log = createLogger(name)
1191
+ const t0 = process.hrtime.bigint();
1192
+ const [name, description] = Array.isArray(arg) ? arg : [
1193
+ arg,
1194
+ ""
1195
+ ];
1196
+ const log = createLogger(name);
1045
1197
  if (name && description) {
1046
- log.start(description)
1198
+ log.start(description);
1047
1199
  }
1048
- const retval = task(log, name)
1200
+ const retval = task(log, name);
1049
1201
  if (!isPromise(retval)) {
1050
- return done(retval)
1202
+ return done(retval);
1051
1203
  }
1052
- return retval.then((result) => done(result))
1204
+ return retval.then((result) => done(result));
1053
1205
  function done(retval2) {
1054
1206
  if (process.exitCode) {
1055
- return retval2
1207
+ return retval2;
1056
1208
  }
1057
- const ns = process.hrtime.bigint() - t0
1058
- const ms3 = Math.floor(Number(ns) / 1e6)
1059
- log.done(C.dim(humanizeDuration(ms3)))
1060
- return retval2
1209
+ const ns = process.hrtime.bigint() - t0;
1210
+ const ms3 = Math.floor(Number(ns) / 1e6);
1211
+ log.done(C.dim(humanizeDuration(ms3)));
1212
+ return retval2;
1061
1213
  }
1062
1214
  }
1063
- __name(timer, 'timer')
1215
+ __name(timer, "timer");
1064
1216
 
1065
1217
  // src/lib/internal/validateParsed.ts
1066
- function validateParsed(args, optionValues, argDefs, optionDefs) {
1067
- return argDefs
1068
- .map((def, index) => {
1069
- const value = args[index]
1070
- if (def.required && (def.variadic ? Array.isArray(value) && value.length === 0 : value === void 0)) {
1071
- return `Missing argument [${index}] ${def.usage}`
1072
- }
1073
- if (def.choices && value !== void 0 && ![value].flat().every((v) => def.choices.includes(v))) {
1074
- return `Invalid argument [${index}] ${def.usage}: Got \`${value}\`. Accepted values: [${def.choices.map((c) => `\`${c}\``).join(',')}]`
1075
- }
1076
- })
1077
- .concat(
1078
- entriesOf(optionValues).map(([key, value]) => {
1079
- const def = optionDefs.find((o) => o.name === key)
1080
- if (!def) {
1081
- return `Unknown option --${key}`
1082
- }
1083
- if (
1084
- def.choices &&
1085
- value !== void 0 &&
1086
- !(def.variadic ? value : [value]).every((v) => def.choices.includes(v))
1087
- ) {
1088
- return `Invalid option value ${def.flags}: Got \`${value}\`. Accepted values: [${def.choices.map((c) => `\`${c}\``).join(',')}]`
1089
- }
1090
- })
1091
- )
1092
- .filter((s) => s !== void 0)
1093
- .reduce((acc, curr) => (acc ?? []).concat(curr), void 0)
1218
+ function validateParsed(args, optionValues, argDefs, optionDefs, rawNames = {}, invalid = /* @__PURE__ */ new Set()) {
1219
+ return argDefs.map((def, index) => {
1220
+ const value = args[index];
1221
+ if (def.required && (def.variadic ? Array.isArray(value) && value.length === 0 : value === void 0)) {
1222
+ return `Missing argument [${index}] ${def.usage}`;
1223
+ }
1224
+ if (def.choices && value !== void 0 && ![
1225
+ value
1226
+ ].flat().every((v) => def.choices.includes(v))) {
1227
+ return `Invalid argument [${index}] ${def.usage}: Got \`${value}\`. Accepted values: [${def.choices.map((c) => `\`${c}\``).join(",")}]`;
1228
+ }
1229
+ }).concat(entriesOf(optionValues).map(([key, value]) => {
1230
+ const def = optionDefs.find((o) => o.name === key);
1231
+ if (!def) {
1232
+ return `Unknown option ${rawNames[key] ?? `--${key}`}`;
1233
+ }
1234
+ if (def.choices && value !== void 0 && !(def.variadic ? value : [
1235
+ value
1236
+ ]).every((v) => def.choices.includes(v))) {
1237
+ return `Invalid option value ${def.flags}: Got \`${value}\`. Accepted values: [${def.choices.map((c) => `\`${c}\``).join(",")}]`;
1238
+ }
1239
+ })).concat(optionDefs.map((def) => {
1240
+ const value = optionValues[def.name];
1241
+ if (def.required && !invalid.has(def.name) && (value === void 0 || Array.isArray(value) && !value.length)) {
1242
+ return `Missing option ${def.flags}`;
1243
+ }
1244
+ })).filter((s) => s !== void 0).reduce((acc, curr) => (acc ?? []).concat(curr), void 0);
1094
1245
  }
1095
- __name(validateParsed, 'validateParsed')
1246
+ __name(validateParsed, "validateParsed");
1096
1247
 
1097
1248
  // src/lib/Command.ts
1098
1249
  function _ts_decorate2(decorators, target, key, desc) {
1099
- var c = arguments.length,
1100
- r = c < 3 ? target : desc === null ? (desc = Object.getOwnPropertyDescriptor(target, key)) : desc,
1101
- d
1102
- if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function')
1103
- r = Reflect.decorate(decorators, target, key, desc)
1104
- else
1105
- for (var i = decorators.length - 1; i >= 0; i--)
1106
- if ((d = decorators[i])) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r
1107
- return (c > 3 && r && Object.defineProperty(target, key, r), r)
1250
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1251
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1252
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1253
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1108
1254
  }
1109
- __name(_ts_decorate2, '_ts_decorate')
1255
+ __name(_ts_decorate2, "_ts_decorate");
1110
1256
  function _ts_metadata2(k, v) {
1111
- if (typeof Reflect === 'object' && typeof Reflect.metadata === 'function') return Reflect.metadata(k, v)
1257
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1112
1258
  }
1113
- __name(_ts_metadata2, '_ts_metadata')
1259
+ __name(_ts_metadata2, "_ts_metadata");
1260
+ var builtinOptions = /* @__PURE__ */ new WeakSet();
1114
1261
  var Command = class _Command {
1115
1262
  static {
1116
- __name(this, 'Command')
1263
+ __name(this, "Command");
1117
1264
  }
1118
1265
  /** parent command in the hierarchy, undefined for root command */
1119
- parent
1266
+ parent;
1120
1267
  /** the command name used to invoke it */
1121
- name
1268
+ name;
1122
1269
  /** semantic version string displayed by --version flag */
1123
- version
1270
+ version;
1124
1271
  /** alternative names for invoking this command */
1125
- aliases
1272
+ aliases;
1126
1273
  /** brief one-line description shown in command lists */
1127
- summary
1274
+ summary;
1128
1275
  /** full description displayed in help text */
1129
- description
1276
+ description;
1130
1277
  /** whether to exclude from help listings */
1131
- hidden
1278
+ hidden;
1132
1279
  /** category for organizing related commands in help output */
1133
- group
1280
+ group;
1134
1281
  /** positional arguments this command accepts */
1135
- arguments
1282
+ arguments;
1136
1283
  /** cLI options (flags) this command recognizes */
1137
- options
1284
+ options;
1138
1285
  /** subcommands registered with this command */
1139
- commands
1286
+ commands;
1140
1287
  /** main action handler executed when command is invoked */
1141
- action
1288
+ action;
1142
1289
  /** option-driven actions (e.g., --help, --version) executed when their conditions match */
1143
- hooks
1290
+ hooks;
1144
1291
  constructor(name, parent) {
1145
- this.name = name
1146
- this.aliases = []
1147
- this.description = ''
1148
- this.arguments = []
1149
- this.options = []
1150
- this.commands = {}
1151
- this.hooks = []
1152
- Object.defineProperty(this, 'parent', {
1292
+ this.name = name;
1293
+ this.aliases = [];
1294
+ this.description = "";
1295
+ this.arguments = [];
1296
+ this.options = [];
1297
+ this.commands = {};
1298
+ this.hooks = [];
1299
+ Object.defineProperty(this, "parent", {
1153
1300
  value: parent,
1154
- enumerable: false,
1155
- })
1301
+ enumerable: false
1302
+ });
1156
1303
  if (!parent) {
1157
- this.addOption('-D, --debug', {
1158
- description: 'Display debug information',
1159
- }).addOptionHook('debug', ({ cmd, ...data }) => {
1160
- console.debug(
1161
- inspect(cmd, {
1162
- depth: 1,
1163
- colors: true,
1164
- })
1165
- )
1166
- console.debug(
1167
- inspect(data, {
1168
- depth: 3,
1169
- colors: true,
1170
- })
1171
- )
1172
- })
1173
- this.addOption('-h, --help', {
1174
- description: 'Display help information',
1175
- }).addOptionHook('help', ({ cmd }) => {
1176
- console.log(cmd.renderHelp())
1177
- process.exitCode = 0
1178
- })
1304
+ this.addBuiltinOption("-D, --debug", "Display debug information", ({ cmd, ...data }) => {
1305
+ data.logger.debug(inspect(cmd, {
1306
+ depth: 3,
1307
+ colors: true
1308
+ }));
1309
+ data.logger.debug(inspect(data, {
1310
+ depth: 1,
1311
+ colors: true
1312
+ }));
1313
+ });
1314
+ this.addBuiltinOption("-h, --help", "Display help information", ({ cmd }) => {
1315
+ console.log(cmd.renderHelp());
1316
+ process.exitCode = 0;
1317
+ });
1179
1318
  }
1180
1319
  }
1181
1320
  get help() {
1182
- return new Help(this)
1321
+ return new Help(this);
1183
1322
  }
1184
1323
  /** configure how the help is rendered */
1185
1324
  helpConfiguration(cb) {
1186
- const help = this.help
1187
- cb?.(help)
1188
- return this
1325
+ const help = this.help;
1326
+ cb?.(help);
1327
+ return this;
1189
1328
  }
1190
1329
  /** renders formatted help text using provided help definition */
1191
1330
  renderHelp(config = {}) {
1192
- const result = this.help.render()
1193
- return config.noColor ? C.stripColor(result) : result
1331
+ const result = this.help.render();
1332
+ return config.noColor ? C.stripColor(result) : result;
1194
1333
  }
1195
1334
  /** sets the command name */
1196
1335
  setName(name) {
1197
- this.name = name
1336
+ this.name = name;
1198
1337
  }
1199
1338
  /** sets command aliases, flattening nested arrays */
1200
1339
  setAliases(...aliases) {
1201
- this.aliases = []
1202
- this.addAliases(...aliases)
1203
- return this
1340
+ this.aliases = [];
1341
+ this.addAliases(...aliases);
1342
+ return this;
1204
1343
  }
1205
1344
  /** adds aliases to existing ones */
1206
1345
  addAliases(...aliases) {
1207
- const taken = this.parent ? valuesOf(this.parent.commands).flatMap((c) => [c.name, ...c.aliases]) : []
1208
- uniq(aliases.flat())
1209
- .filter((a) => !this.aliases.includes(a) && a !== this.name)
1210
- .forEach((a) => {
1211
- if (taken.includes(a)) {
1212
- throw new Error(
1213
- `Alias "${a}" is already used by a sibling command: ${findCommand(this.parent, a)?.name}`
1214
- )
1215
- }
1216
- this.aliases.push(a)
1217
- })
1218
- this.aliases.sort((a, b) => a.length - b.length)
1219
- return this
1346
+ const taken = this.parent ? valuesOf(this.parent.commands).flatMap((c) => [
1347
+ c.name,
1348
+ ...c.aliases
1349
+ ]) : [];
1350
+ uniq(aliases.flat()).filter((a) => !this.aliases.includes(a) && a !== this.name).forEach((a) => {
1351
+ if (taken.includes(a)) {
1352
+ throw new Error(`Alias "${a}" is already used by a sibling command: ${findCommand(this.parent, a)?.name}`);
1353
+ }
1354
+ this.aliases.push(a);
1355
+ });
1356
+ this.aliases.sort((a, b) => a.length - b.length);
1357
+ return this;
1220
1358
  }
1221
1359
  /** sets the command version */
1222
1360
  setVersion(version) {
1223
- this.version = version
1224
- if (findOption(this, 'version')) {
1225
- return this
1361
+ this.version = version;
1362
+ if (findOption(this, "version")) {
1363
+ return this;
1226
1364
  }
1227
- return this.addOption('-V, --version', {
1228
- description: 'Display semver version',
1229
- }).addOptionHook('version', ({ cmd }) => {
1230
- console.log(getCommandAndAncestors(cmd).find((c) => c.version)?.version)
1231
- process.exitCode = 0
1232
- })
1365
+ return this.addBuiltinOption("-V, --version", "Display semver version", ({ cmd }) => {
1366
+ console.log(getCommandAndAncestors(cmd).find((c) => c.version)?.version);
1367
+ process.exitCode = 0;
1368
+ });
1233
1369
  }
1234
1370
  /** sets the command summary */
1235
1371
  setSummary(summary) {
1236
- this.summary = summary
1237
- return this
1372
+ this.summary = summary;
1373
+ return this;
1238
1374
  }
1239
1375
  /** sets command description, joining variadic lines */
1240
1376
  setDescription(...lines) {
1241
- this.description = lines.join('\n')
1242
- return this
1377
+ this.description = lines.join("\n");
1378
+ return this;
1243
1379
  }
1244
1380
  /** sets whether command is hidden from help */
1245
1381
  setHidden(hidden = true) {
1246
- this.hidden = hidden
1247
- return this
1382
+ this.hidden = hidden;
1383
+ return this;
1248
1384
  }
1249
1385
  /** sets the command group for help organization */
1250
1386
  setGroup(group) {
1251
- this.group = group
1252
- return this
1387
+ this.group = group;
1388
+ return this;
1253
1389
  }
1254
1390
  /** add a subcommand and return the subcommand. All options are inherited by the subcommand. */
1255
-
1391
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1256
1392
  command(name, cb) {
1257
1393
  if (this.arguments.length) {
1258
- throw new Error(
1259
- `Cannot add subcommand "${name}" to "${this.name}" because it already has arguments defined.`
1260
- )
1261
- }
1262
- const sub = this.createSubcommand(name)
1263
- const inherit = this.options
1264
- sub.options.push(...inherit)
1265
- const inheritHooks = this.hooks.filter((t) => inherit.some((i) => i.name === t.name))
1266
- sub.hooks.push(...inheritHooks)
1267
- const taken = valuesOf(this.commands).flatMap((c) => [c.name, ...c.aliases])
1394
+ throw new Error(`Cannot add subcommand "${name}" to "${this.name}" because it already has arguments defined.`);
1395
+ }
1396
+ const sub = this.createSubcommand(name);
1397
+ const inherit = this.options;
1398
+ sub.options.push(...inherit);
1399
+ const inheritHooks = this.hooks.filter((t) => inherit.some((i) => i.name === t.name));
1400
+ sub.hooks.push(...inheritHooks);
1401
+ const taken = valuesOf(this.commands).flatMap((c) => [
1402
+ c.name,
1403
+ ...c.aliases
1404
+ ]);
1268
1405
  if (taken.includes(name)) {
1269
- throw new Error(
1270
- `Command name "${getCommandAndAncestors(sub).map((c) => c.name)}" is already used by this command or its aliases: ${taken.join(', ')}`
1271
- )
1406
+ throw new Error(`Command name "${getCommandAndAncestors(sub).map((c) => c.name)}" is already used by this command or its aliases: ${taken.join(", ")}`);
1272
1407
  }
1273
- const kebab = kebabCase(name)
1274
- const words = kebab.split('-')
1275
- const initials = words.map((s) => s[0]).join('')
1408
+ const kebab = kebabCase(name);
1409
+ const words = kebab.split("-");
1410
+ const initials = words.map((s) => s[0]).join("");
1276
1411
  if (taken.includes(initials)) {
1277
- const initials2 = words.map((s) => s[0] + s[1]).join('')
1412
+ const initials2 = words.map((s) => s[0] + s[1]).join("");
1278
1413
  if (!taken.includes(initials2)) {
1279
- sub.addAliases(initials2)
1414
+ sub.addAliases(initials2);
1280
1415
  }
1281
1416
  } else {
1282
- sub.addAliases(initials)
1417
+ sub.addAliases(initials);
1283
1418
  }
1284
- this.commands[name] = sub
1285
- return cb ? cb(sub, this) : sub
1419
+ this.commands[name] = sub;
1420
+ return cb ? cb(sub, this) : sub;
1286
1421
  }
1287
1422
  /** add a subcommand and return the subcommand. All options are inherited by the subcommand. */
1288
-
1423
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1289
1424
  addCommand(name, cb) {
1290
- this.command(name, cb)
1291
- return this
1425
+ this.command(name, cb);
1426
+ return this;
1292
1427
  }
1293
1428
  // implementation
1294
1429
  addArgument(usage, options = {}) {
1295
1430
  if (!/^<(.*?)>$|^\[(.*?)]$/.test(usage)) {
1296
- throw new Error(`Invalid argument format: ${usage}`)
1431
+ throw new Error(`Invalid argument format: ${usage}`);
1297
1432
  }
1298
- const name = usage.slice(1, -1).replace(/\.{3}$/, '')
1299
- const required = usage.startsWith('<')
1300
- const variadic = usage.slice(0, -1).endsWith('...')
1301
- const prevArg = this.arguments[this.arguments.length - 1]
1433
+ const name = usage.slice(1, -1).replace(/\.{3}$/, "");
1434
+ const required = usage.startsWith("<");
1435
+ const variadic = usage.slice(0, -1).endsWith("...");
1436
+ const prevArg = this.arguments[this.arguments.length - 1];
1302
1437
  if (prevArg?.variadic) {
1303
- throw new Error(`Cannot add argument ${usage} after variadic argument ${prevArg.usage}`)
1438
+ throw new Error(`Cannot add argument ${usage} after variadic argument ${prevArg.usage}`);
1304
1439
  }
1305
1440
  if (required && prevArg && !prevArg?.required) {
1306
- throw new Error(`Cannot add required argument ${usage} after optional argument ${prevArg?.usage}`)
1441
+ throw new Error(`Cannot add required argument ${usage} after optional argument ${prevArg?.usage}`);
1307
1442
  }
1308
1443
  if (required && prevArg?.defaultValue) {
1309
- throw new Error(
1310
- `Cannot add required argument ${usage} after optional argument with default value ${prevArg.usage}`
1311
- )
1444
+ throw new Error(`Cannot add required argument ${usage} after optional argument with default value ${prevArg.usage}`);
1312
1445
  }
1313
1446
  const arg = {
1314
1447
  usage,
1315
1448
  name,
1316
1449
  required,
1317
1450
  variadic,
1318
- ...options,
1319
- }
1451
+ ...options
1452
+ };
1320
1453
  if (variadic && !arg.defaultValue) {
1321
- arg.defaultValue = []
1454
+ arg.defaultValue = [];
1322
1455
  }
1323
- this.arguments.push(arg)
1324
- return this
1456
+ this.arguments.push(arg);
1457
+ return this;
1325
1458
  }
1326
1459
  /**
1327
- * adds command-line option with type inference. Parses format: `-s, --long [<value>|[value]|<value...>|[value...]]`
1328
- */
1460
+ * adds command-line option with type inference. Parses format: `-s, --long [<value>|[value]|<value...>|[value...]]`
1461
+ */
1329
1462
  addOption(flags, opts = {}) {
1330
- const ins = {}
1331
- const { short, long, name, argName } = parseOptionFlags(flags)
1463
+ const ins = createOption(flags, opts);
1332
1464
  for (const opt of this.options) {
1333
- if (opt.long === long) {
1334
- throw new Error(`Option long name, --${long} already in use by: ${opt.flags}`)
1335
- }
1336
- if (opt.short === short) {
1337
- throw new Error(`Option short name, -${short} already in use by: ${opt.flags}`)
1338
- }
1339
- }
1340
- ins.flags = flags
1341
- ins.short = short
1342
- ins.long = long
1343
- ins.name = name
1344
- ins.description = ''
1345
- if (argName) {
1346
- ins.type = 'string'
1347
- ins.argName = argName
1348
- if (flags.endsWith('>')) {
1349
- if (flags.endsWith('...>')) {
1350
- ins.required = true
1351
- ins.variadic = true
1352
- } else {
1353
- ins.required = true
1465
+ const builtin = builtinOptions.has(opt);
1466
+ if (opt.long === ins.long) {
1467
+ if (!builtin) {
1468
+ throw new Error(`Option long name, --${ins.long} already in use by: ${opt.flags}`);
1354
1469
  }
1355
- } else if (flags.endsWith(']') && flags.endsWith('...]')) {
1356
- ins.variadic = true
1357
- ins.defaultValue = opts.defaultValue ?? []
1470
+ this.options = this.options.filter((o) => o !== opt);
1471
+ this.hooks = this.hooks.filter((h) => h.name !== opt.name);
1472
+ continue;
1358
1473
  }
1359
- } else {
1360
- ins.type = 'boolean'
1361
- }
1362
- for (const [key, value] of Object.entries(opts)) {
1363
- if (value !== void 0) {
1364
- Reflect.set(ins, key, value)
1474
+ if (opt.short === ins.short) {
1475
+ if (!builtin) {
1476
+ throw new Error(`Option short name, -${ins.short} already in use by: ${opt.flags}`);
1477
+ }
1478
+ const longOnly = {
1479
+ ...opt,
1480
+ short: void 0,
1481
+ flags: `--${opt.long}`
1482
+ };
1483
+ builtinOptions.add(longOnly);
1484
+ this.options = this.options.map((o) => o === opt ? longOnly : o);
1365
1485
  }
1366
1486
  }
1367
- if (ins.env && ins.defaultValue === void 0 && typeof process.env[ins.env] === 'string') {
1368
- ins.required = false
1369
- ins.flags = ins.flags.replace('<', '[').replace('>', ']')
1370
- if (ins.type === 'boolean') {
1371
- ins.defaultValue = /^(t(rue)?|y(es)?|1)$/i.test(process.env[ins.env])
1372
- } else if (ins.variadic) {
1373
- ins.defaultValue = process.env[ins.env]
1374
- .replace(/\[]/, '')
1375
- .split(',')
1376
- .map((v) => v.trim())
1377
- } else {
1378
- ins.defaultValue = process.env[ins.env]
1379
- }
1487
+ this.options.push(ins);
1488
+ return this;
1489
+ }
1490
+ /** adds a built-in option with its hook; it goes without its short flag when an option already has that */
1491
+ addBuiltinOption(flags, description, action) {
1492
+ const ins = createOption(flags, {
1493
+ description
1494
+ });
1495
+ if (this.options.some((o) => o.short === ins.short)) {
1496
+ ins.short = void 0;
1497
+ ins.flags = `--${ins.long}`;
1380
1498
  }
1381
- this.options.push(ins)
1382
- return this
1499
+ builtinOptions.add(ins);
1500
+ this.options.push(ins);
1501
+ return this.addOptionHook(ins.name, action);
1383
1502
  }
1384
1503
  /**
1385
- * register an action to be invoked when an option is set to true or string value.
1386
- *
1387
- * Hooks execute in addition to or instead of the main action handler,
1388
- * allowing for option-driven behavior. For example, `--help` and `--version`
1389
- * are implemented as hooks.
1390
- */
1504
+ * register an action to be invoked when an option is set to true or string value.
1505
+ *
1506
+ * Hooks execute in addition to or instead of the main action handler,
1507
+ * allowing for option-driven behavior. For example, `--help` and `--version`
1508
+ * are implemented as hooks.
1509
+ */
1391
1510
  addOptionHook(optionName, action) {
1392
- const def = findOption(this, optionName)
1511
+ const def = findOption(this, optionName);
1512
+ if (!def) {
1513
+ throw new Error(`Cannot add a hook for option "${String(optionName)}": ${this.name} has no such option`);
1514
+ }
1393
1515
  if (!def.group && /process\.exitCode ?= ?.+;?\s*}$/.test(action.toString())) {
1394
- def.group = 'Command Options'
1516
+ def.group = "Command Options";
1395
1517
  }
1396
1518
  this.hooks.push({
1397
1519
  name: optionName,
1398
- predicate: setName(
1399
- `has${upperFirst(optionName)}`,
1400
- ({ opts }) =>
1401
- opts[optionName] !== void 0 &&
1402
- opts[optionName] !== false &&
1403
- !(Array.isArray(opts[optionName]) && opts[optionName].length === 0)
1404
- ),
1405
- action: setName(optionName, action),
1406
- })
1407
- return this
1520
+ predicate: setName(`has${upperFirst(optionName)}`, ({ opts }) => opts[optionName] !== void 0 && opts[optionName] !== false && !(Array.isArray(opts[optionName]) && opts[optionName].length === 0)),
1521
+ action: setName(optionName, action)
1522
+ });
1523
+ return this;
1408
1524
  }
1409
1525
  /** parses command-line arguments with subcommand support and type-safe validation. */
1410
1526
  parseArgv(argv = process.argv.slice(2)) {
1411
- const sub = findCommand(this, argv[0])
1412
- if (sub) {
1413
- return sub.parseArgv(argv.slice(1))
1527
+ const subIndex = findSubcommandIndex(this, argv);
1528
+ if (subIndex !== -1) {
1529
+ const sub = findCommand(this, argv[subIndex]);
1530
+ return sub.parseArgv(argv.filter((_, i) => i !== subIndex));
1414
1531
  }
1415
- argv = normalizeArgv(argv, this.options)
1532
+ argv = normalizeArgv(argv, this.options);
1533
+ const checked = checkOptionValues(argv, this.options);
1416
1534
  const parsed = parseArgs({
1417
- args: argv,
1418
- options: Object.fromEntries(
1419
- this.options.map((o) => [
1420
- o.name,
1421
- {
1422
- type: o.type,
1423
- short: o.short,
1424
- default: o.defaultValue,
1425
- multiple: !!o.variadic,
1426
- },
1427
- ])
1428
- ),
1535
+ args: checked.argv,
1536
+ options: Object.fromEntries(this.options.map((o) => [
1537
+ o.name,
1538
+ {
1539
+ type: o.type,
1540
+ default: o.defaultValue,
1541
+ multiple: !!o.variadic,
1542
+ ...o.short ? {
1543
+ short: o.short
1544
+ } : {}
1545
+ }
1546
+ ])),
1429
1547
  allowPositionals: true,
1430
1548
  tokens: true,
1431
1549
  strict: false,
1432
- allowNegative: true,
1433
- })
1434
- collectVariadicOptionValues(parsed, this.options)
1435
- mergeOptionDefaults(parsed.values, this.options)
1436
- parsed.values = objSortKeys(parsed.values, (a, b) =>
1437
- a[1] === false ? 1 : b[1] === false ? -1 : a[1] === true ? 1 : b[1] === true ? -1 : 0
1438
- )
1439
- const args = resolveArguments(parsed.positionals, this.arguments)
1440
- const opts = filterObject(parsed.values, (value) => value !== void 0)
1441
- const errors = validateParsed(args, parsed.values, this.arguments, this.options)
1442
- const path = getCommandAncestors(this).map((c) => c.name)
1550
+ allowNegative: true
1551
+ });
1552
+ collectVariadicOptionValues(parsed, this.options);
1553
+ mergeOptionDefaults(parsed.values, this.options);
1554
+ parsed.values = objSortKeys(parsed.values, (a, b) => a[1] === false ? 1 : b[1] === false ? -1 : a[1] === true ? 1 : b[1] === true ? -1 : 0);
1555
+ const args = resolveArguments(parsed.positionals, this.arguments);
1556
+ const opts = filterObject(parsed.values, (value) => value !== void 0);
1557
+ const rawNames = Object.fromEntries(parsed.tokens.flatMap((t) => t.kind === "option" ? [
1558
+ [
1559
+ t.name,
1560
+ t.rawName
1561
+ ]
1562
+ ] : []));
1563
+ const unexpected = this.arguments.some((a) => a.variadic) ? [] : parsed.positionals.slice(this.arguments.length);
1564
+ const errorList = checked.errors.concat(validateParsed(args, parsed.values, this.arguments, this.options, rawNames, checked.invalid) ?? []).concat(
1565
+ // a command with subcommands has no arguments of its own: the words after an unknown name were meant for it
1566
+ Object.keys(this.commands).length ? unexpected.slice(0, 1).map((word) => `Unknown command \`${word}\``) : unexpected.map((word) => `Unexpected argument \`${word}\``)
1567
+ );
1568
+ const errors = errorList.length ? errorList : void 0;
1569
+ const path = getCommandAncestors(this).map((c) => c.name);
1443
1570
  const data = {
1444
1571
  path,
1445
1572
  name: this.name,
@@ -1447,62 +1574,70 @@ var Command = class _Command {
1447
1574
  args,
1448
1575
  opts,
1449
1576
  errors,
1450
- cmd: this,
1451
- }
1452
- const hooks = this.hooks.filter((t) => t.predicate(data))
1453
- const execute = /* @__PURE__ */ __name(async () => {
1577
+ cmd: this
1578
+ };
1579
+ const hooks = this.hooks.filter((t) => t.predicate(data));
1580
+ const execute = /* @__PURE__ */ __name(async () => await timer([
1581
+ [
1582
+ ...path,
1583
+ this.name
1584
+ ].join(" "),
1585
+ this.summary || this.description
1586
+ ], async (logger) => {
1454
1587
  for (const hook of hooks) {
1455
- await hook.action(data)
1588
+ await hook.action({
1589
+ ...data,
1590
+ get logger() {
1591
+ return logger;
1592
+ }
1593
+ });
1456
1594
  if (process.exitCode !== void 0) {
1457
- return
1595
+ return;
1458
1596
  }
1459
1597
  }
1460
- await timer([[...path, this.name].join(' '), this.description], async (logger) => {
1461
- if (errors) {
1462
- errors.forEach((msg) => logger.error(C.red(msg)))
1463
- process.exitCode = 1
1464
- return
1465
- }
1466
- if (this.action) {
1467
- return await this.action(...args, opts, {
1468
- ...data,
1469
- args,
1470
- opts,
1471
- cmd: this,
1472
- logger,
1473
- })
1474
- }
1475
- console.log(this.renderHelp())
1476
- })
1477
- }, 'execute')
1598
+ if (errors) {
1599
+ errors.forEach((msg) => logger.error(C.red(msg)));
1600
+ process.exitCode = 1;
1601
+ return;
1602
+ }
1603
+ if (this.action) {
1604
+ return await this.action(...args, opts, {
1605
+ ...data,
1606
+ args,
1607
+ opts,
1608
+ cmd: this,
1609
+ get logger() {
1610
+ return logger;
1611
+ }
1612
+ });
1613
+ }
1614
+ console.log(this.renderHelp());
1615
+ }), "execute");
1478
1616
  return {
1479
1617
  ...data,
1480
1618
  hooks,
1481
- execute,
1482
- }
1619
+ execute
1620
+ };
1483
1621
  }
1484
1622
  /**
1485
- * sets the main action handler for this command, which is executed after any matching option hooks when the command is invoked.
1486
- * The handler receives parsed arguments and options with correct typings.
1487
- */
1623
+ * sets the main action handler for this command, which is executed after any matching option hooks when the command is invoked.
1624
+ * The handler receives parsed arguments and options with correct typings. It may return a value (or a promise of one):
1625
+ * `execute()` of the parse result gives it back, typed.
1626
+ */
1488
1627
  setAction(fn) {
1489
- this.action = setName(this.name, fn)
1490
- return this
1628
+ const typed = this;
1629
+ typed.action = setName(this.name, fn);
1630
+ return typed;
1491
1631
  }
1492
1632
  /** returns a new Command instance. Override this method in subclasses. */
1493
1633
  createSubcommand(name) {
1494
- return new _Command(name, this)
1495
- }
1496
- }
1497
- _ts_decorate2(
1498
- [
1499
- lazyProp,
1500
- _ts_metadata2('design:type', typeof Help === 'undefined' ? Object : Help),
1501
- _ts_metadata2('design:paramtypes', []),
1502
- ],
1503
- Command.prototype,
1504
- 'help',
1505
- null
1506
- )
1634
+ return new _Command(name, this);
1635
+ }
1636
+ };
1637
+ _ts_decorate2([
1638
+ lazyProp,
1639
+ _ts_metadata2("design:type", typeof Help === "undefined" ? Object : Help),
1640
+ _ts_metadata2("design:paramtypes", [])
1641
+ ], Command.prototype, "help", null);
1507
1642
 
1508
- export { Command, Help, findCommand, findOption, getCommandAncestors, getCommandAndAncestors, parseOptionFlags }
1643
+ export { Command, Help, findCommand, findOption, getCommandAncestors, getCommandAndAncestors, parseOptionFlags };