@pragmatic-divops/cli 1.8.0 → 1.9.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.
@@ -1,27 +1,1874 @@
1
1
  #!/usr/bin/env node
2
- 'use strict';
3
-
4
- var yargs = require('yargs');
5
- var updateNotifier = require('update-notifier');
6
- require('source-map-support/register');
7
- var project = require('@form8ion/project');
8
- var renovateScaffolder = require('@form8ion/renovate-scaffolder');
9
- var javascript$1 = require('@form8ion/javascript');
10
- var javascriptCore = require('@form8ion/javascript-core');
11
- var githubScaffolder = require('@travi/github-scaffolder');
12
- var githubActionsNodeCi = require('@form8ion/github-actions-node-ci');
13
- var mochaScaffolder = require('@form8ion/mocha-scaffolder');
14
- var eslintConfigExtender = require('@form8ion/eslint-config-extender');
15
- var gatsby = require('@form8ion/gatsby');
16
- var netlifyScaffolder = require('@travi/netlify-scaffolder');
17
- var lift = require('@form8ion/lift');
18
- var cucumberScaffolder = require('@form8ion/cucumber-scaffolder');
19
- var codecov = require('@form8ion/codecov');
2
+ import yargs from 'yargs';
3
+ import { format, inspect } from 'util';
4
+ import { normalize, resolve, dirname, basename, extname, relative } from 'path';
5
+ import { readFileSync, statSync, readdirSync, writeFile } from 'fs';
6
+ import { notStrictEqual, strictEqual } from 'assert';
7
+ import { fileURLToPath } from 'url';
8
+ import updateNotifier from 'update-notifier';
9
+ import { questionNames, scaffold as scaffold$8 } from '@form8ion/project';
10
+ import { scaffold as scaffold$7, predicate, lift as lift$2 } from '@form8ion/renovate-scaffolder';
11
+ import { scaffold, questionNames as questionNames$1, lift, test } from '@form8ion/javascript';
12
+ import { packageManagers } from '@form8ion/javascript-core';
13
+ import { prompt, scaffold as scaffold$6 } from '@travi/github-scaffolder';
14
+ import { scaffold as scaffold$1, test as test$1, lift as lift$3 } from '@form8ion/github-actions-node-ci';
15
+ import { scaffold as scaffold$5 } from '@form8ion/mocha-scaffolder';
16
+ import { scaffold as scaffold$4, extendEslintConfig } from '@form8ion/eslint-config-extender';
17
+ import { scaffold as scaffold$3 } from '@form8ion/gatsby';
18
+ import { scaffold as scaffold$2 } from '@travi/netlify-scaffolder';
19
+ import { lift as lift$1 } from '@form8ion/lift';
20
+ import { scaffold as scaffold$a } from '@form8ion/cucumber-scaffolder';
21
+ import { scaffold as scaffold$9 } from '@form8ion/codecov';
22
+
23
+ class YError extends Error {
24
+ constructor(msg) {
25
+ super(msg || 'yargs error');
26
+ this.name = 'YError';
27
+ if (Error.captureStackTrace) {
28
+ Error.captureStackTrace(this, YError);
29
+ }
30
+ }
31
+ }
32
+
33
+ function getProcessArgvBinIndex() {
34
+ if (isBundledElectronApp())
35
+ return 0;
36
+ return 1;
37
+ }
38
+ function isBundledElectronApp() {
39
+ return isElectronApp() && !process.defaultApp;
40
+ }
41
+ function isElectronApp() {
42
+ return !!process.versions.electron;
43
+ }
44
+ function hideBin(argv) {
45
+ return argv.slice(getProcessArgvBinIndex() + 1);
46
+ }
47
+ function getProcessArgvBin() {
48
+ return process.argv[getProcessArgvBinIndex()];
49
+ }
50
+
51
+ /**
52
+ * @license
53
+ * Copyright (c) 2016, Contributors
54
+ * SPDX-License-Identifier: ISC
55
+ */
56
+ function camelCase(str) {
57
+ // Handle the case where an argument is provided as camel case, e.g., fooBar.
58
+ // by ensuring that the string isn't already mixed case:
59
+ const isCamelCase = str !== str.toLowerCase() && str !== str.toUpperCase();
60
+ if (!isCamelCase) {
61
+ str = str.toLowerCase();
62
+ }
63
+ if (str.indexOf('-') === -1 && str.indexOf('_') === -1) {
64
+ return str;
65
+ }
66
+ else {
67
+ let camelcase = '';
68
+ let nextChrUpper = false;
69
+ const leadingHyphens = str.match(/^-+/);
70
+ for (let i = leadingHyphens ? leadingHyphens[0].length : 0; i < str.length; i++) {
71
+ let chr = str.charAt(i);
72
+ if (nextChrUpper) {
73
+ nextChrUpper = false;
74
+ chr = chr.toUpperCase();
75
+ }
76
+ if (i !== 0 && (chr === '-' || chr === '_')) {
77
+ nextChrUpper = true;
78
+ }
79
+ else if (chr !== '-' && chr !== '_') {
80
+ camelcase += chr;
81
+ }
82
+ }
83
+ return camelcase;
84
+ }
85
+ }
86
+ function decamelize(str, joinString) {
87
+ const lowercase = str.toLowerCase();
88
+ joinString = joinString || '-';
89
+ let notCamelcase = '';
90
+ for (let i = 0; i < str.length; i++) {
91
+ const chrLower = lowercase.charAt(i);
92
+ const chrString = str.charAt(i);
93
+ if (chrLower !== chrString && i > 0) {
94
+ notCamelcase += `${joinString}${lowercase.charAt(i)}`;
95
+ }
96
+ else {
97
+ notCamelcase += chrString;
98
+ }
99
+ }
100
+ return notCamelcase;
101
+ }
102
+ function looksLikeNumber(x) {
103
+ if (x === null || x === undefined)
104
+ return false;
105
+ // if loaded from config, may already be a number.
106
+ if (typeof x === 'number')
107
+ return true;
108
+ // hexadecimal.
109
+ if (/^0x[0-9a-f]+$/i.test(x))
110
+ return true;
111
+ // don't treat 0123 as a number; as it drops the leading '0'.
112
+ if (/^0[^.]/.test(x))
113
+ return false;
114
+ return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
115
+ }
116
+
117
+ /**
118
+ * @license
119
+ * Copyright (c) 2016, Contributors
120
+ * SPDX-License-Identifier: ISC
121
+ */
122
+ // take an un-split argv string and tokenize it.
123
+ function tokenizeArgString(argString) {
124
+ if (Array.isArray(argString)) {
125
+ return argString.map(e => typeof e !== 'string' ? e + '' : e);
126
+ }
127
+ argString = argString.trim();
128
+ let i = 0;
129
+ let prevC = null;
130
+ let c = null;
131
+ let opening = null;
132
+ const args = [];
133
+ for (let ii = 0; ii < argString.length; ii++) {
134
+ prevC = c;
135
+ c = argString.charAt(ii);
136
+ // split on spaces unless we're in quotes.
137
+ if (c === ' ' && !opening) {
138
+ if (!(prevC === ' ')) {
139
+ i++;
140
+ }
141
+ continue;
142
+ }
143
+ // don't split the string if we're in matching
144
+ // opening or closing single and double quotes.
145
+ if (c === opening) {
146
+ opening = null;
147
+ }
148
+ else if ((c === "'" || c === '"') && !opening) {
149
+ opening = c;
150
+ }
151
+ if (!args[i])
152
+ args[i] = '';
153
+ args[i] += c;
154
+ }
155
+ return args;
156
+ }
157
+
158
+ /**
159
+ * @license
160
+ * Copyright (c) 2016, Contributors
161
+ * SPDX-License-Identifier: ISC
162
+ */
163
+ var DefaultValuesForTypeKey;
164
+ (function (DefaultValuesForTypeKey) {
165
+ DefaultValuesForTypeKey["BOOLEAN"] = "boolean";
166
+ DefaultValuesForTypeKey["STRING"] = "string";
167
+ DefaultValuesForTypeKey["NUMBER"] = "number";
168
+ DefaultValuesForTypeKey["ARRAY"] = "array";
169
+ })(DefaultValuesForTypeKey || (DefaultValuesForTypeKey = {}));
170
+
171
+ /**
172
+ * @license
173
+ * Copyright (c) 2016, Contributors
174
+ * SPDX-License-Identifier: ISC
175
+ */
176
+ let mixin$1;
177
+ class YargsParser {
178
+ constructor(_mixin) {
179
+ mixin$1 = _mixin;
180
+ }
181
+ parse(argsInput, options) {
182
+ const opts = Object.assign({
183
+ alias: undefined,
184
+ array: undefined,
185
+ boolean: undefined,
186
+ config: undefined,
187
+ configObjects: undefined,
188
+ configuration: undefined,
189
+ coerce: undefined,
190
+ count: undefined,
191
+ default: undefined,
192
+ envPrefix: undefined,
193
+ narg: undefined,
194
+ normalize: undefined,
195
+ string: undefined,
196
+ number: undefined,
197
+ __: undefined,
198
+ key: undefined
199
+ }, options);
200
+ // allow a string argument to be passed in rather
201
+ // than an argv array.
202
+ const args = tokenizeArgString(argsInput);
203
+ // tokenizeArgString adds extra quotes to args if argsInput is a string
204
+ // only strip those extra quotes in processValue if argsInput is a string
205
+ const inputIsString = typeof argsInput === 'string';
206
+ // aliases might have transitive relationships, normalize this.
207
+ const aliases = combineAliases(Object.assign(Object.create(null), opts.alias));
208
+ const configuration = Object.assign({
209
+ 'boolean-negation': true,
210
+ 'camel-case-expansion': true,
211
+ 'combine-arrays': false,
212
+ 'dot-notation': true,
213
+ 'duplicate-arguments-array': true,
214
+ 'flatten-duplicate-arrays': true,
215
+ 'greedy-arrays': true,
216
+ 'halt-at-non-option': false,
217
+ 'nargs-eats-options': false,
218
+ 'negation-prefix': 'no-',
219
+ 'parse-numbers': true,
220
+ 'parse-positional-numbers': true,
221
+ 'populate--': false,
222
+ 'set-placeholder-key': false,
223
+ 'short-option-groups': true,
224
+ 'strip-aliased': false,
225
+ 'strip-dashed': false,
226
+ 'unknown-options-as-args': false
227
+ }, opts.configuration);
228
+ const defaults = Object.assign(Object.create(null), opts.default);
229
+ const configObjects = opts.configObjects || [];
230
+ const envPrefix = opts.envPrefix;
231
+ const notFlagsOption = configuration['populate--'];
232
+ const notFlagsArgv = notFlagsOption ? '--' : '_';
233
+ const newAliases = Object.create(null);
234
+ const defaulted = Object.create(null);
235
+ // allow a i18n handler to be passed in, default to a fake one (util.format).
236
+ const __ = opts.__ || mixin$1.format;
237
+ const flags = {
238
+ aliases: Object.create(null),
239
+ arrays: Object.create(null),
240
+ bools: Object.create(null),
241
+ strings: Object.create(null),
242
+ numbers: Object.create(null),
243
+ counts: Object.create(null),
244
+ normalize: Object.create(null),
245
+ configs: Object.create(null),
246
+ nargs: Object.create(null),
247
+ coercions: Object.create(null),
248
+ keys: []
249
+ };
250
+ const negative = /^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/;
251
+ const negatedBoolean = new RegExp('^--' + configuration['negation-prefix'] + '(.+)');
252
+ [].concat(opts.array || []).filter(Boolean).forEach(function (opt) {
253
+ const key = typeof opt === 'object' ? opt.key : opt;
254
+ // assign to flags[bools|strings|numbers]
255
+ const assignment = Object.keys(opt).map(function (key) {
256
+ const arrayFlagKeys = {
257
+ boolean: 'bools',
258
+ string: 'strings',
259
+ number: 'numbers'
260
+ };
261
+ return arrayFlagKeys[key];
262
+ }).filter(Boolean).pop();
263
+ // assign key to be coerced
264
+ if (assignment) {
265
+ flags[assignment][key] = true;
266
+ }
267
+ flags.arrays[key] = true;
268
+ flags.keys.push(key);
269
+ });
270
+ [].concat(opts.boolean || []).filter(Boolean).forEach(function (key) {
271
+ flags.bools[key] = true;
272
+ flags.keys.push(key);
273
+ });
274
+ [].concat(opts.string || []).filter(Boolean).forEach(function (key) {
275
+ flags.strings[key] = true;
276
+ flags.keys.push(key);
277
+ });
278
+ [].concat(opts.number || []).filter(Boolean).forEach(function (key) {
279
+ flags.numbers[key] = true;
280
+ flags.keys.push(key);
281
+ });
282
+ [].concat(opts.count || []).filter(Boolean).forEach(function (key) {
283
+ flags.counts[key] = true;
284
+ flags.keys.push(key);
285
+ });
286
+ [].concat(opts.normalize || []).filter(Boolean).forEach(function (key) {
287
+ flags.normalize[key] = true;
288
+ flags.keys.push(key);
289
+ });
290
+ if (typeof opts.narg === 'object') {
291
+ Object.entries(opts.narg).forEach(([key, value]) => {
292
+ if (typeof value === 'number') {
293
+ flags.nargs[key] = value;
294
+ flags.keys.push(key);
295
+ }
296
+ });
297
+ }
298
+ if (typeof opts.coerce === 'object') {
299
+ Object.entries(opts.coerce).forEach(([key, value]) => {
300
+ if (typeof value === 'function') {
301
+ flags.coercions[key] = value;
302
+ flags.keys.push(key);
303
+ }
304
+ });
305
+ }
306
+ if (typeof opts.config !== 'undefined') {
307
+ if (Array.isArray(opts.config) || typeof opts.config === 'string') {
308
+ [].concat(opts.config).filter(Boolean).forEach(function (key) {
309
+ flags.configs[key] = true;
310
+ });
311
+ }
312
+ else if (typeof opts.config === 'object') {
313
+ Object.entries(opts.config).forEach(([key, value]) => {
314
+ if (typeof value === 'boolean' || typeof value === 'function') {
315
+ flags.configs[key] = value;
316
+ }
317
+ });
318
+ }
319
+ }
320
+ // create a lookup table that takes into account all
321
+ // combinations of aliases: {f: ['foo'], foo: ['f']}
322
+ extendAliases(opts.key, aliases, opts.default, flags.arrays);
323
+ // apply default values to all aliases.
324
+ Object.keys(defaults).forEach(function (key) {
325
+ (flags.aliases[key] || []).forEach(function (alias) {
326
+ defaults[alias] = defaults[key];
327
+ });
328
+ });
329
+ let error = null;
330
+ checkConfiguration();
331
+ let notFlags = [];
332
+ const argv = Object.assign(Object.create(null), { _: [] });
333
+ // TODO(bcoe): for the first pass at removing object prototype we didn't
334
+ // remove all prototypes from objects returned by this API, we might want
335
+ // to gradually move towards doing so.
336
+ const argvReturn = {};
337
+ for (let i = 0; i < args.length; i++) {
338
+ const arg = args[i];
339
+ const truncatedArg = arg.replace(/^-{3,}/, '---');
340
+ let broken;
341
+ let key;
342
+ let letters;
343
+ let m;
344
+ let next;
345
+ let value;
346
+ // any unknown option (except for end-of-options, "--")
347
+ if (arg !== '--' && /^-/.test(arg) && isUnknownOptionAsArg(arg)) {
348
+ pushPositional(arg);
349
+ // ---, ---=, ----, etc,
350
+ }
351
+ else if (truncatedArg.match(/^---+(=|$)/)) {
352
+ // options without key name are invalid.
353
+ pushPositional(arg);
354
+ continue;
355
+ // -- separated by =
356
+ }
357
+ else if (arg.match(/^--.+=/) || (!configuration['short-option-groups'] && arg.match(/^-.+=/))) {
358
+ // Using [\s\S] instead of . because js doesn't support the
359
+ // 'dotall' regex modifier. See:
360
+ // http://stackoverflow.com/a/1068308/13216
361
+ m = arg.match(/^--?([^=]+)=([\s\S]*)$/);
362
+ // arrays format = '--f=a b c'
363
+ if (m !== null && Array.isArray(m) && m.length >= 3) {
364
+ if (checkAllAliases(m[1], flags.arrays)) {
365
+ i = eatArray(i, m[1], args, m[2]);
366
+ }
367
+ else if (checkAllAliases(m[1], flags.nargs) !== false) {
368
+ // nargs format = '--f=monkey washing cat'
369
+ i = eatNargs(i, m[1], args, m[2]);
370
+ }
371
+ else {
372
+ setArg(m[1], m[2], true);
373
+ }
374
+ }
375
+ }
376
+ else if (arg.match(negatedBoolean) && configuration['boolean-negation']) {
377
+ m = arg.match(negatedBoolean);
378
+ if (m !== null && Array.isArray(m) && m.length >= 2) {
379
+ key = m[1];
380
+ setArg(key, checkAllAliases(key, flags.arrays) ? [false] : false);
381
+ }
382
+ // -- separated by space.
383
+ }
384
+ else if (arg.match(/^--.+/) || (!configuration['short-option-groups'] && arg.match(/^-[^-]+/))) {
385
+ m = arg.match(/^--?(.+)/);
386
+ if (m !== null && Array.isArray(m) && m.length >= 2) {
387
+ key = m[1];
388
+ if (checkAllAliases(key, flags.arrays)) {
389
+ // array format = '--foo a b c'
390
+ i = eatArray(i, key, args);
391
+ }
392
+ else if (checkAllAliases(key, flags.nargs) !== false) {
393
+ // nargs format = '--foo a b c'
394
+ // should be truthy even if: flags.nargs[key] === 0
395
+ i = eatNargs(i, key, args);
396
+ }
397
+ else {
398
+ next = args[i + 1];
399
+ if (next !== undefined && (!next.match(/^-/) ||
400
+ next.match(negative)) &&
401
+ !checkAllAliases(key, flags.bools) &&
402
+ !checkAllAliases(key, flags.counts)) {
403
+ setArg(key, next);
404
+ i++;
405
+ }
406
+ else if (/^(true|false)$/.test(next)) {
407
+ setArg(key, next);
408
+ i++;
409
+ }
410
+ else {
411
+ setArg(key, defaultValue(key));
412
+ }
413
+ }
414
+ }
415
+ // dot-notation flag separated by '='.
416
+ }
417
+ else if (arg.match(/^-.\..+=/)) {
418
+ m = arg.match(/^-([^=]+)=([\s\S]*)$/);
419
+ if (m !== null && Array.isArray(m) && m.length >= 3) {
420
+ setArg(m[1], m[2]);
421
+ }
422
+ // dot-notation flag separated by space.
423
+ }
424
+ else if (arg.match(/^-.\..+/) && !arg.match(negative)) {
425
+ next = args[i + 1];
426
+ m = arg.match(/^-(.\..+)/);
427
+ if (m !== null && Array.isArray(m) && m.length >= 2) {
428
+ key = m[1];
429
+ if (next !== undefined && !next.match(/^-/) &&
430
+ !checkAllAliases(key, flags.bools) &&
431
+ !checkAllAliases(key, flags.counts)) {
432
+ setArg(key, next);
433
+ i++;
434
+ }
435
+ else {
436
+ setArg(key, defaultValue(key));
437
+ }
438
+ }
439
+ }
440
+ else if (arg.match(/^-[^-]+/) && !arg.match(negative)) {
441
+ letters = arg.slice(1, -1).split('');
442
+ broken = false;
443
+ for (let j = 0; j < letters.length; j++) {
444
+ next = arg.slice(j + 2);
445
+ if (letters[j + 1] && letters[j + 1] === '=') {
446
+ value = arg.slice(j + 3);
447
+ key = letters[j];
448
+ if (checkAllAliases(key, flags.arrays)) {
449
+ // array format = '-f=a b c'
450
+ i = eatArray(i, key, args, value);
451
+ }
452
+ else if (checkAllAliases(key, flags.nargs) !== false) {
453
+ // nargs format = '-f=monkey washing cat'
454
+ i = eatNargs(i, key, args, value);
455
+ }
456
+ else {
457
+ setArg(key, value);
458
+ }
459
+ broken = true;
460
+ break;
461
+ }
462
+ if (next === '-') {
463
+ setArg(letters[j], next);
464
+ continue;
465
+ }
466
+ // current letter is an alphabetic character and next value is a number
467
+ if (/[A-Za-z]/.test(letters[j]) &&
468
+ /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next) &&
469
+ checkAllAliases(next, flags.bools) === false) {
470
+ setArg(letters[j], next);
471
+ broken = true;
472
+ break;
473
+ }
474
+ if (letters[j + 1] && letters[j + 1].match(/\W/)) {
475
+ setArg(letters[j], next);
476
+ broken = true;
477
+ break;
478
+ }
479
+ else {
480
+ setArg(letters[j], defaultValue(letters[j]));
481
+ }
482
+ }
483
+ key = arg.slice(-1)[0];
484
+ if (!broken && key !== '-') {
485
+ if (checkAllAliases(key, flags.arrays)) {
486
+ // array format = '-f a b c'
487
+ i = eatArray(i, key, args);
488
+ }
489
+ else if (checkAllAliases(key, flags.nargs) !== false) {
490
+ // nargs format = '-f a b c'
491
+ // should be truthy even if: flags.nargs[key] === 0
492
+ i = eatNargs(i, key, args);
493
+ }
494
+ else {
495
+ next = args[i + 1];
496
+ if (next !== undefined && (!/^(-|--)[^-]/.test(next) ||
497
+ next.match(negative)) &&
498
+ !checkAllAliases(key, flags.bools) &&
499
+ !checkAllAliases(key, flags.counts)) {
500
+ setArg(key, next);
501
+ i++;
502
+ }
503
+ else if (/^(true|false)$/.test(next)) {
504
+ setArg(key, next);
505
+ i++;
506
+ }
507
+ else {
508
+ setArg(key, defaultValue(key));
509
+ }
510
+ }
511
+ }
512
+ }
513
+ else if (arg.match(/^-[0-9]$/) &&
514
+ arg.match(negative) &&
515
+ checkAllAliases(arg.slice(1), flags.bools)) {
516
+ // single-digit boolean alias, e.g: xargs -0
517
+ key = arg.slice(1);
518
+ setArg(key, defaultValue(key));
519
+ }
520
+ else if (arg === '--') {
521
+ notFlags = args.slice(i + 1);
522
+ break;
523
+ }
524
+ else if (configuration['halt-at-non-option']) {
525
+ notFlags = args.slice(i);
526
+ break;
527
+ }
528
+ else {
529
+ pushPositional(arg);
530
+ }
531
+ }
532
+ // order of precedence:
533
+ // 1. command line arg
534
+ // 2. value from env var
535
+ // 3. value from config file
536
+ // 4. value from config objects
537
+ // 5. configured default value
538
+ applyEnvVars(argv, true); // special case: check env vars that point to config file
539
+ applyEnvVars(argv, false);
540
+ setConfig(argv);
541
+ setConfigObjects();
542
+ applyDefaultsAndAliases(argv, flags.aliases, defaults, true);
543
+ applyCoercions(argv);
544
+ if (configuration['set-placeholder-key'])
545
+ setPlaceholderKeys(argv);
546
+ // for any counts either not in args or without an explicit default, set to 0
547
+ Object.keys(flags.counts).forEach(function (key) {
548
+ if (!hasKey(argv, key.split('.')))
549
+ setArg(key, 0);
550
+ });
551
+ // '--' defaults to undefined.
552
+ if (notFlagsOption && notFlags.length)
553
+ argv[notFlagsArgv] = [];
554
+ notFlags.forEach(function (key) {
555
+ argv[notFlagsArgv].push(key);
556
+ });
557
+ if (configuration['camel-case-expansion'] && configuration['strip-dashed']) {
558
+ Object.keys(argv).filter(key => key !== '--' && key.includes('-')).forEach(key => {
559
+ delete argv[key];
560
+ });
561
+ }
562
+ if (configuration['strip-aliased']) {
563
+ [].concat(...Object.keys(aliases).map(k => aliases[k])).forEach(alias => {
564
+ if (configuration['camel-case-expansion'] && alias.includes('-')) {
565
+ delete argv[alias.split('.').map(prop => camelCase(prop)).join('.')];
566
+ }
567
+ delete argv[alias];
568
+ });
569
+ }
570
+ // Push argument into positional array, applying numeric coercion:
571
+ function pushPositional(arg) {
572
+ const maybeCoercedNumber = maybeCoerceNumber('_', arg);
573
+ if (typeof maybeCoercedNumber === 'string' || typeof maybeCoercedNumber === 'number') {
574
+ argv._.push(maybeCoercedNumber);
575
+ }
576
+ }
577
+ // how many arguments should we consume, based
578
+ // on the nargs option?
579
+ function eatNargs(i, key, args, argAfterEqualSign) {
580
+ let ii;
581
+ let toEat = checkAllAliases(key, flags.nargs);
582
+ // NaN has a special meaning for the array type, indicating that one or
583
+ // more values are expected.
584
+ toEat = typeof toEat !== 'number' || isNaN(toEat) ? 1 : toEat;
585
+ if (toEat === 0) {
586
+ if (!isUndefined(argAfterEqualSign)) {
587
+ error = Error(__('Argument unexpected for: %s', key));
588
+ }
589
+ setArg(key, defaultValue(key));
590
+ return i;
591
+ }
592
+ let available = isUndefined(argAfterEqualSign) ? 0 : 1;
593
+ if (configuration['nargs-eats-options']) {
594
+ // classic behavior, yargs eats positional and dash arguments.
595
+ if (args.length - (i + 1) + available < toEat) {
596
+ error = Error(__('Not enough arguments following: %s', key));
597
+ }
598
+ available = toEat;
599
+ }
600
+ else {
601
+ // nargs will not consume flag arguments, e.g., -abc, --foo,
602
+ // and terminates when one is observed.
603
+ for (ii = i + 1; ii < args.length; ii++) {
604
+ if (!args[ii].match(/^-[^0-9]/) || args[ii].match(negative) || isUnknownOptionAsArg(args[ii]))
605
+ available++;
606
+ else
607
+ break;
608
+ }
609
+ if (available < toEat)
610
+ error = Error(__('Not enough arguments following: %s', key));
611
+ }
612
+ let consumed = Math.min(available, toEat);
613
+ if (!isUndefined(argAfterEqualSign) && consumed > 0) {
614
+ setArg(key, argAfterEqualSign);
615
+ consumed--;
616
+ }
617
+ for (ii = i + 1; ii < (consumed + i + 1); ii++) {
618
+ setArg(key, args[ii]);
619
+ }
620
+ return (i + consumed);
621
+ }
622
+ // if an option is an array, eat all non-hyphenated arguments
623
+ // following it... YUM!
624
+ // e.g., --foo apple banana cat becomes ["apple", "banana", "cat"]
625
+ function eatArray(i, key, args, argAfterEqualSign) {
626
+ let argsToSet = [];
627
+ let next = argAfterEqualSign || args[i + 1];
628
+ // If both array and nargs are configured, enforce the nargs count:
629
+ const nargsCount = checkAllAliases(key, flags.nargs);
630
+ if (checkAllAliases(key, flags.bools) && !(/^(true|false)$/.test(next))) {
631
+ argsToSet.push(true);
632
+ }
633
+ else if (isUndefined(next) ||
634
+ (isUndefined(argAfterEqualSign) && /^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))) {
635
+ // for keys without value ==> argsToSet remains an empty []
636
+ // set user default value, if available
637
+ if (defaults[key] !== undefined) {
638
+ const defVal = defaults[key];
639
+ argsToSet = Array.isArray(defVal) ? defVal : [defVal];
640
+ }
641
+ }
642
+ else {
643
+ // value in --option=value is eaten as is
644
+ if (!isUndefined(argAfterEqualSign)) {
645
+ argsToSet.push(processValue(key, argAfterEqualSign, true));
646
+ }
647
+ for (let ii = i + 1; ii < args.length; ii++) {
648
+ if ((!configuration['greedy-arrays'] && argsToSet.length > 0) ||
649
+ (nargsCount && typeof nargsCount === 'number' && argsToSet.length >= nargsCount))
650
+ break;
651
+ next = args[ii];
652
+ if (/^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))
653
+ break;
654
+ i = ii;
655
+ argsToSet.push(processValue(key, next, inputIsString));
656
+ }
657
+ }
658
+ // If both array and nargs are configured, create an error if less than
659
+ // nargs positionals were found. NaN has special meaning, indicating
660
+ // that at least one value is required (more are okay).
661
+ if (typeof nargsCount === 'number' && ((nargsCount && argsToSet.length < nargsCount) ||
662
+ (isNaN(nargsCount) && argsToSet.length === 0))) {
663
+ error = Error(__('Not enough arguments following: %s', key));
664
+ }
665
+ setArg(key, argsToSet);
666
+ return i;
667
+ }
668
+ function setArg(key, val, shouldStripQuotes = inputIsString) {
669
+ if (/-/.test(key) && configuration['camel-case-expansion']) {
670
+ const alias = key.split('.').map(function (prop) {
671
+ return camelCase(prop);
672
+ }).join('.');
673
+ addNewAlias(key, alias);
674
+ }
675
+ const value = processValue(key, val, shouldStripQuotes);
676
+ const splitKey = key.split('.');
677
+ setKey(argv, splitKey, value);
678
+ // handle populating aliases of the full key
679
+ if (flags.aliases[key]) {
680
+ flags.aliases[key].forEach(function (x) {
681
+ const keyProperties = x.split('.');
682
+ setKey(argv, keyProperties, value);
683
+ });
684
+ }
685
+ // handle populating aliases of the first element of the dot-notation key
686
+ if (splitKey.length > 1 && configuration['dot-notation']) {
687
+ (flags.aliases[splitKey[0]] || []).forEach(function (x) {
688
+ let keyProperties = x.split('.');
689
+ // expand alias with nested objects in key
690
+ const a = [].concat(splitKey);
691
+ a.shift(); // nuke the old key.
692
+ keyProperties = keyProperties.concat(a);
693
+ // populate alias only if is not already an alias of the full key
694
+ // (already populated above)
695
+ if (!(flags.aliases[key] || []).includes(keyProperties.join('.'))) {
696
+ setKey(argv, keyProperties, value);
697
+ }
698
+ });
699
+ }
700
+ // Set normalize getter and setter when key is in 'normalize' but isn't an array
701
+ if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) {
702
+ const keys = [key].concat(flags.aliases[key] || []);
703
+ keys.forEach(function (key) {
704
+ Object.defineProperty(argvReturn, key, {
705
+ enumerable: true,
706
+ get() {
707
+ return val;
708
+ },
709
+ set(value) {
710
+ val = typeof value === 'string' ? mixin$1.normalize(value) : value;
711
+ }
712
+ });
713
+ });
714
+ }
715
+ }
716
+ function addNewAlias(key, alias) {
717
+ if (!(flags.aliases[key] && flags.aliases[key].length)) {
718
+ flags.aliases[key] = [alias];
719
+ newAliases[alias] = true;
720
+ }
721
+ if (!(flags.aliases[alias] && flags.aliases[alias].length)) {
722
+ addNewAlias(alias, key);
723
+ }
724
+ }
725
+ function processValue(key, val, shouldStripQuotes) {
726
+ // strings may be quoted, clean this up as we assign values.
727
+ if (shouldStripQuotes) {
728
+ val = stripQuotes(val);
729
+ }
730
+ // handle parsing boolean arguments --foo=true --bar false.
731
+ if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) {
732
+ if (typeof val === 'string')
733
+ val = val === 'true';
734
+ }
735
+ let value = Array.isArray(val)
736
+ ? val.map(function (v) { return maybeCoerceNumber(key, v); })
737
+ : maybeCoerceNumber(key, val);
738
+ // increment a count given as arg (either no value or value parsed as boolean)
739
+ if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === 'boolean')) {
740
+ value = increment();
741
+ }
742
+ // Set normalized value when key is in 'normalize' and in 'arrays'
743
+ if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) {
744
+ if (Array.isArray(val))
745
+ value = val.map((val) => { return mixin$1.normalize(val); });
746
+ else
747
+ value = mixin$1.normalize(val);
748
+ }
749
+ return value;
750
+ }
751
+ function maybeCoerceNumber(key, value) {
752
+ if (!configuration['parse-positional-numbers'] && key === '_')
753
+ return value;
754
+ if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.bools) && !Array.isArray(value)) {
755
+ const shouldCoerceNumber = looksLikeNumber(value) && configuration['parse-numbers'] && (Number.isSafeInteger(Math.floor(parseFloat(`${value}`))));
756
+ if (shouldCoerceNumber || (!isUndefined(value) && checkAllAliases(key, flags.numbers))) {
757
+ value = Number(value);
758
+ }
759
+ }
760
+ return value;
761
+ }
762
+ // set args from config.json file, this should be
763
+ // applied last so that defaults can be applied.
764
+ function setConfig(argv) {
765
+ const configLookup = Object.create(null);
766
+ // expand defaults/aliases, in-case any happen to reference
767
+ // the config.json file.
768
+ applyDefaultsAndAliases(configLookup, flags.aliases, defaults);
769
+ Object.keys(flags.configs).forEach(function (configKey) {
770
+ const configPath = argv[configKey] || configLookup[configKey];
771
+ if (configPath) {
772
+ try {
773
+ let config = null;
774
+ const resolvedConfigPath = mixin$1.resolve(mixin$1.cwd(), configPath);
775
+ const resolveConfig = flags.configs[configKey];
776
+ if (typeof resolveConfig === 'function') {
777
+ try {
778
+ config = resolveConfig(resolvedConfigPath);
779
+ }
780
+ catch (e) {
781
+ config = e;
782
+ }
783
+ if (config instanceof Error) {
784
+ error = config;
785
+ return;
786
+ }
787
+ }
788
+ else {
789
+ config = mixin$1.require(resolvedConfigPath);
790
+ }
791
+ setConfigObject(config);
792
+ }
793
+ catch (ex) {
794
+ // Deno will receive a PermissionDenied error if an attempt is
795
+ // made to load config without the --allow-read flag:
796
+ if (ex.name === 'PermissionDenied')
797
+ error = ex;
798
+ else if (argv[configKey])
799
+ error = Error(__('Invalid JSON config file: %s', configPath));
800
+ }
801
+ }
802
+ });
803
+ }
804
+ // set args from config object.
805
+ // it recursively checks nested objects.
806
+ function setConfigObject(config, prev) {
807
+ Object.keys(config).forEach(function (key) {
808
+ const value = config[key];
809
+ const fullKey = prev ? prev + '.' + key : key;
810
+ // if the value is an inner object and we have dot-notation
811
+ // enabled, treat inner objects in config the same as
812
+ // heavily nested dot notations (foo.bar.apple).
813
+ if (typeof value === 'object' && value !== null && !Array.isArray(value) && configuration['dot-notation']) {
814
+ // if the value is an object but not an array, check nested object
815
+ setConfigObject(value, fullKey);
816
+ }
817
+ else {
818
+ // setting arguments via CLI takes precedence over
819
+ // values within the config file.
820
+ if (!hasKey(argv, fullKey.split('.')) || (checkAllAliases(fullKey, flags.arrays) && configuration['combine-arrays'])) {
821
+ setArg(fullKey, value);
822
+ }
823
+ }
824
+ });
825
+ }
826
+ // set all config objects passed in opts
827
+ function setConfigObjects() {
828
+ if (typeof configObjects !== 'undefined') {
829
+ configObjects.forEach(function (configObject) {
830
+ setConfigObject(configObject);
831
+ });
832
+ }
833
+ }
834
+ function applyEnvVars(argv, configOnly) {
835
+ if (typeof envPrefix === 'undefined')
836
+ return;
837
+ const prefix = typeof envPrefix === 'string' ? envPrefix : '';
838
+ const env = mixin$1.env();
839
+ Object.keys(env).forEach(function (envVar) {
840
+ if (prefix === '' || envVar.lastIndexOf(prefix, 0) === 0) {
841
+ // get array of nested keys and convert them to camel case
842
+ const keys = envVar.split('__').map(function (key, i) {
843
+ if (i === 0) {
844
+ key = key.substring(prefix.length);
845
+ }
846
+ return camelCase(key);
847
+ });
848
+ if (((configOnly && flags.configs[keys.join('.')]) || !configOnly) && !hasKey(argv, keys)) {
849
+ setArg(keys.join('.'), env[envVar]);
850
+ }
851
+ }
852
+ });
853
+ }
854
+ function applyCoercions(argv) {
855
+ let coerce;
856
+ const applied = new Set();
857
+ Object.keys(argv).forEach(function (key) {
858
+ if (!applied.has(key)) { // If we haven't already coerced this option via one of its aliases
859
+ coerce = checkAllAliases(key, flags.coercions);
860
+ if (typeof coerce === 'function') {
861
+ try {
862
+ const value = maybeCoerceNumber(key, coerce(argv[key]));
863
+ ([].concat(flags.aliases[key] || [], key)).forEach(ali => {
864
+ applied.add(ali);
865
+ argv[ali] = value;
866
+ });
867
+ }
868
+ catch (err) {
869
+ error = err;
870
+ }
871
+ }
872
+ }
873
+ });
874
+ }
875
+ function setPlaceholderKeys(argv) {
876
+ flags.keys.forEach((key) => {
877
+ // don't set placeholder keys for dot notation options 'foo.bar'.
878
+ if (~key.indexOf('.'))
879
+ return;
880
+ if (typeof argv[key] === 'undefined')
881
+ argv[key] = undefined;
882
+ });
883
+ return argv;
884
+ }
885
+ function applyDefaultsAndAliases(obj, aliases, defaults, canLog = false) {
886
+ Object.keys(defaults).forEach(function (key) {
887
+ if (!hasKey(obj, key.split('.'))) {
888
+ setKey(obj, key.split('.'), defaults[key]);
889
+ if (canLog)
890
+ defaulted[key] = true;
891
+ (aliases[key] || []).forEach(function (x) {
892
+ if (hasKey(obj, x.split('.')))
893
+ return;
894
+ setKey(obj, x.split('.'), defaults[key]);
895
+ });
896
+ }
897
+ });
898
+ }
899
+ function hasKey(obj, keys) {
900
+ let o = obj;
901
+ if (!configuration['dot-notation'])
902
+ keys = [keys.join('.')];
903
+ keys.slice(0, -1).forEach(function (key) {
904
+ o = (o[key] || {});
905
+ });
906
+ const key = keys[keys.length - 1];
907
+ if (typeof o !== 'object')
908
+ return false;
909
+ else
910
+ return key in o;
911
+ }
912
+ function setKey(obj, keys, value) {
913
+ let o = obj;
914
+ if (!configuration['dot-notation'])
915
+ keys = [keys.join('.')];
916
+ keys.slice(0, -1).forEach(function (key) {
917
+ // TODO(bcoe): in the next major version of yargs, switch to
918
+ // Object.create(null) for dot notation:
919
+ key = sanitizeKey(key);
920
+ if (typeof o === 'object' && o[key] === undefined) {
921
+ o[key] = {};
922
+ }
923
+ if (typeof o[key] !== 'object' || Array.isArray(o[key])) {
924
+ // ensure that o[key] is an array, and that the last item is an empty object.
925
+ if (Array.isArray(o[key])) {
926
+ o[key].push({});
927
+ }
928
+ else {
929
+ o[key] = [o[key], {}];
930
+ }
931
+ // we want to update the empty object at the end of the o[key] array, so set o to that object
932
+ o = o[key][o[key].length - 1];
933
+ }
934
+ else {
935
+ o = o[key];
936
+ }
937
+ });
938
+ // TODO(bcoe): in the next major version of yargs, switch to
939
+ // Object.create(null) for dot notation:
940
+ const key = sanitizeKey(keys[keys.length - 1]);
941
+ const isTypeArray = checkAllAliases(keys.join('.'), flags.arrays);
942
+ const isValueArray = Array.isArray(value);
943
+ let duplicate = configuration['duplicate-arguments-array'];
944
+ // nargs has higher priority than duplicate
945
+ if (!duplicate && checkAllAliases(key, flags.nargs)) {
946
+ duplicate = true;
947
+ if ((!isUndefined(o[key]) && flags.nargs[key] === 1) || (Array.isArray(o[key]) && o[key].length === flags.nargs[key])) {
948
+ o[key] = undefined;
949
+ }
950
+ }
951
+ if (value === increment()) {
952
+ o[key] = increment(o[key]);
953
+ }
954
+ else if (Array.isArray(o[key])) {
955
+ if (duplicate && isTypeArray && isValueArray) {
956
+ o[key] = configuration['flatten-duplicate-arrays'] ? o[key].concat(value) : (Array.isArray(o[key][0]) ? o[key] : [o[key]]).concat([value]);
957
+ }
958
+ else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) {
959
+ o[key] = value;
960
+ }
961
+ else {
962
+ o[key] = o[key].concat([value]);
963
+ }
964
+ }
965
+ else if (o[key] === undefined && isTypeArray) {
966
+ o[key] = isValueArray ? value : [value];
967
+ }
968
+ else if (duplicate && !(o[key] === undefined ||
969
+ checkAllAliases(key, flags.counts) ||
970
+ checkAllAliases(key, flags.bools))) {
971
+ o[key] = [o[key], value];
972
+ }
973
+ else {
974
+ o[key] = value;
975
+ }
976
+ }
977
+ // extend the aliases list with inferred aliases.
978
+ function extendAliases(...args) {
979
+ args.forEach(function (obj) {
980
+ Object.keys(obj || {}).forEach(function (key) {
981
+ // short-circuit if we've already added a key
982
+ // to the aliases array, for example it might
983
+ // exist in both 'opts.default' and 'opts.key'.
984
+ if (flags.aliases[key])
985
+ return;
986
+ flags.aliases[key] = [].concat(aliases[key] || []);
987
+ // For "--option-name", also set argv.optionName
988
+ flags.aliases[key].concat(key).forEach(function (x) {
989
+ if (/-/.test(x) && configuration['camel-case-expansion']) {
990
+ const c = camelCase(x);
991
+ if (c !== key && flags.aliases[key].indexOf(c) === -1) {
992
+ flags.aliases[key].push(c);
993
+ newAliases[c] = true;
994
+ }
995
+ }
996
+ });
997
+ // For "--optionName", also set argv['option-name']
998
+ flags.aliases[key].concat(key).forEach(function (x) {
999
+ if (x.length > 1 && /[A-Z]/.test(x) && configuration['camel-case-expansion']) {
1000
+ const c = decamelize(x, '-');
1001
+ if (c !== key && flags.aliases[key].indexOf(c) === -1) {
1002
+ flags.aliases[key].push(c);
1003
+ newAliases[c] = true;
1004
+ }
1005
+ }
1006
+ });
1007
+ flags.aliases[key].forEach(function (x) {
1008
+ flags.aliases[x] = [key].concat(flags.aliases[key].filter(function (y) {
1009
+ return x !== y;
1010
+ }));
1011
+ });
1012
+ });
1013
+ });
1014
+ }
1015
+ function checkAllAliases(key, flag) {
1016
+ const toCheck = [].concat(flags.aliases[key] || [], key);
1017
+ const keys = Object.keys(flag);
1018
+ const setAlias = toCheck.find(key => keys.includes(key));
1019
+ return setAlias ? flag[setAlias] : false;
1020
+ }
1021
+ function hasAnyFlag(key) {
1022
+ const flagsKeys = Object.keys(flags);
1023
+ const toCheck = [].concat(flagsKeys.map(k => flags[k]));
1024
+ return toCheck.some(function (flag) {
1025
+ return Array.isArray(flag) ? flag.includes(key) : flag[key];
1026
+ });
1027
+ }
1028
+ function hasFlagsMatching(arg, ...patterns) {
1029
+ const toCheck = [].concat(...patterns);
1030
+ return toCheck.some(function (pattern) {
1031
+ const match = arg.match(pattern);
1032
+ return match && hasAnyFlag(match[1]);
1033
+ });
1034
+ }
1035
+ // based on a simplified version of the short flag group parsing logic
1036
+ function hasAllShortFlags(arg) {
1037
+ // if this is a negative number, or doesn't start with a single hyphen, it's not a short flag group
1038
+ if (arg.match(negative) || !arg.match(/^-[^-]+/)) {
1039
+ return false;
1040
+ }
1041
+ let hasAllFlags = true;
1042
+ let next;
1043
+ const letters = arg.slice(1).split('');
1044
+ for (let j = 0; j < letters.length; j++) {
1045
+ next = arg.slice(j + 2);
1046
+ if (!hasAnyFlag(letters[j])) {
1047
+ hasAllFlags = false;
1048
+ break;
1049
+ }
1050
+ if ((letters[j + 1] && letters[j + 1] === '=') ||
1051
+ next === '-' ||
1052
+ (/[A-Za-z]/.test(letters[j]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) ||
1053
+ (letters[j + 1] && letters[j + 1].match(/\W/))) {
1054
+ break;
1055
+ }
1056
+ }
1057
+ return hasAllFlags;
1058
+ }
1059
+ function isUnknownOptionAsArg(arg) {
1060
+ return configuration['unknown-options-as-args'] && isUnknownOption(arg);
1061
+ }
1062
+ function isUnknownOption(arg) {
1063
+ arg = arg.replace(/^-{3,}/, '--');
1064
+ // ignore negative numbers
1065
+ if (arg.match(negative)) {
1066
+ return false;
1067
+ }
1068
+ // if this is a short option group and all of them are configured, it isn't unknown
1069
+ if (hasAllShortFlags(arg)) {
1070
+ return false;
1071
+ }
1072
+ // e.g. '--count=2'
1073
+ const flagWithEquals = /^-+([^=]+?)=[\s\S]*$/;
1074
+ // e.g. '-a' or '--arg'
1075
+ const normalFlag = /^-+([^=]+?)$/;
1076
+ // e.g. '-a-'
1077
+ const flagEndingInHyphen = /^-+([^=]+?)-$/;
1078
+ // e.g. '-abc123'
1079
+ const flagEndingInDigits = /^-+([^=]+?\d+)$/;
1080
+ // e.g. '-a/usr/local'
1081
+ const flagEndingInNonWordCharacters = /^-+([^=]+?)\W+.*$/;
1082
+ // check the different types of flag styles, including negatedBoolean, a pattern defined near the start of the parse method
1083
+ return !hasFlagsMatching(arg, flagWithEquals, negatedBoolean, normalFlag, flagEndingInHyphen, flagEndingInDigits, flagEndingInNonWordCharacters);
1084
+ }
1085
+ // make a best effort to pick a default value
1086
+ // for an option based on name and type.
1087
+ function defaultValue(key) {
1088
+ if (!checkAllAliases(key, flags.bools) &&
1089
+ !checkAllAliases(key, flags.counts) &&
1090
+ `${key}` in defaults) {
1091
+ return defaults[key];
1092
+ }
1093
+ else {
1094
+ return defaultForType(guessType(key));
1095
+ }
1096
+ }
1097
+ // return a default value, given the type of a flag.,
1098
+ function defaultForType(type) {
1099
+ const def = {
1100
+ [DefaultValuesForTypeKey.BOOLEAN]: true,
1101
+ [DefaultValuesForTypeKey.STRING]: '',
1102
+ [DefaultValuesForTypeKey.NUMBER]: undefined,
1103
+ [DefaultValuesForTypeKey.ARRAY]: []
1104
+ };
1105
+ return def[type];
1106
+ }
1107
+ // given a flag, enforce a default type.
1108
+ function guessType(key) {
1109
+ let type = DefaultValuesForTypeKey.BOOLEAN;
1110
+ if (checkAllAliases(key, flags.strings))
1111
+ type = DefaultValuesForTypeKey.STRING;
1112
+ else if (checkAllAliases(key, flags.numbers))
1113
+ type = DefaultValuesForTypeKey.NUMBER;
1114
+ else if (checkAllAliases(key, flags.bools))
1115
+ type = DefaultValuesForTypeKey.BOOLEAN;
1116
+ else if (checkAllAliases(key, flags.arrays))
1117
+ type = DefaultValuesForTypeKey.ARRAY;
1118
+ return type;
1119
+ }
1120
+ function isUndefined(num) {
1121
+ return num === undefined;
1122
+ }
1123
+ // check user configuration settings for inconsistencies
1124
+ function checkConfiguration() {
1125
+ // count keys should not be set as array/narg
1126
+ Object.keys(flags.counts).find(key => {
1127
+ if (checkAllAliases(key, flags.arrays)) {
1128
+ error = Error(__('Invalid configuration: %s, opts.count excludes opts.array.', key));
1129
+ return true;
1130
+ }
1131
+ else if (checkAllAliases(key, flags.nargs)) {
1132
+ error = Error(__('Invalid configuration: %s, opts.count excludes opts.narg.', key));
1133
+ return true;
1134
+ }
1135
+ return false;
1136
+ });
1137
+ }
1138
+ return {
1139
+ aliases: Object.assign({}, flags.aliases),
1140
+ argv: Object.assign(argvReturn, argv),
1141
+ configuration: configuration,
1142
+ defaulted: Object.assign({}, defaulted),
1143
+ error: error,
1144
+ newAliases: Object.assign({}, newAliases)
1145
+ };
1146
+ }
1147
+ }
1148
+ // if any aliases reference each other, we should
1149
+ // merge them together.
1150
+ function combineAliases(aliases) {
1151
+ const aliasArrays = [];
1152
+ const combined = Object.create(null);
1153
+ let change = true;
1154
+ // turn alias lookup hash {key: ['alias1', 'alias2']} into
1155
+ // a simple array ['key', 'alias1', 'alias2']
1156
+ Object.keys(aliases).forEach(function (key) {
1157
+ aliasArrays.push([].concat(aliases[key], key));
1158
+ });
1159
+ // combine arrays until zero changes are
1160
+ // made in an iteration.
1161
+ while (change) {
1162
+ change = false;
1163
+ for (let i = 0; i < aliasArrays.length; i++) {
1164
+ for (let ii = i + 1; ii < aliasArrays.length; ii++) {
1165
+ const intersect = aliasArrays[i].filter(function (v) {
1166
+ return aliasArrays[ii].indexOf(v) !== -1;
1167
+ });
1168
+ if (intersect.length) {
1169
+ aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii]);
1170
+ aliasArrays.splice(ii, 1);
1171
+ change = true;
1172
+ break;
1173
+ }
1174
+ }
1175
+ }
1176
+ }
1177
+ // map arrays back to the hash-lookup (de-dupe while
1178
+ // we're at it).
1179
+ aliasArrays.forEach(function (aliasArray) {
1180
+ aliasArray = aliasArray.filter(function (v, i, self) {
1181
+ return self.indexOf(v) === i;
1182
+ });
1183
+ const lastAlias = aliasArray.pop();
1184
+ if (lastAlias !== undefined && typeof lastAlias === 'string') {
1185
+ combined[lastAlias] = aliasArray;
1186
+ }
1187
+ });
1188
+ return combined;
1189
+ }
1190
+ // this function should only be called when a count is given as an arg
1191
+ // it is NOT called to set a default value
1192
+ // thus we can start the count at 1 instead of 0
1193
+ function increment(orig) {
1194
+ return orig !== undefined ? orig + 1 : 1;
1195
+ }
1196
+ // TODO(bcoe): in the next major version of yargs, switch to
1197
+ // Object.create(null) for dot notation:
1198
+ function sanitizeKey(key) {
1199
+ if (key === '__proto__')
1200
+ return '___proto___';
1201
+ return key;
1202
+ }
1203
+ function stripQuotes(val) {
1204
+ return (typeof val === 'string' &&
1205
+ (val[0] === "'" || val[0] === '"') &&
1206
+ val[val.length - 1] === val[0])
1207
+ ? val.substring(1, val.length - 1)
1208
+ : val;
1209
+ }
1210
+
1211
+ /**
1212
+ * @fileoverview Main entrypoint for libraries using yargs-parser in Node.js
1213
+ * CJS and ESM environments.
1214
+ *
1215
+ * @license
1216
+ * Copyright (c) 2016, Contributors
1217
+ * SPDX-License-Identifier: ISC
1218
+ */
1219
+ var _a, _b, _c;
1220
+ // See https://github.com/yargs/yargs-parser#supported-nodejs-versions for our
1221
+ // version support policy. The YARGS_MIN_NODE_VERSION is used for testing only.
1222
+ const minNodeVersion = (process && process.env && process.env.YARGS_MIN_NODE_VERSION)
1223
+ ? Number(process.env.YARGS_MIN_NODE_VERSION)
1224
+ : 12;
1225
+ const nodeVersion = (_b = (_a = process === null || process === void 0 ? void 0 : process.versions) === null || _a === void 0 ? void 0 : _a.node) !== null && _b !== void 0 ? _b : (_c = process === null || process === void 0 ? void 0 : process.version) === null || _c === void 0 ? void 0 : _c.slice(1);
1226
+ if (nodeVersion) {
1227
+ const major = Number(nodeVersion.match(/^([^.]+)/)[1]);
1228
+ if (major < minNodeVersion) {
1229
+ throw Error(`yargs parser supports a minimum Node.js version of ${minNodeVersion}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`);
1230
+ }
1231
+ }
1232
+ // Creates a yargs-parser instance using Node.js standard libraries:
1233
+ const env = process ? process.env : {};
1234
+ const parser = new YargsParser({
1235
+ cwd: process.cwd,
1236
+ env: () => {
1237
+ return env;
1238
+ },
1239
+ format,
1240
+ normalize,
1241
+ resolve,
1242
+ // TODO: figure out a way to combine ESM and CJS coverage, such that
1243
+ // we can exercise all the lines below:
1244
+ require: (path) => {
1245
+ if (typeof require !== 'undefined') {
1246
+ return require(path);
1247
+ }
1248
+ else if (path.match(/\.json$/)) {
1249
+ // Addresses: https://github.com/yargs/yargs/issues/2040
1250
+ return JSON.parse(readFileSync(path, 'utf8'));
1251
+ }
1252
+ else {
1253
+ throw Error('only .json config files are supported in ESM');
1254
+ }
1255
+ }
1256
+ });
1257
+ const yargsParser = function Parser(args, opts) {
1258
+ const result = parser.parse(args.slice(), opts);
1259
+ return result.argv;
1260
+ };
1261
+ yargsParser.detailed = function (args, opts) {
1262
+ return parser.parse(args.slice(), opts);
1263
+ };
1264
+ yargsParser.camelCase = camelCase;
1265
+ yargsParser.decamelize = decamelize;
1266
+ yargsParser.looksLikeNumber = looksLikeNumber;
1267
+
1268
+ const align = {
1269
+ right: alignRight,
1270
+ center: alignCenter
1271
+ };
1272
+ const top = 0;
1273
+ const right = 1;
1274
+ const bottom = 2;
1275
+ const left = 3;
1276
+ class UI {
1277
+ constructor(opts) {
1278
+ var _a;
1279
+ this.width = opts.width;
1280
+ this.wrap = (_a = opts.wrap) !== null && _a !== void 0 ? _a : true;
1281
+ this.rows = [];
1282
+ }
1283
+ span(...args) {
1284
+ const cols = this.div(...args);
1285
+ cols.span = true;
1286
+ }
1287
+ resetOutput() {
1288
+ this.rows = [];
1289
+ }
1290
+ div(...args) {
1291
+ if (args.length === 0) {
1292
+ this.div('');
1293
+ }
1294
+ if (this.wrap && this.shouldApplyLayoutDSL(...args) && typeof args[0] === 'string') {
1295
+ return this.applyLayoutDSL(args[0]);
1296
+ }
1297
+ const cols = args.map(arg => {
1298
+ if (typeof arg === 'string') {
1299
+ return this.colFromString(arg);
1300
+ }
1301
+ return arg;
1302
+ });
1303
+ this.rows.push(cols);
1304
+ return cols;
1305
+ }
1306
+ shouldApplyLayoutDSL(...args) {
1307
+ return args.length === 1 && typeof args[0] === 'string' &&
1308
+ /[\t\n]/.test(args[0]);
1309
+ }
1310
+ applyLayoutDSL(str) {
1311
+ const rows = str.split('\n').map(row => row.split('\t'));
1312
+ let leftColumnWidth = 0;
1313
+ // simple heuristic for layout, make sure the
1314
+ // second column lines up along the left-hand.
1315
+ // don't allow the first column to take up more
1316
+ // than 50% of the screen.
1317
+ rows.forEach(columns => {
1318
+ if (columns.length > 1 && mixin.stringWidth(columns[0]) > leftColumnWidth) {
1319
+ leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin.stringWidth(columns[0]));
1320
+ }
1321
+ });
1322
+ // generate a table:
1323
+ // replacing ' ' with padding calculations.
1324
+ // using the algorithmically generated width.
1325
+ rows.forEach(columns => {
1326
+ this.div(...columns.map((r, i) => {
1327
+ return {
1328
+ text: r.trim(),
1329
+ padding: this.measurePadding(r),
1330
+ width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined
1331
+ };
1332
+ }));
1333
+ });
1334
+ return this.rows[this.rows.length - 1];
1335
+ }
1336
+ colFromString(text) {
1337
+ return {
1338
+ text,
1339
+ padding: this.measurePadding(text)
1340
+ };
1341
+ }
1342
+ measurePadding(str) {
1343
+ // measure padding without ansi escape codes
1344
+ const noAnsi = mixin.stripAnsi(str);
1345
+ return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length];
1346
+ }
1347
+ toString() {
1348
+ const lines = [];
1349
+ this.rows.forEach(row => {
1350
+ this.rowToString(row, lines);
1351
+ });
1352
+ // don't display any lines with the
1353
+ // hidden flag set.
1354
+ return lines
1355
+ .filter(line => !line.hidden)
1356
+ .map(line => line.text)
1357
+ .join('\n');
1358
+ }
1359
+ rowToString(row, lines) {
1360
+ this.rasterize(row).forEach((rrow, r) => {
1361
+ let str = '';
1362
+ rrow.forEach((col, c) => {
1363
+ const { width } = row[c]; // the width with padding.
1364
+ const wrapWidth = this.negatePadding(row[c]); // the width without padding.
1365
+ let ts = col; // temporary string used during alignment/padding.
1366
+ if (wrapWidth > mixin.stringWidth(col)) {
1367
+ ts += ' '.repeat(wrapWidth - mixin.stringWidth(col));
1368
+ }
1369
+ // align the string within its column.
1370
+ if (row[c].align && row[c].align !== 'left' && this.wrap) {
1371
+ const fn = align[row[c].align];
1372
+ ts = fn(ts, wrapWidth);
1373
+ if (mixin.stringWidth(ts) < wrapWidth) {
1374
+ ts += ' '.repeat((width || 0) - mixin.stringWidth(ts) - 1);
1375
+ }
1376
+ }
1377
+ // apply border and padding to string.
1378
+ const padding = row[c].padding || [0, 0, 0, 0];
1379
+ if (padding[left]) {
1380
+ str += ' '.repeat(padding[left]);
1381
+ }
1382
+ str += addBorder(row[c], ts, '| ');
1383
+ str += ts;
1384
+ str += addBorder(row[c], ts, ' |');
1385
+ if (padding[right]) {
1386
+ str += ' '.repeat(padding[right]);
1387
+ }
1388
+ // if prior row is span, try to render the
1389
+ // current row on the prior line.
1390
+ if (r === 0 && lines.length > 0) {
1391
+ str = this.renderInline(str, lines[lines.length - 1]);
1392
+ }
1393
+ });
1394
+ // remove trailing whitespace.
1395
+ lines.push({
1396
+ text: str.replace(/ +$/, ''),
1397
+ span: row.span
1398
+ });
1399
+ });
1400
+ return lines;
1401
+ }
1402
+ // if the full 'source' can render in
1403
+ // the target line, do so.
1404
+ renderInline(source, previousLine) {
1405
+ const match = source.match(/^ */);
1406
+ const leadingWhitespace = match ? match[0].length : 0;
1407
+ const target = previousLine.text;
1408
+ const targetTextWidth = mixin.stringWidth(target.trimRight());
1409
+ if (!previousLine.span) {
1410
+ return source;
1411
+ }
1412
+ // if we're not applying wrapping logic,
1413
+ // just always append to the span.
1414
+ if (!this.wrap) {
1415
+ previousLine.hidden = true;
1416
+ return target + source;
1417
+ }
1418
+ if (leadingWhitespace < targetTextWidth) {
1419
+ return source;
1420
+ }
1421
+ previousLine.hidden = true;
1422
+ return target.trimRight() + ' '.repeat(leadingWhitespace - targetTextWidth) + source.trimLeft();
1423
+ }
1424
+ rasterize(row) {
1425
+ const rrows = [];
1426
+ const widths = this.columnWidths(row);
1427
+ let wrapped;
1428
+ // word wrap all columns, and create
1429
+ // a data-structure that is easy to rasterize.
1430
+ row.forEach((col, c) => {
1431
+ // leave room for left and right padding.
1432
+ col.width = widths[c];
1433
+ if (this.wrap) {
1434
+ wrapped = mixin.wrap(col.text, this.negatePadding(col), { hard: true }).split('\n');
1435
+ }
1436
+ else {
1437
+ wrapped = col.text.split('\n');
1438
+ }
1439
+ if (col.border) {
1440
+ wrapped.unshift('.' + '-'.repeat(this.negatePadding(col) + 2) + '.');
1441
+ wrapped.push("'" + '-'.repeat(this.negatePadding(col) + 2) + "'");
1442
+ }
1443
+ // add top and bottom padding.
1444
+ if (col.padding) {
1445
+ wrapped.unshift(...new Array(col.padding[top] || 0).fill(''));
1446
+ wrapped.push(...new Array(col.padding[bottom] || 0).fill(''));
1447
+ }
1448
+ wrapped.forEach((str, r) => {
1449
+ if (!rrows[r]) {
1450
+ rrows.push([]);
1451
+ }
1452
+ const rrow = rrows[r];
1453
+ for (let i = 0; i < c; i++) {
1454
+ if (rrow[i] === undefined) {
1455
+ rrow.push('');
1456
+ }
1457
+ }
1458
+ rrow.push(str);
1459
+ });
1460
+ });
1461
+ return rrows;
1462
+ }
1463
+ negatePadding(col) {
1464
+ let wrapWidth = col.width || 0;
1465
+ if (col.padding) {
1466
+ wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0);
1467
+ }
1468
+ if (col.border) {
1469
+ wrapWidth -= 4;
1470
+ }
1471
+ return wrapWidth;
1472
+ }
1473
+ columnWidths(row) {
1474
+ if (!this.wrap) {
1475
+ return row.map(col => {
1476
+ return col.width || mixin.stringWidth(col.text);
1477
+ });
1478
+ }
1479
+ let unset = row.length;
1480
+ let remainingWidth = this.width;
1481
+ // column widths can be set in config.
1482
+ const widths = row.map(col => {
1483
+ if (col.width) {
1484
+ unset--;
1485
+ remainingWidth -= col.width;
1486
+ return col.width;
1487
+ }
1488
+ return undefined;
1489
+ });
1490
+ // any unset widths should be calculated.
1491
+ const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0;
1492
+ return widths.map((w, i) => {
1493
+ if (w === undefined) {
1494
+ return Math.max(unsetWidth, _minWidth(row[i]));
1495
+ }
1496
+ return w;
1497
+ });
1498
+ }
1499
+ }
1500
+ function addBorder(col, ts, style) {
1501
+ if (col.border) {
1502
+ if (/[.']-+[.']/.test(ts)) {
1503
+ return '';
1504
+ }
1505
+ if (ts.trim().length !== 0) {
1506
+ return style;
1507
+ }
1508
+ return ' ';
1509
+ }
1510
+ return '';
1511
+ }
1512
+ // calculates the minimum width of
1513
+ // a column, based on padding preferences.
1514
+ function _minWidth(col) {
1515
+ const padding = col.padding || [];
1516
+ const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0);
1517
+ if (col.border) {
1518
+ return minWidth + 4;
1519
+ }
1520
+ return minWidth;
1521
+ }
1522
+ function getWindowWidth() {
1523
+ /* istanbul ignore next: depends on terminal */
1524
+ if (typeof process === 'object' && process.stdout && process.stdout.columns) {
1525
+ return process.stdout.columns;
1526
+ }
1527
+ return 80;
1528
+ }
1529
+ function alignRight(str, width) {
1530
+ str = str.trim();
1531
+ const strWidth = mixin.stringWidth(str);
1532
+ if (strWidth < width) {
1533
+ return ' '.repeat(width - strWidth) + str;
1534
+ }
1535
+ return str;
1536
+ }
1537
+ function alignCenter(str, width) {
1538
+ str = str.trim();
1539
+ const strWidth = mixin.stringWidth(str);
1540
+ /* istanbul ignore next */
1541
+ if (strWidth >= width) {
1542
+ return str;
1543
+ }
1544
+ return ' '.repeat((width - strWidth) >> 1) + str;
1545
+ }
1546
+ let mixin;
1547
+ function cliui(opts, _mixin) {
1548
+ mixin = _mixin;
1549
+ return new UI({
1550
+ width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(),
1551
+ wrap: opts === null || opts === void 0 ? void 0 : opts.wrap
1552
+ });
1553
+ }
1554
+
1555
+ // Minimal replacement for ansi string helpers "wrap-ansi" and "strip-ansi".
1556
+ // to facilitate ESM and Deno modules.
1557
+ // TODO: look at porting https://www.npmjs.com/package/wrap-ansi to ESM.
1558
+ // The npm application
1559
+ // Copyright (c) npm, Inc. and Contributors
1560
+ // Licensed on the terms of The Artistic License 2.0
1561
+ // See: https://github.com/npm/cli/blob/4c65cd952bc8627811735bea76b9b110cc4fc80e/lib/utils/ansi-trim.js
1562
+ const ansi = new RegExp('\x1b(?:\\[(?:\\d+[ABCDEFGJKSTm]|\\d+;\\d+[Hfm]|' +
1563
+ '\\d+;\\d+;\\d+m|6n|s|u|\\?25[lh])|\\w)', 'g');
1564
+ function stripAnsi(str) {
1565
+ return str.replace(ansi, '');
1566
+ }
1567
+ function wrap(str, width) {
1568
+ const [start, end] = str.match(ansi) || ['', ''];
1569
+ str = stripAnsi(str);
1570
+ let wrapped = '';
1571
+ for (let i = 0; i < str.length; i++) {
1572
+ if (i !== 0 && (i % width) === 0) {
1573
+ wrapped += '\n';
1574
+ }
1575
+ wrapped += str.charAt(i);
1576
+ }
1577
+ if (start && end) {
1578
+ wrapped = `${start}${wrapped}${end}`;
1579
+ }
1580
+ return wrapped;
1581
+ }
1582
+
1583
+ // Bootstrap cliui with CommonJS dependencies:
1584
+
1585
+ function ui (opts) {
1586
+ return cliui(opts, {
1587
+ stringWidth: (str) => {
1588
+ return [...str].length
1589
+ },
1590
+ stripAnsi,
1591
+ wrap
1592
+ })
1593
+ }
1594
+
1595
+ function escalade (start, callback) {
1596
+ let dir = resolve('.', start);
1597
+ let tmp, stats = statSync(dir);
1598
+
1599
+ if (!stats.isDirectory()) {
1600
+ dir = dirname(dir);
1601
+ }
1602
+
1603
+ while (true) {
1604
+ tmp = callback(dir, readdirSync(dir));
1605
+ if (tmp) return resolve(dir, tmp);
1606
+ dir = dirname(tmp = dir);
1607
+ if (tmp === dir) break;
1608
+ }
1609
+ }
1610
+
1611
+ var shim$1 = {
1612
+ fs: {
1613
+ readFileSync,
1614
+ writeFile
1615
+ },
1616
+ format,
1617
+ resolve,
1618
+ exists: (file) => {
1619
+ try {
1620
+ return statSync(file).isFile();
1621
+ }
1622
+ catch (err) {
1623
+ return false;
1624
+ }
1625
+ }
1626
+ };
1627
+
1628
+ let shim;
1629
+ class Y18N {
1630
+ constructor(opts) {
1631
+ // configurable options.
1632
+ opts = opts || {};
1633
+ this.directory = opts.directory || './locales';
1634
+ this.updateFiles = typeof opts.updateFiles === 'boolean' ? opts.updateFiles : true;
1635
+ this.locale = opts.locale || 'en';
1636
+ this.fallbackToLanguage = typeof opts.fallbackToLanguage === 'boolean' ? opts.fallbackToLanguage : true;
1637
+ // internal stuff.
1638
+ this.cache = Object.create(null);
1639
+ this.writeQueue = [];
1640
+ }
1641
+ __(...args) {
1642
+ if (typeof arguments[0] !== 'string') {
1643
+ return this._taggedLiteral(arguments[0], ...arguments);
1644
+ }
1645
+ const str = args.shift();
1646
+ let cb = function () { }; // start with noop.
1647
+ if (typeof args[args.length - 1] === 'function')
1648
+ cb = args.pop();
1649
+ cb = cb || function () { }; // noop.
1650
+ if (!this.cache[this.locale])
1651
+ this._readLocaleFile();
1652
+ // we've observed a new string, update the language file.
1653
+ if (!this.cache[this.locale][str] && this.updateFiles) {
1654
+ this.cache[this.locale][str] = str;
1655
+ // include the current directory and locale,
1656
+ // since these values could change before the
1657
+ // write is performed.
1658
+ this._enqueueWrite({
1659
+ directory: this.directory,
1660
+ locale: this.locale,
1661
+ cb
1662
+ });
1663
+ }
1664
+ else {
1665
+ cb();
1666
+ }
1667
+ return shim.format.apply(shim.format, [this.cache[this.locale][str] || str].concat(args));
1668
+ }
1669
+ __n() {
1670
+ const args = Array.prototype.slice.call(arguments);
1671
+ const singular = args.shift();
1672
+ const plural = args.shift();
1673
+ const quantity = args.shift();
1674
+ let cb = function () { }; // start with noop.
1675
+ if (typeof args[args.length - 1] === 'function')
1676
+ cb = args.pop();
1677
+ if (!this.cache[this.locale])
1678
+ this._readLocaleFile();
1679
+ let str = quantity === 1 ? singular : plural;
1680
+ if (this.cache[this.locale][singular]) {
1681
+ const entry = this.cache[this.locale][singular];
1682
+ str = entry[quantity === 1 ? 'one' : 'other'];
1683
+ }
1684
+ // we've observed a new string, update the language file.
1685
+ if (!this.cache[this.locale][singular] && this.updateFiles) {
1686
+ this.cache[this.locale][singular] = {
1687
+ one: singular,
1688
+ other: plural
1689
+ };
1690
+ // include the current directory and locale,
1691
+ // since these values could change before the
1692
+ // write is performed.
1693
+ this._enqueueWrite({
1694
+ directory: this.directory,
1695
+ locale: this.locale,
1696
+ cb
1697
+ });
1698
+ }
1699
+ else {
1700
+ cb();
1701
+ }
1702
+ // if a %d placeholder is provided, add quantity
1703
+ // to the arguments expanded by util.format.
1704
+ const values = [str];
1705
+ if (~str.indexOf('%d'))
1706
+ values.push(quantity);
1707
+ return shim.format.apply(shim.format, values.concat(args));
1708
+ }
1709
+ setLocale(locale) {
1710
+ this.locale = locale;
1711
+ }
1712
+ getLocale() {
1713
+ return this.locale;
1714
+ }
1715
+ updateLocale(obj) {
1716
+ if (!this.cache[this.locale])
1717
+ this._readLocaleFile();
1718
+ for (const key in obj) {
1719
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
1720
+ this.cache[this.locale][key] = obj[key];
1721
+ }
1722
+ }
1723
+ }
1724
+ _taggedLiteral(parts, ...args) {
1725
+ let str = '';
1726
+ parts.forEach(function (part, i) {
1727
+ const arg = args[i + 1];
1728
+ str += part;
1729
+ if (typeof arg !== 'undefined') {
1730
+ str += '%s';
1731
+ }
1732
+ });
1733
+ return this.__.apply(this, [str].concat([].slice.call(args, 1)));
1734
+ }
1735
+ _enqueueWrite(work) {
1736
+ this.writeQueue.push(work);
1737
+ if (this.writeQueue.length === 1)
1738
+ this._processWriteQueue();
1739
+ }
1740
+ _processWriteQueue() {
1741
+ const _this = this;
1742
+ const work = this.writeQueue[0];
1743
+ // destructure the enqueued work.
1744
+ const directory = work.directory;
1745
+ const locale = work.locale;
1746
+ const cb = work.cb;
1747
+ const languageFile = this._resolveLocaleFile(directory, locale);
1748
+ const serializedLocale = JSON.stringify(this.cache[locale], null, 2);
1749
+ shim.fs.writeFile(languageFile, serializedLocale, 'utf-8', function (err) {
1750
+ _this.writeQueue.shift();
1751
+ if (_this.writeQueue.length > 0)
1752
+ _this._processWriteQueue();
1753
+ cb(err);
1754
+ });
1755
+ }
1756
+ _readLocaleFile() {
1757
+ let localeLookup = {};
1758
+ const languageFile = this._resolveLocaleFile(this.directory, this.locale);
1759
+ try {
1760
+ // When using a bundler such as webpack, readFileSync may not be defined:
1761
+ if (shim.fs.readFileSync) {
1762
+ localeLookup = JSON.parse(shim.fs.readFileSync(languageFile, 'utf-8'));
1763
+ }
1764
+ }
1765
+ catch (err) {
1766
+ if (err instanceof SyntaxError) {
1767
+ err.message = 'syntax error in ' + languageFile;
1768
+ }
1769
+ if (err.code === 'ENOENT')
1770
+ localeLookup = {};
1771
+ else
1772
+ throw err;
1773
+ }
1774
+ this.cache[this.locale] = localeLookup;
1775
+ }
1776
+ _resolveLocaleFile(directory, locale) {
1777
+ let file = shim.resolve(directory, './', locale + '.json');
1778
+ if (this.fallbackToLanguage && !this._fileExistsSync(file) && ~locale.lastIndexOf('_')) {
1779
+ // attempt fallback to language only
1780
+ const languageFile = shim.resolve(directory, './', locale.split('_')[0] + '.json');
1781
+ if (this._fileExistsSync(languageFile))
1782
+ file = languageFile;
1783
+ }
1784
+ return file;
1785
+ }
1786
+ _fileExistsSync(file) {
1787
+ return shim.exists(file);
1788
+ }
1789
+ }
1790
+ function y18n$1(opts, _shim) {
1791
+ shim = _shim;
1792
+ const y18n = new Y18N(opts);
1793
+ return {
1794
+ __: y18n.__.bind(y18n),
1795
+ __n: y18n.__n.bind(y18n),
1796
+ setLocale: y18n.setLocale.bind(y18n),
1797
+ getLocale: y18n.getLocale.bind(y18n),
1798
+ updateLocale: y18n.updateLocale.bind(y18n),
1799
+ locale: y18n.locale
1800
+ };
1801
+ }
1802
+
1803
+ const y18n = (opts) => {
1804
+ return y18n$1(opts, shim$1)
1805
+ };
1806
+
1807
+ const REQUIRE_ERROR = 'require is not supported by ESM';
1808
+ const REQUIRE_DIRECTORY_ERROR = 'loading a directory of commands is not supported yet for ESM';
1809
+
1810
+ let __dirname;
1811
+ try {
1812
+ __dirname = fileURLToPath(import.meta.url);
1813
+ } catch (e) {
1814
+ __dirname = process.cwd();
1815
+ }
1816
+ const mainFilename = __dirname.substring(0, __dirname.lastIndexOf('node_modules'));
1817
+
1818
+ ({
1819
+ assert: {
1820
+ notStrictEqual,
1821
+ strictEqual
1822
+ },
1823
+ cliui: ui,
1824
+ findUp: escalade,
1825
+ getEnv: (key) => {
1826
+ return process.env[key]
1827
+ },
1828
+ inspect,
1829
+ getCallerFile: () => {
1830
+ throw new YError(REQUIRE_DIRECTORY_ERROR)
1831
+ },
1832
+ getProcessArgvBin,
1833
+ mainFilename: mainFilename || process.cwd(),
1834
+ Parser: yargsParser,
1835
+ path: {
1836
+ basename,
1837
+ dirname,
1838
+ extname,
1839
+ relative,
1840
+ resolve
1841
+ },
1842
+ process: {
1843
+ argv: () => process.argv,
1844
+ cwd: process.cwd,
1845
+ emitWarning: (warning, type) => process.emitWarning(warning, type),
1846
+ execPath: () => process.execPath,
1847
+ exit: process.exit,
1848
+ nextTick: process.nextTick,
1849
+ stdColumns: typeof process.stdout.columns !== 'undefined' ? process.stdout.columns : null
1850
+ },
1851
+ readFileSync,
1852
+ require: () => {
1853
+ throw new YError(REQUIRE_ERROR)
1854
+ },
1855
+ requireDirectory: () => {
1856
+ throw new YError(REQUIRE_DIRECTORY_ERROR)
1857
+ },
1858
+ stringWidth: (str) => {
1859
+ return [...str].length
1860
+ },
1861
+ y18n: y18n({
1862
+ directory: resolve(__dirname, '../../../locales'),
1863
+ updateFiles: false
1864
+ })
1865
+ });
20
1866
 
