@bemoje/cli 4.0.1 → 5.0.0

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