21
1867
  var name = "@pragmatic-divops/cli";
22
1868
  var description = "cli for various organization tools";
23
1869
  var license = "MIT";
24
- var version = "1.8.0";
1870
+ var version = "1.9.0";
1871
+ var type = "module";
25
1872
  var author = "Matt Travi <npm@travi.org> (https://matt.travi.org/)";
26
1873
  var repository = "pragmatic-divops/cli";
27
1874
  var bugs = "https://github.com/pragmatic-divops/cli/issues";
@@ -43,13 +1890,11 @@ var scripts = {
43
1890
  watch: "run-s 'build:js -- --watch'",
44
1891
  prepack: "run-s build",
45
1892
  "test:unit": "cross-env NODE_ENV=test c8 run-s test:unit:base",
46
- "test:unit:base": "npm-run-all --print-label --parallel test:unit:mocha test:unit:vitest",
47
- "test:unit:vitest": "DEBUG=any vitest run",
48
- "test:unit:mocha": "mocha 'src/**/*-test.js'",
1893
+ "test:unit:base": "DEBUG=any vitest run",
49
1894
  "lint:peer": "npm ls >/dev/null",
50
1895
  "lint:gherkin": "gherkin-lint",
51
1896
  "test:integration": "run-s 'test:integration:base -- --profile noWip'",
52
- "test:integration:base": "DEBUG=any cucumber-js test/integration --profile base",
1897
+ "test:integration:base": "NODE_OPTIONS=\"--loader=testdouble --enable-source-maps $NODE_OPTIONS\" DEBUG=any cucumber-js test/integration",
53
1898
  "test:integration:debug": "DEBUG=test run-s test:integration",
54
1899
  "test:integration:wip": "run-s 'test:integration:base -- --profile wip'",
55
1900
  "test:integration:wip:debug": "DEBUG=test run-s 'test:integration:wip'",
@@ -78,7 +1923,6 @@ var dependencies = {
78
1923
  "@form8ion/renovate-scaffolder": "1.8.0",
79
1924
  "@travi/github-scaffolder": "8.0.4",
80
1925
  "@travi/netlify-scaffolder": "1.6.0",
81
- "source-map-support": "0.5.21",
82
1926
  "update-notifier": "5.1.0",
83
1927
  yargs: "17.7.1"
84
1928
  };
@@ -89,7 +1933,6 @@ var devDependencies = {
89
1933
  "@pragmatic-divops/commitlint-config": "1.0.31",
90
1934
  "@pragmatic-divops/eslint-config": "1.0.66",
91
1935
  "@pragmatic-divops/eslint-config-cucumber": "1.0.1",
92
- "@pragmatic-divops/eslint-config-mocha": "1.0.9",
93
1936
  "@pragmatic-divops/remark-preset": "3.0.2",
94
1937
  "@rollup/plugin-node-resolve": "15.0.1",
95
1938
  "@travi/any": "2.1.8",
@@ -105,7 +1948,6 @@ var devDependencies = {
105
1948
  husky: "8.0.3",
106
1949
  "jest-when": "3.5.2",
107
1950
  "lockfile-lint": "4.10.1",
108
- mocha: "10.2.0",
109
1951
  "mock-fs": "5.2.0",
110
1952
  nock: "13.3.0",
111
1953
  "npm-run-all": "4.1.5",
@@ -116,7 +1958,6 @@ var devDependencies = {
116
1958
  "rollup-plugin-auto-external": "2.0.0",
117
1959
  "rollup-plugin-executable": "1.6.3",
118
1960
  "rollup-plugin-json": "4.0.0",
119
- sinon: "15.0.2",
120
1961
  testdouble: "3.17.0",
121
1962
  vitest: "0.29.3"
122
1963
  };
@@ -125,6 +1966,7 @@ var pkg = {
125
1966
  description: description,
126
1967
  license: license,
127
1968
  version: version,
1969
+ type: type,
128
1970
  author: author,
129
1971
  repository: repository,
130
1972
  bugs: bugs,
@@ -140,7 +1982,7 @@ var pkg = {
140
1982
  function javascriptScaffolderFactory(decisions) {
141
1983
  const scope = '@pragmatic-divops';
142
1984
 
143
- return options => javascript$1.scaffold({
1985
+ return options => scaffold({
144
1986
  ...options,
145
1987
  configs: {
146
1988
  eslint: {scope},
@@ -149,17 +1991,17 @@ function javascriptScaffolderFactory(decisions) {
149
1991
  commitlint: {name: scope, packageName: `${scope}/commitlint-config`}
150
1992
  },
151
1993
  overrides: {npmAccount: 'form8ion'},
152
- ciServices: {'GitHub Actions': {scaffolder: githubActionsNodeCi.scaffold, public: true}},
153
- hosts: {Netlify: {projectTypes: ['static'], scaffolder: netlifyScaffolder.scaffold}},
154
- applicationTypes: {Gatsby: {scaffolder: gatsby.scaffold}},
155
- packageTypes: {'ESLint Config': {scaffolder: eslintConfigExtender.scaffold}},
156
- unitTestFrameworks: {mocha: {scaffolder: mochaScaffolder.scaffold}},
1994
+ ciServices: {'GitHub Actions': {scaffolder: scaffold$1, public: true}},
1995
+ hosts: {Netlify: {projectTypes: ['static'], scaffolder: scaffold$2}},
1996
+ applicationTypes: {Gatsby: {scaffolder: scaffold$3}},
1997
+ packageTypes: {'ESLint Config': {scaffolder: scaffold$4}},
1998
+ unitTestFrameworks: {mocha: {scaffolder: scaffold$5}},
157
1999
  decisions
158
2000
  });
159
2001
  }
160
2002
 
161
2003
  function githubPromptFactory(decisions) {
162
- return () => githubScaffolder.prompt({account: 'pragmatic-divops', decisions});
2004
+ return () => prompt({account: 'pragmatic-divops', decisions});
163
2005
  }
164
2006
 
165
2007
  const traviName = 'Matt Travi';
@@ -168,42 +2010,42 @@ const orgName = 'pragmatic-divops';
168
2010
  function defineDecisions(providedDecisions) {
169
2011
  return {
170
2012
  ...providedDecisions,
171
- [project.questionNames.COPYRIGHT_HOLDER]: traviName,
172
- [project.questionNames.REPO_HOST]: 'GitHub',
173
- [project.questionNames.REPO_OWNER]: orgName,
174
- [project.questionNames.DEPENDENCY_UPDATER]: 'Renovate',
175
- [javascript$1.questionNames.AUTHOR_NAME]: traviName,
176
- [javascript$1.questionNames.AUTHOR_EMAIL]: 'npm@travi.org',
177
- [javascript$1.questionNames.AUTHOR_URL]: 'https://matt.travi.org',
178
- [javascript$1.questionNames.UNIT_TEST_FRAMEWORK]: 'mocha',
179
- [javascript$1.questionNames.SCOPE]: orgName,
180
- [javascript$1.questionNames.CI_SERVICE]: 'GitHub Actions',
181
- [javascript$1.questionNames.PACKAGE_MANAGER]: javascriptCore.packageManagers.NPM
2013
+ [questionNames.COPYRIGHT_HOLDER]: traviName,
2014
+ [questionNames.REPO_HOST]: 'GitHub',
2015
+ [questionNames.REPO_OWNER]: orgName,
2016
+ [questionNames.DEPENDENCY_UPDATER]: 'Renovate',
2017
+ [questionNames$1.AUTHOR_NAME]: traviName,
2018
+ [questionNames$1.AUTHOR_EMAIL]: 'npm@travi.org',
2019
+ [questionNames$1.AUTHOR_URL]: 'https://matt.travi.org',
2020
+ [questionNames$1.UNIT_TEST_FRAMEWORK]: 'mocha',
2021
+ [questionNames$1.SCOPE]: orgName,
2022
+ [questionNames$1.CI_SERVICE]: 'GitHub Actions',
2023
+ [questionNames$1.PACKAGE_MANAGER]: packageManagers.NPM
182
2024
  };
183
2025
  }
184
2026
 
185
2027
  function defineScaffoldOptions(decisions) {
186
2028
  return {
187
2029
  languages: {JavaScript: javascriptScaffolderFactory(decisions)},
188
- vcsHosts: {GitHub: {scaffolder: githubScaffolder.scaffold, prompt: githubPromptFactory(decisions), public: true}},
2030
+ vcsHosts: {GitHub: {scaffolder: scaffold$6, prompt: githubPromptFactory(decisions), public: true}},
189
2031
  overrides: {copyrightHolder: traviName},
190
- dependencyUpdaters: {Renovate: {scaffolder: renovateScaffolder.scaffold}},
2032
+ dependencyUpdaters: {Renovate: {scaffolder: scaffold$7}},
191
2033
  decisions
192
2034
  };
193
2035
  }
194
2036
 
195
2037
  function handler$2(providedDecisions) {
196
- return project.scaffold(defineScaffoldOptions(defineDecisions(providedDecisions)));
2038
+ return scaffold$8(defineScaffoldOptions(defineDecisions(providedDecisions)));
197
2039
  }
198
2040
 
199
2041
  const command$2 = 'scaffold';
200
2042
  const describe$2 = 'Scaffold a new project';
201
2043
 
202
2044
  var scaffoldCommand = /*#__PURE__*/Object.freeze({
203
- __proto__: null,
204
- command: command$2,
205
- describe: describe$2,
206
- handler: handler$2
2045
+ __proto__: null,
2046
+ command: command$2,
2047
+ describe: describe$2,
2048
+ handler: handler$2
207
2049
  });
208
2050
 
209
2051
  const packageScope = '@pragmatic-divops';
@@ -222,25 +2064,25 @@ const javascriptConfigs = {
222
2064
  };
223
2065
 
224
2066
  function javascript(options) {
225
- return javascript$1.lift({...options, configs: javascriptConfigs});
2067
+ return lift({...options, configs: javascriptConfigs});
226
2068
  }
227
2069
 
228
2070
  function getEnhancedCodecovScaffolder() {
229
- return options => codecov.scaffold({...options, visibility: 'Public'});
2071
+ return options => scaffold$9({...options, visibility: 'Public'});
230
2072
  }
231
2073
 
232
2074
  function handler$1({decisions}) {
233
- return lift.lift({
2075
+ return lift$1({
234
2076
  decisions,
235
2077
  scaffolders: {
236
- Renovate: renovateScaffolder.scaffold,
237
- Cucumber: cucumberScaffolder.scaffold,
2078
+ Renovate: scaffold$7,
2079
+ Cucumber: scaffold$a,
238
2080
  Codecov: getEnhancedCodecovScaffolder()
239
2081
  },
240
2082
  enhancers: {
241
- JavaScript: {test: javascript$1.test, lift: javascript},
242
- Renovate: {test: renovateScaffolder.predicate, lift: renovateScaffolder.lift},
243
- 'GitHub Actions CI': {test: githubActionsNodeCi.test, lift: githubActionsNodeCi.lift}
2083
+ JavaScript: {test: test, lift: javascript},
2084
+ Renovate: {test: predicate, lift: lift$2},
2085
+ 'GitHub Actions CI': {test: test$1, lift: lift$3}
244
2086
  }
245
2087
  });
246
2088
  }
@@ -249,24 +2091,24 @@ const command$1 = 'lift';
249
2091
  const describe$1 = 'Lift an existing project with additional functionality';
250
2092
 
251
2093
  var liftCommand = /*#__PURE__*/Object.freeze({
252
- __proto__: null,
253
- command: command$1,
254
- describe: describe$1,
255
- handler: handler$1
2094
+ __proto__: null,
2095
+ command: command$1,
2096
+ describe: describe$1,
2097
+ handler: handler$1
256
2098
  });
257
2099
 
258
2100
  function handler(providedDecisions) {
259
- return eslintConfigExtender.extendEslintConfig(defineScaffoldOptions(defineDecisions(providedDecisions)), javascriptScaffolderFactory);
2101
+ return extendEslintConfig(defineScaffoldOptions(defineDecisions(providedDecisions)), javascriptScaffolderFactory);
260
2102
  }
261
2103
 
262
2104
  const command = 'extend-eslint-config';
263
2105
  const describe = 'Extend a @form8ion shareable ESLint config';
264
2106
 
265
2107
  var extendEslintConfigCommand = /*#__PURE__*/Object.freeze({
266
- __proto__: null,
267
- command: command,
268
- describe: describe,
269
- handler: handler
2108
+ __proto__: null,
2109
+ command: command,
2110
+ describe: describe,
2111
+ handler: handler
270
2112
  });
271
2113
 
272
2114
  function cli (yargs) {
@@ -282,7 +2124,7 @@ function cli (yargs) {
282
2124
  .argv;
283
2125
  }
284
2126
 
285
- cli(yargs);
2127
+ cli(yargs(hideBin(process.argv)));
286
2128
 
287
2129
  updateNotifier({pkg}).notify();
288
2130
  //# sourceMappingURL=pragmatic-divops.js.map