@sveltejs/kit 1.0.0-next.31 → 1.0.0-next.310

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/README.md +12 -9
  2. package/assets/app/env.js +20 -0
  3. package/assets/app/navigation.js +24 -0
  4. package/assets/app/paths.js +1 -0
  5. package/assets/app/stores.js +97 -0
  6. package/assets/client/singletons.js +13 -0
  7. package/assets/client/start.js +1655 -0
  8. package/assets/components/error.svelte +18 -2
  9. package/assets/env.js +8 -0
  10. package/assets/paths.js +13 -0
  11. package/assets/server/index.js +2862 -0
  12. package/dist/chunks/amp_hook.js +56 -0
  13. package/dist/chunks/cert.js +28154 -0
  14. package/dist/chunks/constants.js +663 -0
  15. package/dist/chunks/filesystem.js +110 -0
  16. package/dist/chunks/index.js +515 -0
  17. package/dist/chunks/index2.js +1326 -0
  18. package/dist/chunks/index3.js +118 -0
  19. package/dist/chunks/index4.js +185 -0
  20. package/dist/chunks/index5.js +251 -0
  21. package/dist/chunks/index6.js +15585 -0
  22. package/dist/chunks/index7.js +4207 -0
  23. package/dist/chunks/misc.js +78 -0
  24. package/dist/chunks/multipart-parser.js +449 -0
  25. package/dist/chunks/object.js +83 -0
  26. package/dist/chunks/sync.js +983 -0
  27. package/dist/chunks/url.js +56 -0
  28. package/dist/cli.js +1023 -91
  29. package/dist/hooks.js +28 -0
  30. package/dist/install-fetch.js +6518 -0
  31. package/dist/node.js +94 -0
  32. package/package.json +92 -54
  33. package/svelte-kit.js +2 -0
  34. package/types/ambient.d.ts +298 -0
  35. package/types/index.d.ts +258 -0
  36. package/types/internal.d.ts +314 -0
  37. package/types/private.d.ts +269 -0
  38. package/CHANGELOG.md +0 -344
  39. package/assets/runtime/app/navigation.js +0 -23
  40. package/assets/runtime/app/navigation.js.map +0 -1
  41. package/assets/runtime/app/paths.js +0 -2
  42. package/assets/runtime/app/paths.js.map +0 -1
  43. package/assets/runtime/app/stores.js +0 -78
  44. package/assets/runtime/app/stores.js.map +0 -1
  45. package/assets/runtime/internal/singletons.js +0 -15
  46. package/assets/runtime/internal/singletons.js.map +0 -1
  47. package/assets/runtime/internal/start.js +0 -591
  48. package/assets/runtime/internal/start.js.map +0 -1
  49. package/assets/runtime/utils-85ebcc60.js +0 -18
  50. package/assets/runtime/utils-85ebcc60.js.map +0 -1
  51. package/dist/api.js +0 -44
  52. package/dist/api.js.map +0 -1
  53. package/dist/cli.js.map +0 -1
  54. package/dist/create_app.js +0 -580
  55. package/dist/create_app.js.map +0 -1
  56. package/dist/index.js +0 -375
  57. package/dist/index.js.map +0 -1
  58. package/dist/index2.js +0 -12205
  59. package/dist/index2.js.map +0 -1
  60. package/dist/index3.js +0 -549
  61. package/dist/index3.js.map +0 -1
  62. package/dist/index4.js +0 -74
  63. package/dist/index4.js.map +0 -1
  64. package/dist/index5.js +0 -468
  65. package/dist/index5.js.map +0 -1
  66. package/dist/index6.js +0 -735
  67. package/dist/index6.js.map +0 -1
  68. package/dist/renderer.js +0 -2425
  69. package/dist/renderer.js.map +0 -1
  70. package/dist/standard.js +0 -103
  71. package/dist/standard.js.map +0 -1
  72. package/dist/utils.js +0 -58
  73. package/dist/utils.js.map +0 -1
  74. package/svelte-kit +0 -3
@@ -0,0 +1,4207 @@
1
+ import require$$0$1 from 'util';
2
+ import require$$0 from 'os';
3
+ import fs__default from 'fs';
4
+ import http$1 from 'http';
5
+ import https$1 from 'https';
6
+ import path__default from 'path';
7
+ import require$$0$2 from 'events';
8
+ import require$$1 from 'child_process';
9
+ import require$$0$3 from 'domain';
10
+ import 'querystring';
11
+ import 'url';
12
+ import require$$10 from 'vm';
13
+
14
+ function _mergeNamespaces(n, m) {
15
+ m.forEach(function (e) {
16
+ e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) {
17
+ if (k !== 'default' && !(k in n)) {
18
+ var d = Object.getOwnPropertyDescriptor(e, k);
19
+ Object.defineProperty(n, k, d.get ? d : {
20
+ enumerable: true,
21
+ get: function () { return e[k]; }
22
+ });
23
+ }
24
+ });
25
+ });
26
+ return Object.freeze(n);
27
+ }
28
+
29
+ var amphtmlValidator = {};
30
+
31
+ var safe = {exports: {}};
32
+
33
+ var colors$1 = {exports: {}};
34
+
35
+ var styles = {exports: {}};
36
+
37
+ /*
38
+ The MIT License (MIT)
39
+
40
+ Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
41
+
42
+ Permission is hereby granted, free of charge, to any person obtaining a copy
43
+ of this software and associated documentation files (the "Software"), to deal
44
+ in the Software without restriction, including without limitation the rights
45
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
46
+ copies of the Software, and to permit persons to whom the Software is
47
+ furnished to do so, subject to the following conditions:
48
+
49
+ The above copyright notice and this permission notice shall be included in
50
+ all copies or substantial portions of the Software.
51
+
52
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
53
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
54
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
55
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
56
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
57
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
58
+ THE SOFTWARE.
59
+
60
+ */
61
+
62
+ (function (module) {
63
+ var styles = {};
64
+ module['exports'] = styles;
65
+
66
+ var codes = {
67
+ reset: [0, 0],
68
+
69
+ bold: [1, 22],
70
+ dim: [2, 22],
71
+ italic: [3, 23],
72
+ underline: [4, 24],
73
+ inverse: [7, 27],
74
+ hidden: [8, 28],
75
+ strikethrough: [9, 29],
76
+
77
+ black: [30, 39],
78
+ red: [31, 39],
79
+ green: [32, 39],
80
+ yellow: [33, 39],
81
+ blue: [34, 39],
82
+ magenta: [35, 39],
83
+ cyan: [36, 39],
84
+ white: [37, 39],
85
+ gray: [90, 39],
86
+ grey: [90, 39],
87
+
88
+ brightRed: [91, 39],
89
+ brightGreen: [92, 39],
90
+ brightYellow: [93, 39],
91
+ brightBlue: [94, 39],
92
+ brightMagenta: [95, 39],
93
+ brightCyan: [96, 39],
94
+ brightWhite: [97, 39],
95
+
96
+ bgBlack: [40, 49],
97
+ bgRed: [41, 49],
98
+ bgGreen: [42, 49],
99
+ bgYellow: [43, 49],
100
+ bgBlue: [44, 49],
101
+ bgMagenta: [45, 49],
102
+ bgCyan: [46, 49],
103
+ bgWhite: [47, 49],
104
+ bgGray: [100, 49],
105
+ bgGrey: [100, 49],
106
+
107
+ bgBrightRed: [101, 49],
108
+ bgBrightGreen: [102, 49],
109
+ bgBrightYellow: [103, 49],
110
+ bgBrightBlue: [104, 49],
111
+ bgBrightMagenta: [105, 49],
112
+ bgBrightCyan: [106, 49],
113
+ bgBrightWhite: [107, 49],
114
+
115
+ // legacy styles for colors pre v1.0.0
116
+ blackBG: [40, 49],
117
+ redBG: [41, 49],
118
+ greenBG: [42, 49],
119
+ yellowBG: [43, 49],
120
+ blueBG: [44, 49],
121
+ magentaBG: [45, 49],
122
+ cyanBG: [46, 49],
123
+ whiteBG: [47, 49],
124
+
125
+ };
126
+
127
+ Object.keys(codes).forEach(function(key) {
128
+ var val = codes[key];
129
+ var style = styles[key] = [];
130
+ style.open = '\u001b[' + val[0] + 'm';
131
+ style.close = '\u001b[' + val[1] + 'm';
132
+ });
133
+ }(styles));
134
+
135
+ /*
136
+ MIT License
137
+
138
+ Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
139
+
140
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
141
+ this software and associated documentation files (the "Software"), to deal in
142
+ the Software without restriction, including without limitation the rights to
143
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
144
+ of the Software, and to permit persons to whom the Software is furnished to do
145
+ so, subject to the following conditions:
146
+
147
+ The above copyright notice and this permission notice shall be included in all
148
+ copies or substantial portions of the Software.
149
+
150
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
151
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
152
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
153
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
154
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
155
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
156
+ SOFTWARE.
157
+ */
158
+
159
+ var hasFlag$1 = function(flag, argv) {
160
+ argv = argv || process.argv;
161
+
162
+ var terminatorPos = argv.indexOf('--');
163
+ var prefix = /^-{1,2}/.test(flag) ? '' : '--';
164
+ var pos = argv.indexOf(prefix + flag);
165
+
166
+ return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
167
+ };
168
+
169
+ /*
170
+ The MIT License (MIT)
171
+
172
+ Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
173
+
174
+ Permission is hereby granted, free of charge, to any person obtaining a copy
175
+ of this software and associated documentation files (the "Software"), to deal
176
+ in the Software without restriction, including without limitation the rights
177
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
178
+ copies of the Software, and to permit persons to whom the Software is
179
+ furnished to do so, subject to the following conditions:
180
+
181
+ The above copyright notice and this permission notice shall be included in
182
+ all copies or substantial portions of the Software.
183
+
184
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
185
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
186
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
187
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
188
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
189
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
190
+ THE SOFTWARE.
191
+
192
+ */
193
+
194
+ var os = require$$0;
195
+ var hasFlag = hasFlag$1;
196
+
197
+ var env = process.env;
198
+
199
+ var forceColor = void 0;
200
+ if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) {
201
+ forceColor = false;
202
+ } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true')
203
+ || hasFlag('color=always')) {
204
+ forceColor = true;
205
+ }
206
+ if ('FORCE_COLOR' in env) {
207
+ forceColor = env.FORCE_COLOR.length === 0
208
+ || parseInt(env.FORCE_COLOR, 10) !== 0;
209
+ }
210
+
211
+ function translateLevel(level) {
212
+ if (level === 0) {
213
+ return false;
214
+ }
215
+
216
+ return {
217
+ level: level,
218
+ hasBasic: true,
219
+ has256: level >= 2,
220
+ has16m: level >= 3,
221
+ };
222
+ }
223
+
224
+ function supportsColor(stream) {
225
+ if (forceColor === false) {
226
+ return 0;
227
+ }
228
+
229
+ if (hasFlag('color=16m') || hasFlag('color=full')
230
+ || hasFlag('color=truecolor')) {
231
+ return 3;
232
+ }
233
+
234
+ if (hasFlag('color=256')) {
235
+ return 2;
236
+ }
237
+
238
+ if (stream && !stream.isTTY && forceColor !== true) {
239
+ return 0;
240
+ }
241
+
242
+ var min = forceColor ? 1 : 0;
243
+
244
+ if (process.platform === 'win32') {
245
+ // Node.js 7.5.0 is the first version of Node.js to include a patch to
246
+ // libuv that enables 256 color output on Windows. Anything earlier and it
247
+ // won't work. However, here we target Node.js 8 at minimum as it is an LTS
248
+ // release, and Node.js 7 is not. Windows 10 build 10586 is the first
249
+ // Windows release that supports 256 colors. Windows 10 build 14931 is the
250
+ // first release that supports 16m/TrueColor.
251
+ var osRelease = os.release().split('.');
252
+ if (Number(process.versions.node.split('.')[0]) >= 8
253
+ && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
254
+ return Number(osRelease[2]) >= 14931 ? 3 : 2;
255
+ }
256
+
257
+ return 1;
258
+ }
259
+
260
+ if ('CI' in env) {
261
+ if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(function(sign) {
262
+ return sign in env;
263
+ }) || env.CI_NAME === 'codeship') {
264
+ return 1;
265
+ }
266
+
267
+ return min;
268
+ }
269
+
270
+ if ('TEAMCITY_VERSION' in env) {
271
+ return (/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0
272
+ );
273
+ }
274
+
275
+ if ('TERM_PROGRAM' in env) {
276
+ var version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
277
+
278
+ switch (env.TERM_PROGRAM) {
279
+ case 'iTerm.app':
280
+ return version >= 3 ? 3 : 2;
281
+ case 'Hyper':
282
+ return 3;
283
+ case 'Apple_Terminal':
284
+ return 2;
285
+ // No default
286
+ }
287
+ }
288
+
289
+ if (/-256(color)?$/i.test(env.TERM)) {
290
+ return 2;
291
+ }
292
+
293
+ if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
294
+ return 1;
295
+ }
296
+
297
+ if ('COLORTERM' in env) {
298
+ return 1;
299
+ }
300
+
301
+ if (env.TERM === 'dumb') {
302
+ return min;
303
+ }
304
+
305
+ return min;
306
+ }
307
+
308
+ function getSupportLevel(stream) {
309
+ var level = supportsColor(stream);
310
+ return translateLevel(level);
311
+ }
312
+
313
+ var supportsColors = {
314
+ supportsColor: getSupportLevel,
315
+ stdout: getSupportLevel(process.stdout),
316
+ stderr: getSupportLevel(process.stderr),
317
+ };
318
+
319
+ var trap = {exports: {}};
320
+
321
+ (function (module) {
322
+ module['exports'] = function runTheTrap(text, options) {
323
+ var result = '';
324
+ text = text || 'Run the trap, drop the bass';
325
+ text = text.split('');
326
+ var trap = {
327
+ a: ['\u0040', '\u0104', '\u023a', '\u0245', '\u0394', '\u039b', '\u0414'],
328
+ b: ['\u00df', '\u0181', '\u0243', '\u026e', '\u03b2', '\u0e3f'],
329
+ c: ['\u00a9', '\u023b', '\u03fe'],
330
+ d: ['\u00d0', '\u018a', '\u0500', '\u0501', '\u0502', '\u0503'],
331
+ e: ['\u00cb', '\u0115', '\u018e', '\u0258', '\u03a3', '\u03be', '\u04bc',
332
+ '\u0a6c'],
333
+ f: ['\u04fa'],
334
+ g: ['\u0262'],
335
+ h: ['\u0126', '\u0195', '\u04a2', '\u04ba', '\u04c7', '\u050a'],
336
+ i: ['\u0f0f'],
337
+ j: ['\u0134'],
338
+ k: ['\u0138', '\u04a0', '\u04c3', '\u051e'],
339
+ l: ['\u0139'],
340
+ m: ['\u028d', '\u04cd', '\u04ce', '\u0520', '\u0521', '\u0d69'],
341
+ n: ['\u00d1', '\u014b', '\u019d', '\u0376', '\u03a0', '\u048a'],
342
+ o: ['\u00d8', '\u00f5', '\u00f8', '\u01fe', '\u0298', '\u047a', '\u05dd',
343
+ '\u06dd', '\u0e4f'],
344
+ p: ['\u01f7', '\u048e'],
345
+ q: ['\u09cd'],
346
+ r: ['\u00ae', '\u01a6', '\u0210', '\u024c', '\u0280', '\u042f'],
347
+ s: ['\u00a7', '\u03de', '\u03df', '\u03e8'],
348
+ t: ['\u0141', '\u0166', '\u0373'],
349
+ u: ['\u01b1', '\u054d'],
350
+ v: ['\u05d8'],
351
+ w: ['\u0428', '\u0460', '\u047c', '\u0d70'],
352
+ x: ['\u04b2', '\u04fe', '\u04fc', '\u04fd'],
353
+ y: ['\u00a5', '\u04b0', '\u04cb'],
354
+ z: ['\u01b5', '\u0240'],
355
+ };
356
+ text.forEach(function(c) {
357
+ c = c.toLowerCase();
358
+ var chars = trap[c] || [' '];
359
+ var rand = Math.floor(Math.random() * chars.length);
360
+ if (typeof trap[c] !== 'undefined') {
361
+ result += trap[c][rand];
362
+ } else {
363
+ result += c;
364
+ }
365
+ });
366
+ return result;
367
+ };
368
+ }(trap));
369
+
370
+ var zalgo = {exports: {}};
371
+
372
+ (function (module) {
373
+ // please no
374
+ module['exports'] = function zalgo(text, options) {
375
+ text = text || ' he is here ';
376
+ var soul = {
377
+ 'up': [
378
+ '̍', '̎', '̄', '̅',
379
+ '̿', '̑', '̆', '̐',
380
+ '͒', '͗', '͑', '̇',
381
+ '̈', '̊', '͂', '̓',
382
+ '̈', '͊', '͋', '͌',
383
+ '̃', '̂', '̌', '͐',
384
+ '̀', '́', '̋', '̏',
385
+ '̒', '̓', '̔', '̽',
386
+ '̉', 'ͣ', 'ͤ', 'ͥ',
387
+ 'ͦ', 'ͧ', 'ͨ', 'ͩ',
388
+ 'ͪ', 'ͫ', 'ͬ', 'ͭ',
389
+ 'ͮ', 'ͯ', '̾', '͛',
390
+ '͆', '̚',
391
+ ],
392
+ 'down': [
393
+ '̖', '̗', '̘', '̙',
394
+ '̜', '̝', '̞', '̟',
395
+ '̠', '̤', '̥', '̦',
396
+ '̩', '̪', '̫', '̬',
397
+ '̭', '̮', '̯', '̰',
398
+ '̱', '̲', '̳', '̹',
399
+ '̺', '̻', '̼', 'ͅ',
400
+ '͇', '͈', '͉', '͍',
401
+ '͎', '͓', '͔', '͕',
402
+ '͖', '͙', '͚', '̣',
403
+ ],
404
+ 'mid': [
405
+ '̕', '̛', '̀', '́',
406
+ '͘', '̡', '̢', '̧',
407
+ '̨', '̴', '̵', '̶',
408
+ '͜', '͝', '͞',
409
+ '͟', '͠', '͢', '̸',
410
+ '̷', '͡', ' ҉',
411
+ ],
412
+ };
413
+ var all = [].concat(soul.up, soul.down, soul.mid);
414
+
415
+ function randomNumber(range) {
416
+ var r = Math.floor(Math.random() * range);
417
+ return r;
418
+ }
419
+
420
+ function isChar(character) {
421
+ var bool = false;
422
+ all.filter(function(i) {
423
+ bool = (i === character);
424
+ });
425
+ return bool;
426
+ }
427
+
428
+
429
+ function heComes(text, options) {
430
+ var result = '';
431
+ var counts;
432
+ var l;
433
+ options = options || {};
434
+ options['up'] =
435
+ typeof options['up'] !== 'undefined' ? options['up'] : true;
436
+ options['mid'] =
437
+ typeof options['mid'] !== 'undefined' ? options['mid'] : true;
438
+ options['down'] =
439
+ typeof options['down'] !== 'undefined' ? options['down'] : true;
440
+ options['size'] =
441
+ typeof options['size'] !== 'undefined' ? options['size'] : 'maxi';
442
+ text = text.split('');
443
+ for (l in text) {
444
+ if (isChar(l)) {
445
+ continue;
446
+ }
447
+ result = result + text[l];
448
+ counts = {'up': 0, 'down': 0, 'mid': 0};
449
+ switch (options.size) {
450
+ case 'mini':
451
+ counts.up = randomNumber(8);
452
+ counts.mid = randomNumber(2);
453
+ counts.down = randomNumber(8);
454
+ break;
455
+ case 'maxi':
456
+ counts.up = randomNumber(16) + 3;
457
+ counts.mid = randomNumber(4) + 1;
458
+ counts.down = randomNumber(64) + 3;
459
+ break;
460
+ default:
461
+ counts.up = randomNumber(8) + 1;
462
+ counts.mid = randomNumber(6) / 2;
463
+ counts.down = randomNumber(8) + 1;
464
+ break;
465
+ }
466
+
467
+ var arr = ['up', 'mid', 'down'];
468
+ for (var d in arr) {
469
+ var index = arr[d];
470
+ for (var i = 0; i <= counts[index]; i++) {
471
+ if (options[index]) {
472
+ result = result + soul[index][randomNumber(soul[index].length)];
473
+ }
474
+ }
475
+ }
476
+ }
477
+ return result;
478
+ }
479
+ // don't summon him
480
+ return heComes(text, options);
481
+ };
482
+ }(zalgo));
483
+
484
+ var america = {exports: {}};
485
+
486
+ (function (module) {
487
+ module['exports'] = function(colors) {
488
+ return function(letter, i, exploded) {
489
+ if (letter === ' ') return letter;
490
+ switch (i%3) {
491
+ case 0: return colors.red(letter);
492
+ case 1: return colors.white(letter);
493
+ case 2: return colors.blue(letter);
494
+ }
495
+ };
496
+ };
497
+ }(america));
498
+
499
+ var zebra = {exports: {}};
500
+
501
+ (function (module) {
502
+ module['exports'] = function(colors) {
503
+ return function(letter, i, exploded) {
504
+ return i % 2 === 0 ? letter : colors.inverse(letter);
505
+ };
506
+ };
507
+ }(zebra));
508
+
509
+ var rainbow = {exports: {}};
510
+
511
+ (function (module) {
512
+ module['exports'] = function(colors) {
513
+ // RoY G BiV
514
+ var rainbowColors = ['red', 'yellow', 'green', 'blue', 'magenta'];
515
+ return function(letter, i, exploded) {
516
+ if (letter === ' ') {
517
+ return letter;
518
+ } else {
519
+ return colors[rainbowColors[i++ % rainbowColors.length]](letter);
520
+ }
521
+ };
522
+ };
523
+ }(rainbow));
524
+
525
+ var random = {exports: {}};
526
+
527
+ (function (module) {
528
+ module['exports'] = function(colors) {
529
+ var available = ['underline', 'inverse', 'grey', 'yellow', 'red', 'green',
530
+ 'blue', 'white', 'cyan', 'magenta', 'brightYellow', 'brightRed',
531
+ 'brightGreen', 'brightBlue', 'brightWhite', 'brightCyan', 'brightMagenta'];
532
+ return function(letter, i, exploded) {
533
+ return letter === ' ' ? letter :
534
+ colors[
535
+ available[Math.round(Math.random() * (available.length - 2))]
536
+ ](letter);
537
+ };
538
+ };
539
+ }(random));
540
+
541
+ /*
542
+
543
+ The MIT License (MIT)
544
+
545
+ Original Library
546
+ - Copyright (c) Marak Squires
547
+
548
+ Additional functionality
549
+ - Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
550
+
551
+ Permission is hereby granted, free of charge, to any person obtaining a copy
552
+ of this software and associated documentation files (the "Software"), to deal
553
+ in the Software without restriction, including without limitation the rights
554
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
555
+ copies of the Software, and to permit persons to whom the Software is
556
+ furnished to do so, subject to the following conditions:
557
+
558
+ The above copyright notice and this permission notice shall be included in
559
+ all copies or substantial portions of the Software.
560
+
561
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
562
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
563
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
564
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
565
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
566
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
567
+ THE SOFTWARE.
568
+
569
+ */
570
+
571
+ (function (module) {
572
+ var colors = {};
573
+ module['exports'] = colors;
574
+
575
+ colors.themes = {};
576
+
577
+ var util = require$$0$1;
578
+ var ansiStyles = colors.styles = styles.exports;
579
+ var defineProps = Object.defineProperties;
580
+ var newLineRegex = new RegExp(/[\r\n]+/g);
581
+
582
+ colors.supportsColor = supportsColors.supportsColor;
583
+
584
+ if (typeof colors.enabled === 'undefined') {
585
+ colors.enabled = colors.supportsColor() !== false;
586
+ }
587
+
588
+ colors.enable = function() {
589
+ colors.enabled = true;
590
+ };
591
+
592
+ colors.disable = function() {
593
+ colors.enabled = false;
594
+ };
595
+
596
+ colors.stripColors = colors.strip = function(str) {
597
+ return ('' + str).replace(/\x1B\[\d+m/g, '');
598
+ };
599
+
600
+ // eslint-disable-next-line no-unused-vars
601
+ colors.stylize = function stylize(str, style) {
602
+ if (!colors.enabled) {
603
+ return str+'';
604
+ }
605
+
606
+ var styleMap = ansiStyles[style];
607
+
608
+ // Stylize should work for non-ANSI styles, too
609
+ if(!styleMap && style in colors){
610
+ // Style maps like trap operate as functions on strings;
611
+ // they don't have properties like open or close.
612
+ return colors[style](str);
613
+ }
614
+
615
+ return styleMap.open + str + styleMap.close;
616
+ };
617
+
618
+ var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
619
+ var escapeStringRegexp = function(str) {
620
+ if (typeof str !== 'string') {
621
+ throw new TypeError('Expected a string');
622
+ }
623
+ return str.replace(matchOperatorsRe, '\\$&');
624
+ };
625
+
626
+ function build(_styles) {
627
+ var builder = function builder() {
628
+ return applyStyle.apply(builder, arguments);
629
+ };
630
+ builder._styles = _styles;
631
+ // __proto__ is used because we must return a function, but there is
632
+ // no way to create a function with a different prototype.
633
+ builder.__proto__ = proto;
634
+ return builder;
635
+ }
636
+
637
+ var styles$1 = (function() {
638
+ var ret = {};
639
+ ansiStyles.grey = ansiStyles.gray;
640
+ Object.keys(ansiStyles).forEach(function(key) {
641
+ ansiStyles[key].closeRe =
642
+ new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
643
+ ret[key] = {
644
+ get: function() {
645
+ return build(this._styles.concat(key));
646
+ },
647
+ };
648
+ });
649
+ return ret;
650
+ })();
651
+
652
+ var proto = defineProps(function colors() {}, styles$1);
653
+
654
+ function applyStyle() {
655
+ var args = Array.prototype.slice.call(arguments);
656
+
657
+ var str = args.map(function(arg) {
658
+ // Use weak equality check so we can colorize null/undefined in safe mode
659
+ if (arg != null && arg.constructor === String) {
660
+ return arg;
661
+ } else {
662
+ return util.inspect(arg);
663
+ }
664
+ }).join(' ');
665
+
666
+ if (!colors.enabled || !str) {
667
+ return str;
668
+ }
669
+
670
+ var newLinesPresent = str.indexOf('\n') != -1;
671
+
672
+ var nestedStyles = this._styles;
673
+
674
+ var i = nestedStyles.length;
675
+ while (i--) {
676
+ var code = ansiStyles[nestedStyles[i]];
677
+ str = code.open + str.replace(code.closeRe, code.open) + code.close;
678
+ if (newLinesPresent) {
679
+ str = str.replace(newLineRegex, function(match) {
680
+ return code.close + match + code.open;
681
+ });
682
+ }
683
+ }
684
+
685
+ return str;
686
+ }
687
+
688
+ colors.setTheme = function(theme) {
689
+ if (typeof theme === 'string') {
690
+ console.log('colors.setTheme now only accepts an object, not a string. ' +
691
+ 'If you are trying to set a theme from a file, it is now your (the ' +
692
+ 'caller\'s) responsibility to require the file. The old syntax ' +
693
+ 'looked like colors.setTheme(__dirname + ' +
694
+ '\'/../themes/generic-logging.js\'); The new syntax looks like '+
695
+ 'colors.setTheme(require(__dirname + ' +
696
+ '\'/../themes/generic-logging.js\'));');
697
+ return;
698
+ }
699
+ for (var style in theme) {
700
+ (function(style) {
701
+ colors[style] = function(str) {
702
+ if (typeof theme[style] === 'object') {
703
+ var out = str;
704
+ for (var i in theme[style]) {
705
+ out = colors[theme[style][i]](out);
706
+ }
707
+ return out;
708
+ }
709
+ return colors[theme[style]](str);
710
+ };
711
+ })(style);
712
+ }
713
+ };
714
+
715
+ function init() {
716
+ var ret = {};
717
+ Object.keys(styles$1).forEach(function(name) {
718
+ ret[name] = {
719
+ get: function() {
720
+ return build([name]);
721
+ },
722
+ };
723
+ });
724
+ return ret;
725
+ }
726
+
727
+ var sequencer = function sequencer(map, str) {
728
+ var exploded = str.split('');
729
+ exploded = exploded.map(map);
730
+ return exploded.join('');
731
+ };
732
+
733
+ // custom formatter methods
734
+ colors.trap = trap.exports;
735
+ colors.zalgo = zalgo.exports;
736
+
737
+ // maps
738
+ colors.maps = {};
739
+ colors.maps.america = america.exports(colors);
740
+ colors.maps.zebra = zebra.exports(colors);
741
+ colors.maps.rainbow = rainbow.exports(colors);
742
+ colors.maps.random = random.exports(colors);
743
+
744
+ for (var map in colors.maps) {
745
+ (function(map) {
746
+ colors[map] = function(str) {
747
+ return sequencer(colors.maps[map], str);
748
+ };
749
+ })(map);
750
+ }
751
+
752
+ defineProps(colors, init());
753
+ }(colors$1));
754
+
755
+ (function (module) {
756
+ //
757
+ // Remark: Requiring this file will use the "safe" colors API,
758
+ // which will not touch String.prototype.
759
+ //
760
+ // var colors = require('colors/safe');
761
+ // colors.red("foo")
762
+ //
763
+ //
764
+ var colors = colors$1.exports;
765
+ module['exports'] = colors;
766
+ }(safe));
767
+
768
+ var commander = {exports: {}};
769
+
770
+ /**
771
+ * Module dependencies.
772
+ */
773
+
774
+ (function (module, exports) {
775
+ const EventEmitter = require$$0$2.EventEmitter;
776
+ const childProcess = require$$1;
777
+ const path = path__default;
778
+ const fs = fs__default;
779
+
780
+ // @ts-check
781
+
782
+ // Although this is a class, methods are static in style to allow override using subclass or just functions.
783
+ class Help {
784
+ constructor() {
785
+ this.helpWidth = undefined;
786
+ this.sortSubcommands = false;
787
+ this.sortOptions = false;
788
+ }
789
+
790
+ /**
791
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
792
+ *
793
+ * @param {Command} cmd
794
+ * @returns {Command[]}
795
+ */
796
+
797
+ visibleCommands(cmd) {
798
+ const visibleCommands = cmd.commands.filter(cmd => !cmd._hidden);
799
+ if (cmd._hasImplicitHelpCommand()) {
800
+ // Create a command matching the implicit help command.
801
+ const args = cmd._helpCommandnameAndArgs.split(/ +/);
802
+ const helpCommand = cmd.createCommand(args.shift())
803
+ .helpOption(false);
804
+ helpCommand.description(cmd._helpCommandDescription);
805
+ helpCommand._parseExpectedArgs(args);
806
+ visibleCommands.push(helpCommand);
807
+ }
808
+ if (this.sortSubcommands) {
809
+ visibleCommands.sort((a, b) => {
810
+ return a.name().localeCompare(b.name());
811
+ });
812
+ }
813
+ return visibleCommands;
814
+ }
815
+
816
+ /**
817
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
818
+ *
819
+ * @param {Command} cmd
820
+ * @returns {Option[]}
821
+ */
822
+
823
+ visibleOptions(cmd) {
824
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
825
+ // Implicit help
826
+ const showShortHelpFlag = cmd._hasHelpOption && cmd._helpShortFlag && !cmd._findOption(cmd._helpShortFlag);
827
+ const showLongHelpFlag = cmd._hasHelpOption && !cmd._findOption(cmd._helpLongFlag);
828
+ if (showShortHelpFlag || showLongHelpFlag) {
829
+ let helpOption;
830
+ if (!showShortHelpFlag) {
831
+ helpOption = cmd.createOption(cmd._helpLongFlag, cmd._helpDescription);
832
+ } else if (!showLongHelpFlag) {
833
+ helpOption = cmd.createOption(cmd._helpShortFlag, cmd._helpDescription);
834
+ } else {
835
+ helpOption = cmd.createOption(cmd._helpFlags, cmd._helpDescription);
836
+ }
837
+ visibleOptions.push(helpOption);
838
+ }
839
+ if (this.sortOptions) {
840
+ const getSortKey = (option) => {
841
+ // WYSIWYG for order displayed in help with short before long, no special handling for negated.
842
+ return option.short ? option.short.replace(/^-/, '') : option.long.replace(/^--/, '');
843
+ };
844
+ visibleOptions.sort((a, b) => {
845
+ return getSortKey(a).localeCompare(getSortKey(b));
846
+ });
847
+ }
848
+ return visibleOptions;
849
+ }
850
+
851
+ /**
852
+ * Get an array of the arguments which have descriptions.
853
+ *
854
+ * @param {Command} cmd
855
+ * @returns {{ term: string, description:string }[]}
856
+ */
857
+
858
+ visibleArguments(cmd) {
859
+ if (cmd._argsDescription && cmd._args.length) {
860
+ return cmd._args.map((argument) => {
861
+ return { term: argument.name, description: cmd._argsDescription[argument.name] || '' };
862
+ }, 0);
863
+ }
864
+ return [];
865
+ }
866
+
867
+ /**
868
+ * Get the command term to show in the list of subcommands.
869
+ *
870
+ * @param {Command} cmd
871
+ * @returns {string}
872
+ */
873
+
874
+ subcommandTerm(cmd) {
875
+ // Legacy. Ignores custom usage string, and nested commands.
876
+ const args = cmd._args.map(arg => humanReadableArgName(arg)).join(' ');
877
+ return cmd._name +
878
+ (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +
879
+ (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option
880
+ (args ? ' ' + args : '');
881
+ }
882
+
883
+ /**
884
+ * Get the option term to show in the list of options.
885
+ *
886
+ * @param {Option} option
887
+ * @returns {string}
888
+ */
889
+
890
+ optionTerm(option) {
891
+ return option.flags;
892
+ }
893
+
894
+ /**
895
+ * Get the longest command term length.
896
+ *
897
+ * @param {Command} cmd
898
+ * @param {Help} helper
899
+ * @returns {number}
900
+ */
901
+
902
+ longestSubcommandTermLength(cmd, helper) {
903
+ return helper.visibleCommands(cmd).reduce((max, command) => {
904
+ return Math.max(max, helper.subcommandTerm(command).length);
905
+ }, 0);
906
+ };
907
+
908
+ /**
909
+ * Get the longest option term length.
910
+ *
911
+ * @param {Command} cmd
912
+ * @param {Help} helper
913
+ * @returns {number}
914
+ */
915
+
916
+ longestOptionTermLength(cmd, helper) {
917
+ return helper.visibleOptions(cmd).reduce((max, option) => {
918
+ return Math.max(max, helper.optionTerm(option).length);
919
+ }, 0);
920
+ };
921
+
922
+ /**
923
+ * Get the longest argument term length.
924
+ *
925
+ * @param {Command} cmd
926
+ * @param {Help} helper
927
+ * @returns {number}
928
+ */
929
+
930
+ longestArgumentTermLength(cmd, helper) {
931
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
932
+ return Math.max(max, argument.term.length);
933
+ }, 0);
934
+ };
935
+
936
+ /**
937
+ * Get the command usage to be displayed at the top of the built-in help.
938
+ *
939
+ * @param {Command} cmd
940
+ * @returns {string}
941
+ */
942
+
943
+ commandUsage(cmd) {
944
+ // Usage
945
+ let cmdName = cmd._name;
946
+ if (cmd._aliases[0]) {
947
+ cmdName = cmdName + '|' + cmd._aliases[0];
948
+ }
949
+ let parentCmdNames = '';
950
+ for (let parentCmd = cmd.parent; parentCmd; parentCmd = parentCmd.parent) {
951
+ parentCmdNames = parentCmd.name() + ' ' + parentCmdNames;
952
+ }
953
+ return parentCmdNames + cmdName + ' ' + cmd.usage();
954
+ }
955
+
956
+ /**
957
+ * Get the description for the command.
958
+ *
959
+ * @param {Command} cmd
960
+ * @returns {string}
961
+ */
962
+
963
+ commandDescription(cmd) {
964
+ // @ts-ignore: overloaded return type
965
+ return cmd.description();
966
+ }
967
+
968
+ /**
969
+ * Get the command description to show in the list of subcommands.
970
+ *
971
+ * @param {Command} cmd
972
+ * @returns {string}
973
+ */
974
+
975
+ subcommandDescription(cmd) {
976
+ // @ts-ignore: overloaded return type
977
+ return cmd.description();
978
+ }
979
+
980
+ /**
981
+ * Get the option description to show in the list of options.
982
+ *
983
+ * @param {Option} option
984
+ * @return {string}
985
+ */
986
+
987
+ optionDescription(option) {
988
+ if (option.negate) {
989
+ return option.description;
990
+ }
991
+ const extraInfo = [];
992
+ if (option.argChoices) {
993
+ extraInfo.push(
994
+ // use stringify to match the display of the default value
995
+ `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`);
996
+ }
997
+ if (option.defaultValue !== undefined) {
998
+ extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
999
+ }
1000
+ if (extraInfo.length > 0) {
1001
+ return `${option.description} (${extraInfo.join(', ')})`;
1002
+ }
1003
+ return option.description;
1004
+ };
1005
+
1006
+ /**
1007
+ * Generate the built-in help text.
1008
+ *
1009
+ * @param {Command} cmd
1010
+ * @param {Help} helper
1011
+ * @returns {string}
1012
+ */
1013
+
1014
+ formatHelp(cmd, helper) {
1015
+ const termWidth = helper.padWidth(cmd, helper);
1016
+ const helpWidth = helper.helpWidth || 80;
1017
+ const itemIndentWidth = 2;
1018
+ const itemSeparatorWidth = 2; // between term and description
1019
+ function formatItem(term, description) {
1020
+ if (description) {
1021
+ const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
1022
+ return helper.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth);
1023
+ }
1024
+ return term;
1025
+ } function formatList(textArray) {
1026
+ return textArray.join('\n').replace(/^/gm, ' '.repeat(itemIndentWidth));
1027
+ }
1028
+
1029
+ // Usage
1030
+ let output = [`Usage: ${helper.commandUsage(cmd)}`, ''];
1031
+
1032
+ // Description
1033
+ const commandDescription = helper.commandDescription(cmd);
1034
+ if (commandDescription.length > 0) {
1035
+ output = output.concat([commandDescription, '']);
1036
+ }
1037
+
1038
+ // Arguments
1039
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
1040
+ return formatItem(argument.term, argument.description);
1041
+ });
1042
+ if (argumentList.length > 0) {
1043
+ output = output.concat(['Arguments:', formatList(argumentList), '']);
1044
+ }
1045
+
1046
+ // Options
1047
+ const optionList = helper.visibleOptions(cmd).map((option) => {
1048
+ return formatItem(helper.optionTerm(option), helper.optionDescription(option));
1049
+ });
1050
+ if (optionList.length > 0) {
1051
+ output = output.concat(['Options:', formatList(optionList), '']);
1052
+ }
1053
+
1054
+ // Commands
1055
+ const commandList = helper.visibleCommands(cmd).map((cmd) => {
1056
+ return formatItem(helper.subcommandTerm(cmd), helper.subcommandDescription(cmd));
1057
+ });
1058
+ if (commandList.length > 0) {
1059
+ output = output.concat(['Commands:', formatList(commandList), '']);
1060
+ }
1061
+
1062
+ return output.join('\n');
1063
+ }
1064
+
1065
+ /**
1066
+ * Calculate the pad width from the maximum term length.
1067
+ *
1068
+ * @param {Command} cmd
1069
+ * @param {Help} helper
1070
+ * @returns {number}
1071
+ */
1072
+
1073
+ padWidth(cmd, helper) {
1074
+ return Math.max(
1075
+ helper.longestOptionTermLength(cmd, helper),
1076
+ helper.longestSubcommandTermLength(cmd, helper),
1077
+ helper.longestArgumentTermLength(cmd, helper)
1078
+ );
1079
+ };
1080
+
1081
+ /**
1082
+ * Wrap the given string to width characters per line, with lines after the first indented.
1083
+ * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
1084
+ *
1085
+ * @param {string} str
1086
+ * @param {number} width
1087
+ * @param {number} indent
1088
+ * @param {number} [minColumnWidth=40]
1089
+ * @return {string}
1090
+ *
1091
+ */
1092
+
1093
+ wrap(str, width, indent, minColumnWidth = 40) {
1094
+ // Detect manually wrapped and indented strings by searching for line breaks
1095
+ // followed by multiple spaces/tabs.
1096
+ if (str.match(/[\n]\s+/)) return str;
1097
+ // Do not wrap if not enough room for a wrapped column of text (as could end up with a word per line).
1098
+ const columnWidth = width - indent;
1099
+ if (columnWidth < minColumnWidth) return str;
1100
+
1101
+ const leadingStr = str.substr(0, indent);
1102
+ const columnText = str.substr(indent);
1103
+
1104
+ const indentString = ' '.repeat(indent);
1105
+ const regex = new RegExp('.{1,' + (columnWidth - 1) + '}([\\s\u200B]|$)|[^\\s\u200B]+?([\\s\u200B]|$)', 'g');
1106
+ const lines = columnText.match(regex) || [];
1107
+ return leadingStr + lines.map((line, i) => {
1108
+ if (line.slice(-1) === '\n') {
1109
+ line = line.slice(0, line.length - 1);
1110
+ }
1111
+ return ((i > 0) ? indentString : '') + line.trimRight();
1112
+ }).join('\n');
1113
+ }
1114
+ }
1115
+
1116
+ class Option {
1117
+ /**
1118
+ * Initialize a new `Option` with the given `flags` and `description`.
1119
+ *
1120
+ * @param {string} flags
1121
+ * @param {string} [description]
1122
+ */
1123
+
1124
+ constructor(flags, description) {
1125
+ this.flags = flags;
1126
+ this.description = description || '';
1127
+
1128
+ this.required = flags.includes('<'); // A value must be supplied when the option is specified.
1129
+ this.optional = flags.includes('['); // A value is optional when the option is specified.
1130
+ // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument
1131
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags); // The option can take multiple values.
1132
+ this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.
1133
+ const optionFlags = _parseOptionFlags(flags);
1134
+ this.short = optionFlags.shortFlag;
1135
+ this.long = optionFlags.longFlag;
1136
+ this.negate = false;
1137
+ if (this.long) {
1138
+ this.negate = this.long.startsWith('--no-');
1139
+ }
1140
+ this.defaultValue = undefined;
1141
+ this.defaultValueDescription = undefined;
1142
+ this.parseArg = undefined;
1143
+ this.hidden = false;
1144
+ this.argChoices = undefined;
1145
+ }
1146
+
1147
+ /**
1148
+ * Set the default value, and optionally supply the description to be displayed in the help.
1149
+ *
1150
+ * @param {any} value
1151
+ * @param {string} [description]
1152
+ * @return {Option}
1153
+ */
1154
+
1155
+ default(value, description) {
1156
+ this.defaultValue = value;
1157
+ this.defaultValueDescription = description;
1158
+ return this;
1159
+ };
1160
+
1161
+ /**
1162
+ * Set the custom handler for processing CLI option arguments into option values.
1163
+ *
1164
+ * @param {Function} [fn]
1165
+ * @return {Option}
1166
+ */
1167
+
1168
+ argParser(fn) {
1169
+ this.parseArg = fn;
1170
+ return this;
1171
+ };
1172
+
1173
+ /**
1174
+ * Whether the option is mandatory and must have a value after parsing.
1175
+ *
1176
+ * @param {boolean} [mandatory=true]
1177
+ * @return {Option}
1178
+ */
1179
+
1180
+ makeOptionMandatory(mandatory = true) {
1181
+ this.mandatory = !!mandatory;
1182
+ return this;
1183
+ };
1184
+
1185
+ /**
1186
+ * Hide option in help.
1187
+ *
1188
+ * @param {boolean} [hide=true]
1189
+ * @return {Option}
1190
+ */
1191
+
1192
+ hideHelp(hide = true) {
1193
+ this.hidden = !!hide;
1194
+ return this;
1195
+ };
1196
+
1197
+ /**
1198
+ * @api private
1199
+ */
1200
+
1201
+ _concatValue(value, previous) {
1202
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
1203
+ return [value];
1204
+ }
1205
+
1206
+ return previous.concat(value);
1207
+ }
1208
+
1209
+ /**
1210
+ * Only allow option value to be one of choices.
1211
+ *
1212
+ * @param {string[]} values
1213
+ * @return {Option}
1214
+ */
1215
+
1216
+ choices(values) {
1217
+ this.argChoices = values;
1218
+ this.parseArg = (arg, previous) => {
1219
+ if (!values.includes(arg)) {
1220
+ throw new InvalidOptionArgumentError(`Allowed choices are ${values.join(', ')}.`);
1221
+ }
1222
+ if (this.variadic) {
1223
+ return this._concatValue(arg, previous);
1224
+ }
1225
+ return arg;
1226
+ };
1227
+ return this;
1228
+ };
1229
+
1230
+ /**
1231
+ * Return option name.
1232
+ *
1233
+ * @return {string}
1234
+ */
1235
+
1236
+ name() {
1237
+ if (this.long) {
1238
+ return this.long.replace(/^--/, '');
1239
+ }
1240
+ return this.short.replace(/^-/, '');
1241
+ };
1242
+
1243
+ /**
1244
+ * Return option name, in a camelcase format that can be used
1245
+ * as a object attribute key.
1246
+ *
1247
+ * @return {string}
1248
+ * @api private
1249
+ */
1250
+
1251
+ attributeName() {
1252
+ return camelcase(this.name().replace(/^no-/, ''));
1253
+ };
1254
+
1255
+ /**
1256
+ * Check if `arg` matches the short or long flag.
1257
+ *
1258
+ * @param {string} arg
1259
+ * @return {boolean}
1260
+ * @api private
1261
+ */
1262
+
1263
+ is(arg) {
1264
+ return this.short === arg || this.long === arg;
1265
+ };
1266
+ }
1267
+
1268
+ /**
1269
+ * CommanderError class
1270
+ * @class
1271
+ */
1272
+ class CommanderError extends Error {
1273
+ /**
1274
+ * Constructs the CommanderError class
1275
+ * @param {number} exitCode suggested exit code which could be used with process.exit
1276
+ * @param {string} code an id string representing the error
1277
+ * @param {string} message human-readable description of the error
1278
+ * @constructor
1279
+ */
1280
+ constructor(exitCode, code, message) {
1281
+ super(message);
1282
+ // properly capture stack trace in Node.js
1283
+ Error.captureStackTrace(this, this.constructor);
1284
+ this.name = this.constructor.name;
1285
+ this.code = code;
1286
+ this.exitCode = exitCode;
1287
+ this.nestedError = undefined;
1288
+ }
1289
+ }
1290
+
1291
+ /**
1292
+ * InvalidOptionArgumentError class
1293
+ * @class
1294
+ */
1295
+ class InvalidOptionArgumentError extends CommanderError {
1296
+ /**
1297
+ * Constructs the InvalidOptionArgumentError class
1298
+ * @param {string} [message] explanation of why argument is invalid
1299
+ * @constructor
1300
+ */
1301
+ constructor(message) {
1302
+ super(1, 'commander.invalidOptionArgument', message);
1303
+ // properly capture stack trace in Node.js
1304
+ Error.captureStackTrace(this, this.constructor);
1305
+ this.name = this.constructor.name;
1306
+ }
1307
+ }
1308
+
1309
+ class Command extends EventEmitter {
1310
+ /**
1311
+ * Initialize a new `Command`.
1312
+ *
1313
+ * @param {string} [name]
1314
+ */
1315
+
1316
+ constructor(name) {
1317
+ super();
1318
+ this.commands = [];
1319
+ this.options = [];
1320
+ this.parent = null;
1321
+ this._allowUnknownOption = false;
1322
+ this._allowExcessArguments = true;
1323
+ this._args = [];
1324
+ this.rawArgs = null;
1325
+ this._scriptPath = null;
1326
+ this._name = name || '';
1327
+ this._optionValues = {};
1328
+ this._storeOptionsAsProperties = false;
1329
+ this._actionResults = [];
1330
+ this._actionHandler = null;
1331
+ this._executableHandler = false;
1332
+ this._executableFile = null; // custom name for executable
1333
+ this._defaultCommandName = null;
1334
+ this._exitCallback = null;
1335
+ this._aliases = [];
1336
+ this._combineFlagAndOptionalValue = true;
1337
+ this._description = '';
1338
+ this._argsDescription = undefined;
1339
+ this._enablePositionalOptions = false;
1340
+ this._passThroughOptions = false;
1341
+
1342
+ // see .configureOutput() for docs
1343
+ this._outputConfiguration = {
1344
+ writeOut: (str) => process.stdout.write(str),
1345
+ writeErr: (str) => process.stderr.write(str),
1346
+ getOutHelpWidth: () => process.stdout.isTTY ? process.stdout.columns : undefined,
1347
+ getErrHelpWidth: () => process.stderr.isTTY ? process.stderr.columns : undefined,
1348
+ outputError: (str, write) => write(str)
1349
+ };
1350
+
1351
+ this._hidden = false;
1352
+ this._hasHelpOption = true;
1353
+ this._helpFlags = '-h, --help';
1354
+ this._helpDescription = 'display help for command';
1355
+ this._helpShortFlag = '-h';
1356
+ this._helpLongFlag = '--help';
1357
+ this._addImplicitHelpCommand = undefined; // Deliberately undefined, not decided whether true or false
1358
+ this._helpCommandName = 'help';
1359
+ this._helpCommandnameAndArgs = 'help [command]';
1360
+ this._helpCommandDescription = 'display help for command';
1361
+ this._helpConfiguration = {};
1362
+ }
1363
+
1364
+ /**
1365
+ * Define a command.
1366
+ *
1367
+ * There are two styles of command: pay attention to where to put the description.
1368
+ *
1369
+ * Examples:
1370
+ *
1371
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1372
+ * program
1373
+ * .command('clone <source> [destination]')
1374
+ * .description('clone a repository into a newly created directory')
1375
+ * .action((source, destination) => {
1376
+ * console.log('clone command called');
1377
+ * });
1378
+ *
1379
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1380
+ * program
1381
+ * .command('start <service>', 'start named service')
1382
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1383
+ *
1384
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1385
+ * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1386
+ * @param {Object} [execOpts] - configuration options (for executable)
1387
+ * @return {Command} returns new command for action handler, or `this` for executable command
1388
+ */
1389
+
1390
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1391
+ let desc = actionOptsOrExecDesc;
1392
+ let opts = execOpts;
1393
+ if (typeof desc === 'object' && desc !== null) {
1394
+ opts = desc;
1395
+ desc = null;
1396
+ }
1397
+ opts = opts || {};
1398
+ const args = nameAndArgs.split(/ +/);
1399
+ const cmd = this.createCommand(args.shift());
1400
+
1401
+ if (desc) {
1402
+ cmd.description(desc);
1403
+ cmd._executableHandler = true;
1404
+ }
1405
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1406
+
1407
+ cmd._outputConfiguration = this._outputConfiguration;
1408
+
1409
+ cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden
1410
+ cmd._hasHelpOption = this._hasHelpOption;
1411
+ cmd._helpFlags = this._helpFlags;
1412
+ cmd._helpDescription = this._helpDescription;
1413
+ cmd._helpShortFlag = this._helpShortFlag;
1414
+ cmd._helpLongFlag = this._helpLongFlag;
1415
+ cmd._helpCommandName = this._helpCommandName;
1416
+ cmd._helpCommandnameAndArgs = this._helpCommandnameAndArgs;
1417
+ cmd._helpCommandDescription = this._helpCommandDescription;
1418
+ cmd._helpConfiguration = this._helpConfiguration;
1419
+ cmd._exitCallback = this._exitCallback;
1420
+ cmd._storeOptionsAsProperties = this._storeOptionsAsProperties;
1421
+ cmd._combineFlagAndOptionalValue = this._combineFlagAndOptionalValue;
1422
+ cmd._allowExcessArguments = this._allowExcessArguments;
1423
+ cmd._enablePositionalOptions = this._enablePositionalOptions;
1424
+
1425
+ cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor
1426
+ this.commands.push(cmd);
1427
+ cmd._parseExpectedArgs(args);
1428
+ cmd.parent = this;
1429
+
1430
+ if (desc) return this;
1431
+ return cmd;
1432
+ };
1433
+
1434
+ /**
1435
+ * Factory routine to create a new unattached command.
1436
+ *
1437
+ * See .command() for creating an attached subcommand, which uses this routine to
1438
+ * create the command. You can override createCommand to customise subcommands.
1439
+ *
1440
+ * @param {string} [name]
1441
+ * @return {Command} new command
1442
+ */
1443
+
1444
+ createCommand(name) {
1445
+ return new Command(name);
1446
+ };
1447
+
1448
+ /**
1449
+ * You can customise the help with a subclass of Help by overriding createHelp,
1450
+ * or by overriding Help properties using configureHelp().
1451
+ *
1452
+ * @return {Help}
1453
+ */
1454
+
1455
+ createHelp() {
1456
+ return Object.assign(new Help(), this.configureHelp());
1457
+ };
1458
+
1459
+ /**
1460
+ * You can customise the help by overriding Help properties using configureHelp(),
1461
+ * or with a subclass of Help by overriding createHelp().
1462
+ *
1463
+ * @param {Object} [configuration] - configuration options
1464
+ * @return {Command|Object} `this` command for chaining, or stored configuration
1465
+ */
1466
+
1467
+ configureHelp(configuration) {
1468
+ if (configuration === undefined) return this._helpConfiguration;
1469
+
1470
+ this._helpConfiguration = configuration;
1471
+ return this;
1472
+ }
1473
+
1474
+ /**
1475
+ * The default output goes to stdout and stderr. You can customise this for special
1476
+ * applications. You can also customise the display of errors by overriding outputError.
1477
+ *
1478
+ * The configuration properties are all functions:
1479
+ *
1480
+ * // functions to change where being written, stdout and stderr
1481
+ * writeOut(str)
1482
+ * writeErr(str)
1483
+ * // matching functions to specify width for wrapping help
1484
+ * getOutHelpWidth()
1485
+ * getErrHelpWidth()
1486
+ * // functions based on what is being written out
1487
+ * outputError(str, write) // used for displaying errors, and not used for displaying help
1488
+ *
1489
+ * @param {Object} [configuration] - configuration options
1490
+ * @return {Command|Object} `this` command for chaining, or stored configuration
1491
+ */
1492
+
1493
+ configureOutput(configuration) {
1494
+ if (configuration === undefined) return this._outputConfiguration;
1495
+
1496
+ Object.assign(this._outputConfiguration, configuration);
1497
+ return this;
1498
+ }
1499
+
1500
+ /**
1501
+ * Add a prepared subcommand.
1502
+ *
1503
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1504
+ *
1505
+ * @param {Command} cmd - new subcommand
1506
+ * @param {Object} [opts] - configuration options
1507
+ * @return {Command} `this` command for chaining
1508
+ */
1509
+
1510
+ addCommand(cmd, opts) {
1511
+ if (!cmd._name) throw new Error('Command passed to .addCommand() must have a name');
1512
+
1513
+ // To keep things simple, block automatic name generation for deeply nested executables.
1514
+ // Fail fast and detect when adding rather than later when parsing.
1515
+ function checkExplicitNames(commandArray) {
1516
+ commandArray.forEach((cmd) => {
1517
+ if (cmd._executableHandler && !cmd._executableFile) {
1518
+ throw new Error(`Must specify executableFile for deeply nested executable: ${cmd.name()}`);
1519
+ }
1520
+ checkExplicitNames(cmd.commands);
1521
+ });
1522
+ }
1523
+ checkExplicitNames(cmd.commands);
1524
+
1525
+ opts = opts || {};
1526
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1527
+ if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation
1528
+
1529
+ this.commands.push(cmd);
1530
+ cmd.parent = this;
1531
+ return this;
1532
+ };
1533
+
1534
+ /**
1535
+ * Define argument syntax for the command.
1536
+ */
1537
+
1538
+ arguments(desc) {
1539
+ return this._parseExpectedArgs(desc.split(/ +/));
1540
+ };
1541
+
1542
+ /**
1543
+ * Override default decision whether to add implicit help command.
1544
+ *
1545
+ * addHelpCommand() // force on
1546
+ * addHelpCommand(false); // force off
1547
+ * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details
1548
+ *
1549
+ * @return {Command} `this` command for chaining
1550
+ */
1551
+
1552
+ addHelpCommand(enableOrNameAndArgs, description) {
1553
+ if (enableOrNameAndArgs === false) {
1554
+ this._addImplicitHelpCommand = false;
1555
+ } else {
1556
+ this._addImplicitHelpCommand = true;
1557
+ if (typeof enableOrNameAndArgs === 'string') {
1558
+ this._helpCommandName = enableOrNameAndArgs.split(' ')[0];
1559
+ this._helpCommandnameAndArgs = enableOrNameAndArgs;
1560
+ }
1561
+ this._helpCommandDescription = description || this._helpCommandDescription;
1562
+ }
1563
+ return this;
1564
+ };
1565
+
1566
+ /**
1567
+ * @return {boolean}
1568
+ * @api private
1569
+ */
1570
+
1571
+ _hasImplicitHelpCommand() {
1572
+ if (this._addImplicitHelpCommand === undefined) {
1573
+ return this.commands.length && !this._actionHandler && !this._findCommand('help');
1574
+ }
1575
+ return this._addImplicitHelpCommand;
1576
+ };
1577
+
1578
+ /**
1579
+ * Parse expected `args`.
1580
+ *
1581
+ * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`.
1582
+ *
1583
+ * @param {Array} args
1584
+ * @return {Command} `this` command for chaining
1585
+ * @api private
1586
+ */
1587
+
1588
+ _parseExpectedArgs(args) {
1589
+ if (!args.length) return;
1590
+ args.forEach((arg) => {
1591
+ const argDetails = {
1592
+ required: false,
1593
+ name: '',
1594
+ variadic: false
1595
+ };
1596
+
1597
+ switch (arg[0]) {
1598
+ case '<':
1599
+ argDetails.required = true;
1600
+ argDetails.name = arg.slice(1, -1);
1601
+ break;
1602
+ case '[':
1603
+ argDetails.name = arg.slice(1, -1);
1604
+ break;
1605
+ }
1606
+
1607
+ if (argDetails.name.length > 3 && argDetails.name.slice(-3) === '...') {
1608
+ argDetails.variadic = true;
1609
+ argDetails.name = argDetails.name.slice(0, -3);
1610
+ }
1611
+ if (argDetails.name) {
1612
+ this._args.push(argDetails);
1613
+ }
1614
+ });
1615
+ this._args.forEach((arg, i) => {
1616
+ if (arg.variadic && i < this._args.length - 1) {
1617
+ throw new Error(`only the last argument can be variadic '${arg.name}'`);
1618
+ }
1619
+ });
1620
+ return this;
1621
+ };
1622
+
1623
+ /**
1624
+ * Register callback to use as replacement for calling process.exit.
1625
+ *
1626
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1627
+ * @return {Command} `this` command for chaining
1628
+ */
1629
+
1630
+ exitOverride(fn) {
1631
+ if (fn) {
1632
+ this._exitCallback = fn;
1633
+ } else {
1634
+ this._exitCallback = (err) => {
1635
+ if (err.code !== 'commander.executeSubCommandAsync') {
1636
+ throw err;
1637
+ }
1638
+ };
1639
+ }
1640
+ return this;
1641
+ };
1642
+
1643
+ /**
1644
+ * Call process.exit, and _exitCallback if defined.
1645
+ *
1646
+ * @param {number} exitCode exit code for using with process.exit
1647
+ * @param {string} code an id string representing the error
1648
+ * @param {string} message human-readable description of the error
1649
+ * @return never
1650
+ * @api private
1651
+ */
1652
+
1653
+ _exit(exitCode, code, message) {
1654
+ if (this._exitCallback) {
1655
+ this._exitCallback(new CommanderError(exitCode, code, message));
1656
+ // Expecting this line is not reached.
1657
+ }
1658
+ process.exit(exitCode);
1659
+ };
1660
+
1661
+ /**
1662
+ * Register callback `fn` for the command.
1663
+ *
1664
+ * Examples:
1665
+ *
1666
+ * program
1667
+ * .command('help')
1668
+ * .description('display verbose help')
1669
+ * .action(function() {
1670
+ * // output help here
1671
+ * });
1672
+ *
1673
+ * @param {Function} fn
1674
+ * @return {Command} `this` command for chaining
1675
+ */
1676
+
1677
+ action(fn) {
1678
+ const listener = (args) => {
1679
+ // The .action callback takes an extra parameter which is the command or options.
1680
+ const expectedArgsCount = this._args.length;
1681
+ const actionArgs = args.slice(0, expectedArgsCount);
1682
+ if (this._storeOptionsAsProperties) {
1683
+ actionArgs[expectedArgsCount] = this; // backwards compatible "options"
1684
+ } else {
1685
+ actionArgs[expectedArgsCount] = this.opts();
1686
+ }
1687
+ actionArgs.push(this);
1688
+
1689
+ const actionResult = fn.apply(this, actionArgs);
1690
+ // Remember result in case it is async. Assume parseAsync getting called on root.
1691
+ let rootCommand = this;
1692
+ while (rootCommand.parent) {
1693
+ rootCommand = rootCommand.parent;
1694
+ }
1695
+ rootCommand._actionResults.push(actionResult);
1696
+ };
1697
+ this._actionHandler = listener;
1698
+ return this;
1699
+ };
1700
+
1701
+ /**
1702
+ * Factory routine to create a new unattached option.
1703
+ *
1704
+ * See .option() for creating an attached option, which uses this routine to
1705
+ * create the option. You can override createOption to return a custom option.
1706
+ *
1707
+ * @param {string} flags
1708
+ * @param {string} [description]
1709
+ * @return {Option} new option
1710
+ */
1711
+
1712
+ createOption(flags, description) {
1713
+ return new Option(flags, description);
1714
+ };
1715
+
1716
+ /**
1717
+ * Add an option.
1718
+ *
1719
+ * @param {Option} option
1720
+ * @return {Command} `this` command for chaining
1721
+ */
1722
+ addOption(option) {
1723
+ const oname = option.name();
1724
+ const name = option.attributeName();
1725
+
1726
+ let defaultValue = option.defaultValue;
1727
+
1728
+ // preassign default value for --no-*, [optional], <required>, or plain flag if boolean value
1729
+ if (option.negate || option.optional || option.required || typeof defaultValue === 'boolean') {
1730
+ // when --no-foo we make sure default is true, unless a --foo option is already defined
1731
+ if (option.negate) {
1732
+ const positiveLongFlag = option.long.replace(/^--no-/, '--');
1733
+ defaultValue = this._findOption(positiveLongFlag) ? this._getOptionValue(name) : true;
1734
+ }
1735
+ // preassign only if we have a default
1736
+ if (defaultValue !== undefined) {
1737
+ this._setOptionValue(name, defaultValue);
1738
+ }
1739
+ }
1740
+
1741
+ // register the option
1742
+ this.options.push(option);
1743
+
1744
+ // when it's passed assign the value
1745
+ // and conditionally invoke the callback
1746
+ this.on('option:' + oname, (val) => {
1747
+ const oldValue = this._getOptionValue(name);
1748
+
1749
+ // custom processing
1750
+ if (val !== null && option.parseArg) {
1751
+ try {
1752
+ val = option.parseArg(val, oldValue === undefined ? defaultValue : oldValue);
1753
+ } catch (err) {
1754
+ if (err.code === 'commander.invalidOptionArgument') {
1755
+ const message = `error: option '${option.flags}' argument '${val}' is invalid. ${err.message}`;
1756
+ this._displayError(err.exitCode, err.code, message);
1757
+ }
1758
+ throw err;
1759
+ }
1760
+ } else if (val !== null && option.variadic) {
1761
+ val = option._concatValue(val, oldValue);
1762
+ }
1763
+
1764
+ // unassigned or boolean value
1765
+ if (typeof oldValue === 'boolean' || typeof oldValue === 'undefined') {
1766
+ // if no value, negate false, and we have a default, then use it!
1767
+ if (val == null) {
1768
+ this._setOptionValue(name, option.negate
1769
+ ? false
1770
+ : defaultValue || true);
1771
+ } else {
1772
+ this._setOptionValue(name, val);
1773
+ }
1774
+ } else if (val !== null) {
1775
+ // reassign
1776
+ this._setOptionValue(name, option.negate ? false : val);
1777
+ }
1778
+ });
1779
+
1780
+ return this;
1781
+ }
1782
+
1783
+ /**
1784
+ * Internal implementation shared by .option() and .requiredOption()
1785
+ *
1786
+ * @api private
1787
+ */
1788
+ _optionEx(config, flags, description, fn, defaultValue) {
1789
+ const option = this.createOption(flags, description);
1790
+ option.makeOptionMandatory(!!config.mandatory);
1791
+ if (typeof fn === 'function') {
1792
+ option.default(defaultValue).argParser(fn);
1793
+ } else if (fn instanceof RegExp) {
1794
+ // deprecated
1795
+ const regex = fn;
1796
+ fn = (val, def) => {
1797
+ const m = regex.exec(val);
1798
+ return m ? m[0] : def;
1799
+ };
1800
+ option.default(defaultValue).argParser(fn);
1801
+ } else {
1802
+ option.default(fn);
1803
+ }
1804
+
1805
+ return this.addOption(option);
1806
+ }
1807
+
1808
+ /**
1809
+ * Define option with `flags`, `description` and optional
1810
+ * coercion `fn`.
1811
+ *
1812
+ * The `flags` string contains the short and/or long flags,
1813
+ * separated by comma, a pipe or space. The following are all valid
1814
+ * all will output this way when `--help` is used.
1815
+ *
1816
+ * "-p, --pepper"
1817
+ * "-p|--pepper"
1818
+ * "-p --pepper"
1819
+ *
1820
+ * Examples:
1821
+ *
1822
+ * // simple boolean defaulting to undefined
1823
+ * program.option('-p, --pepper', 'add pepper');
1824
+ *
1825
+ * program.pepper
1826
+ * // => undefined
1827
+ *
1828
+ * --pepper
1829
+ * program.pepper
1830
+ * // => true
1831
+ *
1832
+ * // simple boolean defaulting to true (unless non-negated option is also defined)
1833
+ * program.option('-C, --no-cheese', 'remove cheese');
1834
+ *
1835
+ * program.cheese
1836
+ * // => true
1837
+ *
1838
+ * --no-cheese
1839
+ * program.cheese
1840
+ * // => false
1841
+ *
1842
+ * // required argument
1843
+ * program.option('-C, --chdir <path>', 'change the working directory');
1844
+ *
1845
+ * --chdir /tmp
1846
+ * program.chdir
1847
+ * // => "/tmp"
1848
+ *
1849
+ * // optional argument
1850
+ * program.option('-c, --cheese [type]', 'add cheese [marble]');
1851
+ *
1852
+ * @param {string} flags
1853
+ * @param {string} [description]
1854
+ * @param {Function|*} [fn] - custom option processing function or default value
1855
+ * @param {*} [defaultValue]
1856
+ * @return {Command} `this` command for chaining
1857
+ */
1858
+
1859
+ option(flags, description, fn, defaultValue) {
1860
+ return this._optionEx({}, flags, description, fn, defaultValue);
1861
+ };
1862
+
1863
+ /**
1864
+ * Add a required option which must have a value after parsing. This usually means
1865
+ * the option must be specified on the command line. (Otherwise the same as .option().)
1866
+ *
1867
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1868
+ *
1869
+ * @param {string} flags
1870
+ * @param {string} [description]
1871
+ * @param {Function|*} [fn] - custom option processing function or default value
1872
+ * @param {*} [defaultValue]
1873
+ * @return {Command} `this` command for chaining
1874
+ */
1875
+
1876
+ requiredOption(flags, description, fn, defaultValue) {
1877
+ return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue);
1878
+ };
1879
+
1880
+ /**
1881
+ * Alter parsing of short flags with optional values.
1882
+ *
1883
+ * Examples:
1884
+ *
1885
+ * // for `.option('-f,--flag [value]'):
1886
+ * .combineFlagAndOptionalValue(true) // `-f80` is treated like `--flag=80`, this is the default behaviour
1887
+ * .combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1888
+ *
1889
+ * @param {Boolean} [combine=true] - if `true` or omitted, an optional value can be specified directly after the flag.
1890
+ */
1891
+ combineFlagAndOptionalValue(combine = true) {
1892
+ this._combineFlagAndOptionalValue = !!combine;
1893
+ return this;
1894
+ };
1895
+
1896
+ /**
1897
+ * Allow unknown options on the command line.
1898
+ *
1899
+ * @param {Boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown
1900
+ * for unknown options.
1901
+ */
1902
+ allowUnknownOption(allowUnknown = true) {
1903
+ this._allowUnknownOption = !!allowUnknown;
1904
+ return this;
1905
+ };
1906
+
1907
+ /**
1908
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1909
+ *
1910
+ * @param {Boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown
1911
+ * for excess arguments.
1912
+ */
1913
+ allowExcessArguments(allowExcess = true) {
1914
+ this._allowExcessArguments = !!allowExcess;
1915
+ return this;
1916
+ };
1917
+
1918
+ /**
1919
+ * Enable positional options. Positional means global options are specified before subcommands which lets
1920
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1921
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
1922
+ *
1923
+ * @param {Boolean} [positional=true]
1924
+ */
1925
+ enablePositionalOptions(positional = true) {
1926
+ this._enablePositionalOptions = !!positional;
1927
+ return this;
1928
+ };
1929
+
1930
+ /**
1931
+ * Pass through options that come after command-arguments rather than treat them as command-options,
1932
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1933
+ * positional options to have been enabled on the program (parent commands).
1934
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
1935
+ *
1936
+ * @param {Boolean} [passThrough=true]
1937
+ * for unknown options.
1938
+ */
1939
+ passThroughOptions(passThrough = true) {
1940
+ this._passThroughOptions = !!passThrough;
1941
+ if (!!this.parent && passThrough && !this.parent._enablePositionalOptions) {
1942
+ throw new Error('passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)');
1943
+ }
1944
+ return this;
1945
+ };
1946
+
1947
+ /**
1948
+ * Whether to store option values as properties on command object,
1949
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
1950
+ *
1951
+ * @param {boolean} [storeAsProperties=true]
1952
+ * @return {Command} `this` command for chaining
1953
+ */
1954
+
1955
+ storeOptionsAsProperties(storeAsProperties = true) {
1956
+ this._storeOptionsAsProperties = !!storeAsProperties;
1957
+ if (this.options.length) {
1958
+ throw new Error('call .storeOptionsAsProperties() before adding options');
1959
+ }
1960
+ return this;
1961
+ };
1962
+
1963
+ /**
1964
+ * Store option value
1965
+ *
1966
+ * @param {string} key
1967
+ * @param {Object} value
1968
+ * @api private
1969
+ */
1970
+
1971
+ _setOptionValue(key, value) {
1972
+ if (this._storeOptionsAsProperties) {
1973
+ this[key] = value;
1974
+ } else {
1975
+ this._optionValues[key] = value;
1976
+ }
1977
+ };
1978
+
1979
+ /**
1980
+ * Retrieve option value
1981
+ *
1982
+ * @param {string} key
1983
+ * @return {Object} value
1984
+ * @api private
1985
+ */
1986
+
1987
+ _getOptionValue(key) {
1988
+ if (this._storeOptionsAsProperties) {
1989
+ return this[key];
1990
+ }
1991
+ return this._optionValues[key];
1992
+ };
1993
+
1994
+ /**
1995
+ * Parse `argv`, setting options and invoking commands when defined.
1996
+ *
1997
+ * The default expectation is that the arguments are from node and have the application as argv[0]
1998
+ * and the script being run in argv[1], with user parameters after that.
1999
+ *
2000
+ * Examples:
2001
+ *
2002
+ * program.parse(process.argv);
2003
+ * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions
2004
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2005
+ *
2006
+ * @param {string[]} [argv] - optional, defaults to process.argv
2007
+ * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron
2008
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
2009
+ * @return {Command} `this` command for chaining
2010
+ */
2011
+
2012
+ parse(argv, parseOptions) {
2013
+ if (argv !== undefined && !Array.isArray(argv)) {
2014
+ throw new Error('first parameter to parse must be array or undefined');
2015
+ }
2016
+ parseOptions = parseOptions || {};
2017
+
2018
+ // Default to using process.argv
2019
+ if (argv === undefined) {
2020
+ argv = process.argv;
2021
+ // @ts-ignore: unknown property
2022
+ if (process.versions && process.versions.electron) {
2023
+ parseOptions.from = 'electron';
2024
+ }
2025
+ }
2026
+ this.rawArgs = argv.slice();
2027
+
2028
+ // make it a little easier for callers by supporting various argv conventions
2029
+ let userArgs;
2030
+ switch (parseOptions.from) {
2031
+ case undefined:
2032
+ case 'node':
2033
+ this._scriptPath = argv[1];
2034
+ userArgs = argv.slice(2);
2035
+ break;
2036
+ case 'electron':
2037
+ // @ts-ignore: unknown property
2038
+ if (process.defaultApp) {
2039
+ this._scriptPath = argv[1];
2040
+ userArgs = argv.slice(2);
2041
+ } else {
2042
+ userArgs = argv.slice(1);
2043
+ }
2044
+ break;
2045
+ case 'user':
2046
+ userArgs = argv.slice(0);
2047
+ break;
2048
+ default:
2049
+ throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
2050
+ }
2051
+ if (!this._scriptPath && require.main) {
2052
+ this._scriptPath = require.main.filename;
2053
+ }
2054
+
2055
+ // Guess name, used in usage in help.
2056
+ this._name = this._name || (this._scriptPath && path.basename(this._scriptPath, path.extname(this._scriptPath)));
2057
+
2058
+ // Let's go!
2059
+ this._parseCommand([], userArgs);
2060
+
2061
+ return this;
2062
+ };
2063
+
2064
+ /**
2065
+ * Parse `argv`, setting options and invoking commands when defined.
2066
+ *
2067
+ * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.
2068
+ *
2069
+ * The default expectation is that the arguments are from node and have the application as argv[0]
2070
+ * and the script being run in argv[1], with user parameters after that.
2071
+ *
2072
+ * Examples:
2073
+ *
2074
+ * program.parseAsync(process.argv);
2075
+ * program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions
2076
+ * program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2077
+ *
2078
+ * @param {string[]} [argv]
2079
+ * @param {Object} [parseOptions]
2080
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
2081
+ * @return {Promise}
2082
+ */
2083
+
2084
+ parseAsync(argv, parseOptions) {
2085
+ this.parse(argv, parseOptions);
2086
+ return Promise.all(this._actionResults).then(() => this);
2087
+ };
2088
+
2089
+ /**
2090
+ * Execute a sub-command executable.
2091
+ *
2092
+ * @api private
2093
+ */
2094
+
2095
+ _executeSubCommand(subcommand, args) {
2096
+ args = args.slice();
2097
+ let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.
2098
+ const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];
2099
+
2100
+ // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.
2101
+ this._checkForMissingMandatoryOptions();
2102
+
2103
+ // Want the entry script as the reference for command name and directory for searching for other files.
2104
+ let scriptPath = this._scriptPath;
2105
+ // Fallback in case not set, due to how Command created or called.
2106
+ if (!scriptPath && require.main) {
2107
+ scriptPath = require.main.filename;
2108
+ }
2109
+
2110
+ let baseDir;
2111
+ try {
2112
+ const resolvedLink = fs.realpathSync(scriptPath);
2113
+ baseDir = path.dirname(resolvedLink);
2114
+ } catch (e) {
2115
+ baseDir = '.'; // dummy, probably not going to find executable!
2116
+ }
2117
+
2118
+ // name of the subcommand, like `pm-install`
2119
+ let bin = path.basename(scriptPath, path.extname(scriptPath)) + '-' + subcommand._name;
2120
+ if (subcommand._executableFile) {
2121
+ bin = subcommand._executableFile;
2122
+ }
2123
+
2124
+ const localBin = path.join(baseDir, bin);
2125
+ if (fs.existsSync(localBin)) {
2126
+ // prefer local `./<bin>` to bin in the $PATH
2127
+ bin = localBin;
2128
+ } else {
2129
+ // Look for source files.
2130
+ sourceExt.forEach((ext) => {
2131
+ if (fs.existsSync(`${localBin}${ext}`)) {
2132
+ bin = `${localBin}${ext}`;
2133
+ }
2134
+ });
2135
+ }
2136
+ launchWithNode = sourceExt.includes(path.extname(bin));
2137
+
2138
+ let proc;
2139
+ if (process.platform !== 'win32') {
2140
+ if (launchWithNode) {
2141
+ args.unshift(bin);
2142
+ // add executable arguments to spawn
2143
+ args = incrementNodeInspectorPort(process.execArgv).concat(args);
2144
+
2145
+ proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });
2146
+ } else {
2147
+ proc = childProcess.spawn(bin, args, { stdio: 'inherit' });
2148
+ }
2149
+ } else {
2150
+ args.unshift(bin);
2151
+ // add executable arguments to spawn
2152
+ args = incrementNodeInspectorPort(process.execArgv).concat(args);
2153
+ proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });
2154
+ }
2155
+
2156
+ const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];
2157
+ signals.forEach((signal) => {
2158
+ // @ts-ignore
2159
+ process.on(signal, () => {
2160
+ if (proc.killed === false && proc.exitCode === null) {
2161
+ proc.kill(signal);
2162
+ }
2163
+ });
2164
+ });
2165
+
2166
+ // By default terminate process when spawned process terminates.
2167
+ // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running!
2168
+ const exitCallback = this._exitCallback;
2169
+ if (!exitCallback) {
2170
+ proc.on('close', process.exit.bind(process));
2171
+ } else {
2172
+ proc.on('close', () => {
2173
+ exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)'));
2174
+ });
2175
+ }
2176
+ proc.on('error', (err) => {
2177
+ // @ts-ignore
2178
+ if (err.code === 'ENOENT') {
2179
+ const executableMissing = `'${bin}' does not exist
2180
+ - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
2181
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name`;
2182
+ throw new Error(executableMissing);
2183
+ // @ts-ignore
2184
+ } else if (err.code === 'EACCES') {
2185
+ throw new Error(`'${bin}' not executable`);
2186
+ }
2187
+ if (!exitCallback) {
2188
+ process.exit(1);
2189
+ } else {
2190
+ const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)');
2191
+ wrappedError.nestedError = err;
2192
+ exitCallback(wrappedError);
2193
+ }
2194
+ });
2195
+
2196
+ // Store the reference to the child process
2197
+ this.runningCommand = proc;
2198
+ };
2199
+
2200
+ /**
2201
+ * @api private
2202
+ */
2203
+ _dispatchSubcommand(commandName, operands, unknown) {
2204
+ const subCommand = this._findCommand(commandName);
2205
+ if (!subCommand) this.help({ error: true });
2206
+
2207
+ if (subCommand._executableHandler) {
2208
+ this._executeSubCommand(subCommand, operands.concat(unknown));
2209
+ } else {
2210
+ subCommand._parseCommand(operands, unknown);
2211
+ }
2212
+ };
2213
+
2214
+ /**
2215
+ * Process arguments in context of this command.
2216
+ *
2217
+ * @api private
2218
+ */
2219
+
2220
+ _parseCommand(operands, unknown) {
2221
+ const parsed = this.parseOptions(unknown);
2222
+ operands = operands.concat(parsed.operands);
2223
+ unknown = parsed.unknown;
2224
+ this.args = operands.concat(unknown);
2225
+
2226
+ if (operands && this._findCommand(operands[0])) {
2227
+ this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2228
+ } else if (this._hasImplicitHelpCommand() && operands[0] === this._helpCommandName) {
2229
+ if (operands.length === 1) {
2230
+ this.help();
2231
+ } else {
2232
+ this._dispatchSubcommand(operands[1], [], [this._helpLongFlag]);
2233
+ }
2234
+ } else if (this._defaultCommandName) {
2235
+ outputHelpIfRequested(this, unknown); // Run the help for default command from parent rather than passing to default command
2236
+ this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
2237
+ } else {
2238
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
2239
+ // probably missing subcommand and no handler, user needs help
2240
+ this.help({ error: true });
2241
+ }
2242
+
2243
+ outputHelpIfRequested(this, parsed.unknown);
2244
+ this._checkForMissingMandatoryOptions();
2245
+
2246
+ // We do not always call this check to avoid masking a "better" error, like unknown command.
2247
+ const checkForUnknownOptions = () => {
2248
+ if (parsed.unknown.length > 0) {
2249
+ this.unknownOption(parsed.unknown[0]);
2250
+ }
2251
+ };
2252
+
2253
+ const commandEvent = `command:${this.name()}`;
2254
+ if (this._actionHandler) {
2255
+ checkForUnknownOptions();
2256
+ // Check expected arguments and collect variadic together.
2257
+ const args = this.args.slice();
2258
+ this._args.forEach((arg, i) => {
2259
+ if (arg.required && args[i] == null) {
2260
+ this.missingArgument(arg.name);
2261
+ } else if (arg.variadic) {
2262
+ args[i] = args.splice(i);
2263
+ args.length = Math.min(i + 1, args.length);
2264
+ }
2265
+ });
2266
+ if (args.length > this._args.length) {
2267
+ this._excessArguments(args);
2268
+ }
2269
+
2270
+ this._actionHandler(args);
2271
+ if (this.parent) this.parent.emit(commandEvent, operands, unknown); // legacy
2272
+ } else if (this.parent && this.parent.listenerCount(commandEvent)) {
2273
+ checkForUnknownOptions();
2274
+ this.parent.emit(commandEvent, operands, unknown); // legacy
2275
+ } else if (operands.length) {
2276
+ if (this._findCommand('*')) { // legacy default command
2277
+ this._dispatchSubcommand('*', operands, unknown);
2278
+ } else if (this.listenerCount('command:*')) {
2279
+ // skip option check, emit event for possible misspelling suggestion
2280
+ this.emit('command:*', operands, unknown);
2281
+ } else if (this.commands.length) {
2282
+ this.unknownCommand();
2283
+ } else {
2284
+ checkForUnknownOptions();
2285
+ }
2286
+ } else if (this.commands.length) {
2287
+ // This command has subcommands and nothing hooked up at this level, so display help.
2288
+ this.help({ error: true });
2289
+ } else {
2290
+ checkForUnknownOptions();
2291
+ // fall through for caller to handle after calling .parse()
2292
+ }
2293
+ }
2294
+ };
2295
+
2296
+ /**
2297
+ * Find matching command.
2298
+ *
2299
+ * @api private
2300
+ */
2301
+ _findCommand(name) {
2302
+ if (!name) return undefined;
2303
+ return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name));
2304
+ };
2305
+
2306
+ /**
2307
+ * Return an option matching `arg` if any.
2308
+ *
2309
+ * @param {string} arg
2310
+ * @return {Option}
2311
+ * @api private
2312
+ */
2313
+
2314
+ _findOption(arg) {
2315
+ return this.options.find(option => option.is(arg));
2316
+ };
2317
+
2318
+ /**
2319
+ * Display an error message if a mandatory option does not have a value.
2320
+ * Lazy calling after checking for help flags from leaf subcommand.
2321
+ *
2322
+ * @api private
2323
+ */
2324
+
2325
+ _checkForMissingMandatoryOptions() {
2326
+ // Walk up hierarchy so can call in subcommand after checking for displaying help.
2327
+ for (let cmd = this; cmd; cmd = cmd.parent) {
2328
+ cmd.options.forEach((anOption) => {
2329
+ if (anOption.mandatory && (cmd._getOptionValue(anOption.attributeName()) === undefined)) {
2330
+ cmd.missingMandatoryOptionValue(anOption);
2331
+ }
2332
+ });
2333
+ }
2334
+ };
2335
+
2336
+ /**
2337
+ * Parse options from `argv` removing known options,
2338
+ * and return argv split into operands and unknown arguments.
2339
+ *
2340
+ * Examples:
2341
+ *
2342
+ * argv => operands, unknown
2343
+ * --known kkk op => [op], []
2344
+ * op --known kkk => [op], []
2345
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2346
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2347
+ *
2348
+ * @param {String[]} argv
2349
+ * @return {{operands: String[], unknown: String[]}}
2350
+ */
2351
+
2352
+ parseOptions(argv) {
2353
+ const operands = []; // operands, not options or values
2354
+ const unknown = []; // first unknown option and remaining unknown args
2355
+ let dest = operands;
2356
+ const args = argv.slice();
2357
+
2358
+ function maybeOption(arg) {
2359
+ return arg.length > 1 && arg[0] === '-';
2360
+ }
2361
+
2362
+ // parse options
2363
+ let activeVariadicOption = null;
2364
+ while (args.length) {
2365
+ const arg = args.shift();
2366
+
2367
+ // literal
2368
+ if (arg === '--') {
2369
+ if (dest === unknown) dest.push(arg);
2370
+ dest.push(...args);
2371
+ break;
2372
+ }
2373
+
2374
+ if (activeVariadicOption && !maybeOption(arg)) {
2375
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2376
+ continue;
2377
+ }
2378
+ activeVariadicOption = null;
2379
+
2380
+ if (maybeOption(arg)) {
2381
+ const option = this._findOption(arg);
2382
+ // recognised option, call listener to assign value with possible custom processing
2383
+ if (option) {
2384
+ if (option.required) {
2385
+ const value = args.shift();
2386
+ if (value === undefined) this.optionMissingArgument(option);
2387
+ this.emit(`option:${option.name()}`, value);
2388
+ } else if (option.optional) {
2389
+ let value = null;
2390
+ // historical behaviour is optional value is following arg unless an option
2391
+ if (args.length > 0 && !maybeOption(args[0])) {
2392
+ value = args.shift();
2393
+ }
2394
+ this.emit(`option:${option.name()}`, value);
2395
+ } else { // boolean flag
2396
+ this.emit(`option:${option.name()}`);
2397
+ }
2398
+ activeVariadicOption = option.variadic ? option : null;
2399
+ continue;
2400
+ }
2401
+ }
2402
+
2403
+ // Look for combo options following single dash, eat first one if known.
2404
+ if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {
2405
+ const option = this._findOption(`-${arg[1]}`);
2406
+ if (option) {
2407
+ if (option.required || (option.optional && this._combineFlagAndOptionalValue)) {
2408
+ // option with value following in same argument
2409
+ this.emit(`option:${option.name()}`, arg.slice(2));
2410
+ } else {
2411
+ // boolean option, emit and put back remainder of arg for further processing
2412
+ this.emit(`option:${option.name()}`);
2413
+ args.unshift(`-${arg.slice(2)}`);
2414
+ }
2415
+ continue;
2416
+ }
2417
+ }
2418
+
2419
+ // Look for known long flag with value, like --foo=bar
2420
+ if (/^--[^=]+=/.test(arg)) {
2421
+ const index = arg.indexOf('=');
2422
+ const option = this._findOption(arg.slice(0, index));
2423
+ if (option && (option.required || option.optional)) {
2424
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
2425
+ continue;
2426
+ }
2427
+ }
2428
+
2429
+ // Not a recognised option by this command.
2430
+ // Might be a command-argument, or subcommand option, or unknown option, or help command or option.
2431
+
2432
+ // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.
2433
+ if (maybeOption(arg)) {
2434
+ dest = unknown;
2435
+ }
2436
+
2437
+ // If using positionalOptions, stop processing our options at subcommand.
2438
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2439
+ if (this._findCommand(arg)) {
2440
+ operands.push(arg);
2441
+ if (args.length > 0) unknown.push(...args);
2442
+ break;
2443
+ } else if (arg === this._helpCommandName && this._hasImplicitHelpCommand()) {
2444
+ operands.push(arg);
2445
+ if (args.length > 0) operands.push(...args);
2446
+ break;
2447
+ } else if (this._defaultCommandName) {
2448
+ unknown.push(arg);
2449
+ if (args.length > 0) unknown.push(...args);
2450
+ break;
2451
+ }
2452
+ }
2453
+
2454
+ // If using passThroughOptions, stop processing options at first command-argument.
2455
+ if (this._passThroughOptions) {
2456
+ dest.push(arg);
2457
+ if (args.length > 0) dest.push(...args);
2458
+ break;
2459
+ }
2460
+
2461
+ // add arg
2462
+ dest.push(arg);
2463
+ }
2464
+
2465
+ return { operands, unknown };
2466
+ };
2467
+
2468
+ /**
2469
+ * Return an object containing options as key-value pairs
2470
+ *
2471
+ * @return {Object}
2472
+ */
2473
+ opts() {
2474
+ if (this._storeOptionsAsProperties) {
2475
+ // Preserve original behaviour so backwards compatible when still using properties
2476
+ const result = {};
2477
+ const len = this.options.length;
2478
+
2479
+ for (let i = 0; i < len; i++) {
2480
+ const key = this.options[i].attributeName();
2481
+ result[key] = key === this._versionOptionName ? this._version : this[key];
2482
+ }
2483
+ return result;
2484
+ }
2485
+
2486
+ return this._optionValues;
2487
+ };
2488
+
2489
+ /**
2490
+ * Internal bottleneck for handling of parsing errors.
2491
+ *
2492
+ * @api private
2493
+ */
2494
+ _displayError(exitCode, code, message) {
2495
+ this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);
2496
+ this._exit(exitCode, code, message);
2497
+ }
2498
+
2499
+ /**
2500
+ * Argument `name` is missing.
2501
+ *
2502
+ * @param {string} name
2503
+ * @api private
2504
+ */
2505
+
2506
+ missingArgument(name) {
2507
+ const message = `error: missing required argument '${name}'`;
2508
+ this._displayError(1, 'commander.missingArgument', message);
2509
+ };
2510
+
2511
+ /**
2512
+ * `Option` is missing an argument.
2513
+ *
2514
+ * @param {Option} option
2515
+ * @api private
2516
+ */
2517
+
2518
+ optionMissingArgument(option) {
2519
+ const message = `error: option '${option.flags}' argument missing`;
2520
+ this._displayError(1, 'commander.optionMissingArgument', message);
2521
+ };
2522
+
2523
+ /**
2524
+ * `Option` does not have a value, and is a mandatory option.
2525
+ *
2526
+ * @param {Option} option
2527
+ * @api private
2528
+ */
2529
+
2530
+ missingMandatoryOptionValue(option) {
2531
+ const message = `error: required option '${option.flags}' not specified`;
2532
+ this._displayError(1, 'commander.missingMandatoryOptionValue', message);
2533
+ };
2534
+
2535
+ /**
2536
+ * Unknown option `flag`.
2537
+ *
2538
+ * @param {string} flag
2539
+ * @api private
2540
+ */
2541
+
2542
+ unknownOption(flag) {
2543
+ if (this._allowUnknownOption) return;
2544
+ const message = `error: unknown option '${flag}'`;
2545
+ this._displayError(1, 'commander.unknownOption', message);
2546
+ };
2547
+
2548
+ /**
2549
+ * Excess arguments, more than expected.
2550
+ *
2551
+ * @param {string[]} receivedArgs
2552
+ * @api private
2553
+ */
2554
+
2555
+ _excessArguments(receivedArgs) {
2556
+ if (this._allowExcessArguments) return;
2557
+
2558
+ const expected = this._args.length;
2559
+ const s = (expected === 1) ? '' : 's';
2560
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : '';
2561
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2562
+ this._displayError(1, 'commander.excessArguments', message);
2563
+ };
2564
+
2565
+ /**
2566
+ * Unknown command.
2567
+ *
2568
+ * @api private
2569
+ */
2570
+
2571
+ unknownCommand() {
2572
+ const partCommands = [this.name()];
2573
+ for (let parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) {
2574
+ partCommands.unshift(parentCmd.name());
2575
+ }
2576
+ const fullCommand = partCommands.join(' ');
2577
+ const message = `error: unknown command '${this.args[0]}'.` +
2578
+ (this._hasHelpOption ? ` See '${fullCommand} ${this._helpLongFlag}'.` : '');
2579
+ this._displayError(1, 'commander.unknownCommand', message);
2580
+ };
2581
+
2582
+ /**
2583
+ * Set the program version to `str`.
2584
+ *
2585
+ * This method auto-registers the "-V, --version" flag
2586
+ * which will print the version number when passed.
2587
+ *
2588
+ * You can optionally supply the flags and description to override the defaults.
2589
+ *
2590
+ * @param {string} str
2591
+ * @param {string} [flags]
2592
+ * @param {string} [description]
2593
+ * @return {this | string} `this` command for chaining, or version string if no arguments
2594
+ */
2595
+
2596
+ version(str, flags, description) {
2597
+ if (str === undefined) return this._version;
2598
+ this._version = str;
2599
+ flags = flags || '-V, --version';
2600
+ description = description || 'output the version number';
2601
+ const versionOption = this.createOption(flags, description);
2602
+ this._versionOptionName = versionOption.attributeName();
2603
+ this.options.push(versionOption);
2604
+ this.on('option:' + versionOption.name(), () => {
2605
+ this._outputConfiguration.writeOut(`${str}\n`);
2606
+ this._exit(0, 'commander.version', str);
2607
+ });
2608
+ return this;
2609
+ };
2610
+
2611
+ /**
2612
+ * Set the description to `str`.
2613
+ *
2614
+ * @param {string} [str]
2615
+ * @param {Object} [argsDescription]
2616
+ * @return {string|Command}
2617
+ */
2618
+ description(str, argsDescription) {
2619
+ if (str === undefined && argsDescription === undefined) return this._description;
2620
+ this._description = str;
2621
+ this._argsDescription = argsDescription;
2622
+ return this;
2623
+ };
2624
+
2625
+ /**
2626
+ * Set an alias for the command.
2627
+ *
2628
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2629
+ *
2630
+ * @param {string} [alias]
2631
+ * @return {string|Command}
2632
+ */
2633
+
2634
+ alias(alias) {
2635
+ if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility
2636
+
2637
+ let command = this;
2638
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
2639
+ // assume adding alias for last added executable subcommand, rather than this
2640
+ command = this.commands[this.commands.length - 1];
2641
+ }
2642
+
2643
+ if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');
2644
+
2645
+ command._aliases.push(alias);
2646
+ return this;
2647
+ };
2648
+
2649
+ /**
2650
+ * Set aliases for the command.
2651
+ *
2652
+ * Only the first alias is shown in the auto-generated help.
2653
+ *
2654
+ * @param {string[]} [aliases]
2655
+ * @return {string[]|Command}
2656
+ */
2657
+
2658
+ aliases(aliases) {
2659
+ // Getter for the array of aliases is the main reason for having aliases() in addition to alias().
2660
+ if (aliases === undefined) return this._aliases;
2661
+
2662
+ aliases.forEach((alias) => this.alias(alias));
2663
+ return this;
2664
+ };
2665
+
2666
+ /**
2667
+ * Set / get the command usage `str`.
2668
+ *
2669
+ * @param {string} [str]
2670
+ * @return {String|Command}
2671
+ */
2672
+
2673
+ usage(str) {
2674
+ if (str === undefined) {
2675
+ if (this._usage) return this._usage;
2676
+
2677
+ const args = this._args.map((arg) => {
2678
+ return humanReadableArgName(arg);
2679
+ });
2680
+ return [].concat(
2681
+ (this.options.length || this._hasHelpOption ? '[options]' : []),
2682
+ (this.commands.length ? '[command]' : []),
2683
+ (this._args.length ? args : [])
2684
+ ).join(' ');
2685
+ }
2686
+
2687
+ this._usage = str;
2688
+ return this;
2689
+ };
2690
+
2691
+ /**
2692
+ * Get or set the name of the command
2693
+ *
2694
+ * @param {string} [str]
2695
+ * @return {string|Command}
2696
+ */
2697
+
2698
+ name(str) {
2699
+ if (str === undefined) return this._name;
2700
+ this._name = str;
2701
+ return this;
2702
+ };
2703
+
2704
+ /**
2705
+ * Return program help documentation.
2706
+ *
2707
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
2708
+ * @return {string}
2709
+ */
2710
+
2711
+ helpInformation(contextOptions) {
2712
+ const helper = this.createHelp();
2713
+ if (helper.helpWidth === undefined) {
2714
+ helper.helpWidth = (contextOptions && contextOptions.error) ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
2715
+ }
2716
+ return helper.formatHelp(this, helper);
2717
+ };
2718
+
2719
+ /**
2720
+ * @api private
2721
+ */
2722
+
2723
+ _getHelpContext(contextOptions) {
2724
+ contextOptions = contextOptions || {};
2725
+ const context = { error: !!contextOptions.error };
2726
+ let write;
2727
+ if (context.error) {
2728
+ write = (arg) => this._outputConfiguration.writeErr(arg);
2729
+ } else {
2730
+ write = (arg) => this._outputConfiguration.writeOut(arg);
2731
+ }
2732
+ context.write = contextOptions.write || write;
2733
+ context.command = this;
2734
+ return context;
2735
+ }
2736
+
2737
+ /**
2738
+ * Output help information for this command.
2739
+ *
2740
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2741
+ *
2742
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2743
+ */
2744
+
2745
+ outputHelp(contextOptions) {
2746
+ let deprecatedCallback;
2747
+ if (typeof contextOptions === 'function') {
2748
+ deprecatedCallback = contextOptions;
2749
+ contextOptions = undefined;
2750
+ }
2751
+ const context = this._getHelpContext(contextOptions);
2752
+
2753
+ const groupListeners = [];
2754
+ let command = this;
2755
+ while (command) {
2756
+ groupListeners.push(command); // ordered from current command to root
2757
+ command = command.parent;
2758
+ }
2759
+
2760
+ groupListeners.slice().reverse().forEach(command => command.emit('beforeAllHelp', context));
2761
+ this.emit('beforeHelp', context);
2762
+
2763
+ let helpInformation = this.helpInformation(context);
2764
+ if (deprecatedCallback) {
2765
+ helpInformation = deprecatedCallback(helpInformation);
2766
+ if (typeof helpInformation !== 'string' && !Buffer.isBuffer(helpInformation)) {
2767
+ throw new Error('outputHelp callback must return a string or a Buffer');
2768
+ }
2769
+ }
2770
+ context.write(helpInformation);
2771
+
2772
+ this.emit(this._helpLongFlag); // deprecated
2773
+ this.emit('afterHelp', context);
2774
+ groupListeners.forEach(command => command.emit('afterAllHelp', context));
2775
+ };
2776
+
2777
+ /**
2778
+ * You can pass in flags and a description to override the help
2779
+ * flags and help description for your command. Pass in false to
2780
+ * disable the built-in help option.
2781
+ *
2782
+ * @param {string | boolean} [flags]
2783
+ * @param {string} [description]
2784
+ * @return {Command} `this` command for chaining
2785
+ */
2786
+
2787
+ helpOption(flags, description) {
2788
+ if (typeof flags === 'boolean') {
2789
+ this._hasHelpOption = flags;
2790
+ return this;
2791
+ }
2792
+ this._helpFlags = flags || this._helpFlags;
2793
+ this._helpDescription = description || this._helpDescription;
2794
+
2795
+ const helpFlags = _parseOptionFlags(this._helpFlags);
2796
+ this._helpShortFlag = helpFlags.shortFlag;
2797
+ this._helpLongFlag = helpFlags.longFlag;
2798
+
2799
+ return this;
2800
+ };
2801
+
2802
+ /**
2803
+ * Output help information and exit.
2804
+ *
2805
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2806
+ *
2807
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2808
+ */
2809
+
2810
+ help(contextOptions) {
2811
+ this.outputHelp(contextOptions);
2812
+ let exitCode = process.exitCode || 0;
2813
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== 'function' && contextOptions.error) {
2814
+ exitCode = 1;
2815
+ }
2816
+ // message: do not have all displayed text available so only passing placeholder.
2817
+ this._exit(exitCode, 'commander.help', '(outputHelp)');
2818
+ };
2819
+
2820
+ /**
2821
+ * Add additional text to be displayed with the built-in help.
2822
+ *
2823
+ * Position is 'before' or 'after' to affect just this command,
2824
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
2825
+ *
2826
+ * @param {string} position - before or after built-in help
2827
+ * @param {string | Function} text - string to add, or a function returning a string
2828
+ * @return {Command} `this` command for chaining
2829
+ */
2830
+ addHelpText(position, text) {
2831
+ const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];
2832
+ if (!allowedValues.includes(position)) {
2833
+ throw new Error(`Unexpected value for position to addHelpText.
2834
+ Expecting one of '${allowedValues.join("', '")}'`);
2835
+ }
2836
+ const helpEvent = `${position}Help`;
2837
+ this.on(helpEvent, (context) => {
2838
+ let helpStr;
2839
+ if (typeof text === 'function') {
2840
+ helpStr = text({ error: context.error, command: context.command });
2841
+ } else {
2842
+ helpStr = text;
2843
+ }
2844
+ // Ignore falsy value when nothing to output.
2845
+ if (helpStr) {
2846
+ context.write(`${helpStr}\n`);
2847
+ }
2848
+ });
2849
+ return this;
2850
+ }
2851
+ }
2852
+ /**
2853
+ * Expose the root command.
2854
+ */
2855
+
2856
+ exports = module.exports = new Command();
2857
+ exports.program = exports; // More explicit access to global command.
2858
+
2859
+ /**
2860
+ * Expose classes
2861
+ */
2862
+
2863
+ exports.Command = Command;
2864
+ exports.Option = Option;
2865
+ exports.CommanderError = CommanderError;
2866
+ exports.InvalidOptionArgumentError = InvalidOptionArgumentError;
2867
+ exports.Help = Help;
2868
+
2869
+ /**
2870
+ * Camel-case the given `flag`
2871
+ *
2872
+ * @param {string} flag
2873
+ * @return {string}
2874
+ * @api private
2875
+ */
2876
+
2877
+ function camelcase(flag) {
2878
+ return flag.split('-').reduce((str, word) => {
2879
+ return str + word[0].toUpperCase() + word.slice(1);
2880
+ });
2881
+ }
2882
+
2883
+ /**
2884
+ * Output help information if help flags specified
2885
+ *
2886
+ * @param {Command} cmd - command to output help for
2887
+ * @param {Array} args - array of options to search for help flags
2888
+ * @api private
2889
+ */
2890
+
2891
+ function outputHelpIfRequested(cmd, args) {
2892
+ const helpOption = cmd._hasHelpOption && args.find(arg => arg === cmd._helpLongFlag || arg === cmd._helpShortFlag);
2893
+ if (helpOption) {
2894
+ cmd.outputHelp();
2895
+ // (Do not have all displayed text available so only passing placeholder.)
2896
+ cmd._exit(0, 'commander.helpDisplayed', '(outputHelp)');
2897
+ }
2898
+ }
2899
+
2900
+ /**
2901
+ * Takes an argument and returns its human readable equivalent for help usage.
2902
+ *
2903
+ * @param {Object} arg
2904
+ * @return {string}
2905
+ * @api private
2906
+ */
2907
+
2908
+ function humanReadableArgName(arg) {
2909
+ const nameOutput = arg.name + (arg.variadic === true ? '...' : '');
2910
+
2911
+ return arg.required
2912
+ ? '<' + nameOutput + '>'
2913
+ : '[' + nameOutput + ']';
2914
+ }
2915
+
2916
+ /**
2917
+ * Parse the short and long flag out of something like '-m,--mixed <value>'
2918
+ *
2919
+ * @api private
2920
+ */
2921
+
2922
+ function _parseOptionFlags(flags) {
2923
+ let shortFlag;
2924
+ let longFlag;
2925
+ // Use original very loose parsing to maintain backwards compatibility for now,
2926
+ // which allowed for example unintended `-sw, --short-word` [sic].
2927
+ const flagParts = flags.split(/[ |,]+/);
2928
+ if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1])) shortFlag = flagParts.shift();
2929
+ longFlag = flagParts.shift();
2930
+ // Add support for lone short flag without significantly changing parsing!
2931
+ if (!shortFlag && /^-[^-]$/.test(longFlag)) {
2932
+ shortFlag = longFlag;
2933
+ longFlag = undefined;
2934
+ }
2935
+ return { shortFlag, longFlag };
2936
+ }
2937
+
2938
+ /**
2939
+ * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
2940
+ *
2941
+ * @param {string[]} args - array of arguments from node.execArgv
2942
+ * @returns {string[]}
2943
+ * @api private
2944
+ */
2945
+
2946
+ function incrementNodeInspectorPort(args) {
2947
+ // Testing for these options:
2948
+ // --inspect[=[host:]port]
2949
+ // --inspect-brk[=[host:]port]
2950
+ // --inspect-port=[host:]port
2951
+ return args.map((arg) => {
2952
+ if (!arg.startsWith('--inspect')) {
2953
+ return arg;
2954
+ }
2955
+ let debugOption;
2956
+ let debugHost = '127.0.0.1';
2957
+ let debugPort = '9229';
2958
+ let match;
2959
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
2960
+ // e.g. --inspect
2961
+ debugOption = match[1];
2962
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2963
+ debugOption = match[1];
2964
+ if (/^\d+$/.test(match[3])) {
2965
+ // e.g. --inspect=1234
2966
+ debugPort = match[3];
2967
+ } else {
2968
+ // e.g. --inspect=localhost
2969
+ debugHost = match[3];
2970
+ }
2971
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
2972
+ // e.g. --inspect=localhost:1234
2973
+ debugOption = match[1];
2974
+ debugHost = match[3];
2975
+ debugPort = match[4];
2976
+ }
2977
+
2978
+ if (debugOption && debugPort !== '0') {
2979
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2980
+ }
2981
+ return arg;
2982
+ });
2983
+ }
2984
+ }(commander, commander.exports));
2985
+
2986
+ var domain; // The domain module is executed on demand
2987
+ var hasSetImmediate = typeof setImmediate === "function";
2988
+
2989
+ // Use the fastest means possible to execute a task in its own turn, with
2990
+ // priority over other events including network IO events in Node.js.
2991
+ //
2992
+ // An exception thrown by a task will permanently interrupt the processing of
2993
+ // subsequent tasks. The higher level `asap` function ensures that if an
2994
+ // exception is thrown by a task, that the task queue will continue flushing as
2995
+ // soon as possible, but if you use `rawAsap` directly, you are responsible to
2996
+ // either ensure that no exceptions are thrown from your task, or to manually
2997
+ // call `rawAsap.requestFlush` if an exception is thrown.
2998
+ var raw = rawAsap$1;
2999
+ function rawAsap$1(task) {
3000
+ if (!queue.length) {
3001
+ requestFlush();
3002
+ flushing = true;
3003
+ }
3004
+ // Avoids a function call
3005
+ queue[queue.length] = task;
3006
+ }
3007
+
3008
+ var queue = [];
3009
+ // Once a flush has been requested, no further calls to `requestFlush` are
3010
+ // necessary until the next `flush` completes.
3011
+ var flushing = false;
3012
+ // The position of the next task to execute in the task queue. This is
3013
+ // preserved between calls to `flush` so that it can be resumed if
3014
+ // a task throws an exception.
3015
+ var index$1 = 0;
3016
+ // If a task schedules additional tasks recursively, the task queue can grow
3017
+ // unbounded. To prevent memory excaustion, the task queue will periodically
3018
+ // truncate already-completed tasks.
3019
+ var capacity = 1024;
3020
+
3021
+ // The flush function processes all tasks that have been scheduled with
3022
+ // `rawAsap` unless and until one of those tasks throws an exception.
3023
+ // If a task throws an exception, `flush` ensures that its state will remain
3024
+ // consistent and will resume where it left off when called again.
3025
+ // However, `flush` does not make any arrangements to be called again if an
3026
+ // exception is thrown.
3027
+ function flush() {
3028
+ while (index$1 < queue.length) {
3029
+ var currentIndex = index$1;
3030
+ // Advance the index before calling the task. This ensures that we will
3031
+ // begin flushing on the next task the task throws an error.
3032
+ index$1 = index$1 + 1;
3033
+ queue[currentIndex].call();
3034
+ // Prevent leaking memory for long chains of recursive calls to `asap`.
3035
+ // If we call `asap` within tasks scheduled by `asap`, the queue will
3036
+ // grow, but to avoid an O(n) walk for every task we execute, we don't
3037
+ // shift tasks off the queue after they have been executed.
3038
+ // Instead, we periodically shift 1024 tasks off the queue.
3039
+ if (index$1 > capacity) {
3040
+ // Manually shift all values starting at the index back to the
3041
+ // beginning of the queue.
3042
+ for (var scan = 0, newLength = queue.length - index$1; scan < newLength; scan++) {
3043
+ queue[scan] = queue[scan + index$1];
3044
+ }
3045
+ queue.length -= index$1;
3046
+ index$1 = 0;
3047
+ }
3048
+ }
3049
+ queue.length = 0;
3050
+ index$1 = 0;
3051
+ flushing = false;
3052
+ }
3053
+
3054
+ rawAsap$1.requestFlush = requestFlush;
3055
+ function requestFlush() {
3056
+ // Ensure flushing is not bound to any domain.
3057
+ // It is not sufficient to exit the domain, because domains exist on a stack.
3058
+ // To execute code outside of any domain, the following dance is necessary.
3059
+ var parentDomain = process.domain;
3060
+ if (parentDomain) {
3061
+ if (!domain) {
3062
+ // Lazy execute the domain module.
3063
+ // Only employed if the user elects to use domains.
3064
+ domain = require$$0$3;
3065
+ }
3066
+ domain.active = process.domain = null;
3067
+ }
3068
+
3069
+ // `setImmediate` is slower that `process.nextTick`, but `process.nextTick`
3070
+ // cannot handle recursion.
3071
+ // `requestFlush` will only be called recursively from `asap.js`, to resume
3072
+ // flushing after an error is thrown into a domain.
3073
+ // Conveniently, `setImmediate` was introduced in the same version
3074
+ // `process.nextTick` started throwing recursion errors.
3075
+ if (flushing && hasSetImmediate) {
3076
+ setImmediate(flush);
3077
+ } else {
3078
+ process.nextTick(flush);
3079
+ }
3080
+
3081
+ if (parentDomain) {
3082
+ domain.active = process.domain = parentDomain;
3083
+ }
3084
+ }
3085
+
3086
+ var asap$2 = raw;
3087
+
3088
+ function noop() {}
3089
+
3090
+ // States:
3091
+ //
3092
+ // 0 - pending
3093
+ // 1 - fulfilled with _value
3094
+ // 2 - rejected with _value
3095
+ // 3 - adopted the state of another promise, _value
3096
+ //
3097
+ // once the state is no longer pending (0) it is immutable
3098
+
3099
+ // All `_` prefixed properties will be reduced to `_{random number}`
3100
+ // at build time to obfuscate them and discourage their use.
3101
+ // We don't use symbols or Object.defineProperty to fully hide them
3102
+ // because the performance isn't good enough.
3103
+
3104
+
3105
+ // to avoid using try/catch inside critical functions, we
3106
+ // extract them to here.
3107
+ var LAST_ERROR = null;
3108
+ var IS_ERROR = {};
3109
+ function getThen(obj) {
3110
+ try {
3111
+ return obj.then;
3112
+ } catch (ex) {
3113
+ LAST_ERROR = ex;
3114
+ return IS_ERROR;
3115
+ }
3116
+ }
3117
+
3118
+ function tryCallOne(fn, a) {
3119
+ try {
3120
+ return fn(a);
3121
+ } catch (ex) {
3122
+ LAST_ERROR = ex;
3123
+ return IS_ERROR;
3124
+ }
3125
+ }
3126
+ function tryCallTwo(fn, a, b) {
3127
+ try {
3128
+ fn(a, b);
3129
+ } catch (ex) {
3130
+ LAST_ERROR = ex;
3131
+ return IS_ERROR;
3132
+ }
3133
+ }
3134
+
3135
+ var core = Promise$7;
3136
+
3137
+ function Promise$7(fn) {
3138
+ if (typeof this !== 'object') {
3139
+ throw new TypeError('Promises must be constructed via new');
3140
+ }
3141
+ if (typeof fn !== 'function') {
3142
+ throw new TypeError('Promise constructor\'s argument is not a function');
3143
+ }
3144
+ this._U = 0;
3145
+ this._V = 0;
3146
+ this._W = null;
3147
+ this._X = null;
3148
+ if (fn === noop) return;
3149
+ doResolve(fn, this);
3150
+ }
3151
+ Promise$7._Y = null;
3152
+ Promise$7._Z = null;
3153
+ Promise$7._0 = noop;
3154
+
3155
+ Promise$7.prototype.then = function(onFulfilled, onRejected) {
3156
+ if (this.constructor !== Promise$7) {
3157
+ return safeThen(this, onFulfilled, onRejected);
3158
+ }
3159
+ var res = new Promise$7(noop);
3160
+ handle(this, new Handler(onFulfilled, onRejected, res));
3161
+ return res;
3162
+ };
3163
+
3164
+ function safeThen(self, onFulfilled, onRejected) {
3165
+ return new self.constructor(function (resolve, reject) {
3166
+ var res = new Promise$7(noop);
3167
+ res.then(resolve, reject);
3168
+ handle(self, new Handler(onFulfilled, onRejected, res));
3169
+ });
3170
+ }
3171
+ function handle(self, deferred) {
3172
+ while (self._V === 3) {
3173
+ self = self._W;
3174
+ }
3175
+ if (Promise$7._Y) {
3176
+ Promise$7._Y(self);
3177
+ }
3178
+ if (self._V === 0) {
3179
+ if (self._U === 0) {
3180
+ self._U = 1;
3181
+ self._X = deferred;
3182
+ return;
3183
+ }
3184
+ if (self._U === 1) {
3185
+ self._U = 2;
3186
+ self._X = [self._X, deferred];
3187
+ return;
3188
+ }
3189
+ self._X.push(deferred);
3190
+ return;
3191
+ }
3192
+ handleResolved(self, deferred);
3193
+ }
3194
+
3195
+ function handleResolved(self, deferred) {
3196
+ asap$2(function() {
3197
+ var cb = self._V === 1 ? deferred.onFulfilled : deferred.onRejected;
3198
+ if (cb === null) {
3199
+ if (self._V === 1) {
3200
+ resolve(deferred.promise, self._W);
3201
+ } else {
3202
+ reject(deferred.promise, self._W);
3203
+ }
3204
+ return;
3205
+ }
3206
+ var ret = tryCallOne(cb, self._W);
3207
+ if (ret === IS_ERROR) {
3208
+ reject(deferred.promise, LAST_ERROR);
3209
+ } else {
3210
+ resolve(deferred.promise, ret);
3211
+ }
3212
+ });
3213
+ }
3214
+ function resolve(self, newValue) {
3215
+ // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
3216
+ if (newValue === self) {
3217
+ return reject(
3218
+ self,
3219
+ new TypeError('A promise cannot be resolved with itself.')
3220
+ );
3221
+ }
3222
+ if (
3223
+ newValue &&
3224
+ (typeof newValue === 'object' || typeof newValue === 'function')
3225
+ ) {
3226
+ var then = getThen(newValue);
3227
+ if (then === IS_ERROR) {
3228
+ return reject(self, LAST_ERROR);
3229
+ }
3230
+ if (
3231
+ then === self.then &&
3232
+ newValue instanceof Promise$7
3233
+ ) {
3234
+ self._V = 3;
3235
+ self._W = newValue;
3236
+ finale(self);
3237
+ return;
3238
+ } else if (typeof then === 'function') {
3239
+ doResolve(then.bind(newValue), self);
3240
+ return;
3241
+ }
3242
+ }
3243
+ self._V = 1;
3244
+ self._W = newValue;
3245
+ finale(self);
3246
+ }
3247
+
3248
+ function reject(self, newValue) {
3249
+ self._V = 2;
3250
+ self._W = newValue;
3251
+ if (Promise$7._Z) {
3252
+ Promise$7._Z(self, newValue);
3253
+ }
3254
+ finale(self);
3255
+ }
3256
+ function finale(self) {
3257
+ if (self._U === 1) {
3258
+ handle(self, self._X);
3259
+ self._X = null;
3260
+ }
3261
+ if (self._U === 2) {
3262
+ for (var i = 0; i < self._X.length; i++) {
3263
+ handle(self, self._X[i]);
3264
+ }
3265
+ self._X = null;
3266
+ }
3267
+ }
3268
+
3269
+ function Handler(onFulfilled, onRejected, promise){
3270
+ this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
3271
+ this.onRejected = typeof onRejected === 'function' ? onRejected : null;
3272
+ this.promise = promise;
3273
+ }
3274
+
3275
+ /**
3276
+ * Take a potentially misbehaving resolver function and make sure
3277
+ * onFulfilled and onRejected are only called once.
3278
+ *
3279
+ * Makes no guarantees about asynchrony.
3280
+ */
3281
+ function doResolve(fn, promise) {
3282
+ var done = false;
3283
+ var res = tryCallTwo(fn, function (value) {
3284
+ if (done) return;
3285
+ done = true;
3286
+ resolve(promise, value);
3287
+ }, function (reason) {
3288
+ if (done) return;
3289
+ done = true;
3290
+ reject(promise, reason);
3291
+ });
3292
+ if (!done && res === IS_ERROR) {
3293
+ done = true;
3294
+ reject(promise, LAST_ERROR);
3295
+ }
3296
+ }
3297
+
3298
+ var Promise$6 = core;
3299
+ Promise$6.prototype.done = function (onFulfilled, onRejected) {
3300
+ var self = arguments.length ? this.then.apply(this, arguments) : this;
3301
+ self.then(null, function (err) {
3302
+ setTimeout(function () {
3303
+ throw err;
3304
+ }, 0);
3305
+ });
3306
+ };
3307
+
3308
+ var Promise$5 = core;
3309
+ Promise$5.prototype.finally = function (f) {
3310
+ return this.then(function (value) {
3311
+ return Promise$5.resolve(f()).then(function () {
3312
+ return value;
3313
+ });
3314
+ }, function (err) {
3315
+ return Promise$5.resolve(f()).then(function () {
3316
+ throw err;
3317
+ });
3318
+ });
3319
+ };
3320
+
3321
+ //This file contains the ES6 extensions to the core Promises/A+ API
3322
+
3323
+ var Promise$4 = core;
3324
+
3325
+ /* Static Functions */
3326
+
3327
+ var TRUE = valuePromise(true);
3328
+ var FALSE = valuePromise(false);
3329
+ var NULL = valuePromise(null);
3330
+ var UNDEFINED = valuePromise(undefined);
3331
+ var ZERO = valuePromise(0);
3332
+ var EMPTYSTRING = valuePromise('');
3333
+
3334
+ function valuePromise(value) {
3335
+ var p = new Promise$4(Promise$4._0);
3336
+ p._V = 1;
3337
+ p._W = value;
3338
+ return p;
3339
+ }
3340
+ Promise$4.resolve = function (value) {
3341
+ if (value instanceof Promise$4) return value;
3342
+
3343
+ if (value === null) return NULL;
3344
+ if (value === undefined) return UNDEFINED;
3345
+ if (value === true) return TRUE;
3346
+ if (value === false) return FALSE;
3347
+ if (value === 0) return ZERO;
3348
+ if (value === '') return EMPTYSTRING;
3349
+
3350
+ if (typeof value === 'object' || typeof value === 'function') {
3351
+ try {
3352
+ var then = value.then;
3353
+ if (typeof then === 'function') {
3354
+ return new Promise$4(then.bind(value));
3355
+ }
3356
+ } catch (ex) {
3357
+ return new Promise$4(function (resolve, reject) {
3358
+ reject(ex);
3359
+ });
3360
+ }
3361
+ }
3362
+ return valuePromise(value);
3363
+ };
3364
+
3365
+ var iterableToArray = function (iterable) {
3366
+ if (typeof Array.from === 'function') {
3367
+ // ES2015+, iterables exist
3368
+ iterableToArray = Array.from;
3369
+ return Array.from(iterable);
3370
+ }
3371
+
3372
+ // ES5, only arrays and array-likes exist
3373
+ iterableToArray = function (x) { return Array.prototype.slice.call(x); };
3374
+ return Array.prototype.slice.call(iterable);
3375
+ };
3376
+
3377
+ Promise$4.all = function (arr) {
3378
+ var args = iterableToArray(arr);
3379
+
3380
+ return new Promise$4(function (resolve, reject) {
3381
+ if (args.length === 0) return resolve([]);
3382
+ var remaining = args.length;
3383
+ function res(i, val) {
3384
+ if (val && (typeof val === 'object' || typeof val === 'function')) {
3385
+ if (val instanceof Promise$4 && val.then === Promise$4.prototype.then) {
3386
+ while (val._V === 3) {
3387
+ val = val._W;
3388
+ }
3389
+ if (val._V === 1) return res(i, val._W);
3390
+ if (val._V === 2) reject(val._W);
3391
+ val.then(function (val) {
3392
+ res(i, val);
3393
+ }, reject);
3394
+ return;
3395
+ } else {
3396
+ var then = val.then;
3397
+ if (typeof then === 'function') {
3398
+ var p = new Promise$4(then.bind(val));
3399
+ p.then(function (val) {
3400
+ res(i, val);
3401
+ }, reject);
3402
+ return;
3403
+ }
3404
+ }
3405
+ }
3406
+ args[i] = val;
3407
+ if (--remaining === 0) {
3408
+ resolve(args);
3409
+ }
3410
+ }
3411
+ for (var i = 0; i < args.length; i++) {
3412
+ res(i, args[i]);
3413
+ }
3414
+ });
3415
+ };
3416
+
3417
+ Promise$4.reject = function (value) {
3418
+ return new Promise$4(function (resolve, reject) {
3419
+ reject(value);
3420
+ });
3421
+ };
3422
+
3423
+ Promise$4.race = function (values) {
3424
+ return new Promise$4(function (resolve, reject) {
3425
+ iterableToArray(values).forEach(function(value){
3426
+ Promise$4.resolve(value).then(resolve, reject);
3427
+ });
3428
+ });
3429
+ };
3430
+
3431
+ /* Prototype Methods */
3432
+
3433
+ Promise$4.prototype['catch'] = function (onRejected) {
3434
+ return this.then(null, onRejected);
3435
+ };
3436
+
3437
+ var rawAsap = raw;
3438
+ var freeTasks = [];
3439
+
3440
+ /**
3441
+ * Calls a task as soon as possible after returning, in its own event, with
3442
+ * priority over IO events. An exception thrown in a task can be handled by
3443
+ * `process.on("uncaughtException") or `domain.on("error")`, but will otherwise
3444
+ * crash the process. If the error is handled, all subsequent tasks will
3445
+ * resume.
3446
+ *
3447
+ * @param {{call}} task A callable object, typically a function that takes no
3448
+ * arguments.
3449
+ */
3450
+ var asap_1 = asap$1;
3451
+ function asap$1(task) {
3452
+ var rawTask;
3453
+ if (freeTasks.length) {
3454
+ rawTask = freeTasks.pop();
3455
+ } else {
3456
+ rawTask = new RawTask();
3457
+ }
3458
+ rawTask.task = task;
3459
+ rawTask.domain = process.domain;
3460
+ rawAsap(rawTask);
3461
+ }
3462
+
3463
+ function RawTask() {
3464
+ this.task = null;
3465
+ this.domain = null;
3466
+ }
3467
+
3468
+ RawTask.prototype.call = function () {
3469
+ if (this.domain) {
3470
+ this.domain.enter();
3471
+ }
3472
+ var threw = true;
3473
+ try {
3474
+ this.task.call();
3475
+ threw = false;
3476
+ // If the task throws an exception (presumably) Node.js restores the
3477
+ // domain stack for the next event.
3478
+ if (this.domain) {
3479
+ this.domain.exit();
3480
+ }
3481
+ } finally {
3482
+ // We use try/finally and a threw flag to avoid messing up stack traces
3483
+ // when we catch and release errors.
3484
+ if (threw) {
3485
+ // In Node.js, uncaught exceptions are considered fatal errors.
3486
+ // Re-throw them to interrupt flushing!
3487
+ // Ensure that flushing continues if an uncaught exception is
3488
+ // suppressed listening process.on("uncaughtException") or
3489
+ // domain.on("error").
3490
+ rawAsap.requestFlush();
3491
+ }
3492
+ // If the task threw an error, we do not want to exit the domain here.
3493
+ // Exiting the domain would prevent the domain from catching the error.
3494
+ this.task = null;
3495
+ this.domain = null;
3496
+ freeTasks.push(this);
3497
+ }
3498
+ };
3499
+
3500
+ // This file contains then/promise specific extensions that are only useful
3501
+ // for node.js interop
3502
+
3503
+ var Promise$3 = core;
3504
+ var asap = asap_1;
3505
+
3506
+ /* Static Functions */
3507
+
3508
+ Promise$3.denodeify = function (fn, argumentCount) {
3509
+ if (
3510
+ typeof argumentCount === 'number' && argumentCount !== Infinity
3511
+ ) {
3512
+ return denodeifyWithCount(fn, argumentCount);
3513
+ } else {
3514
+ return denodeifyWithoutCount(fn);
3515
+ }
3516
+ };
3517
+
3518
+ var callbackFn = (
3519
+ 'function (err, res) {' +
3520
+ 'if (err) { rj(err); } else { rs(res); }' +
3521
+ '}'
3522
+ );
3523
+ function denodeifyWithCount(fn, argumentCount) {
3524
+ var args = [];
3525
+ for (var i = 0; i < argumentCount; i++) {
3526
+ args.push('a' + i);
3527
+ }
3528
+ var body = [
3529
+ 'return function (' + args.join(',') + ') {',
3530
+ 'var self = this;',
3531
+ 'return new Promise(function (rs, rj) {',
3532
+ 'var res = fn.call(',
3533
+ ['self'].concat(args).concat([callbackFn]).join(','),
3534
+ ');',
3535
+ 'if (res &&',
3536
+ '(typeof res === "object" || typeof res === "function") &&',
3537
+ 'typeof res.then === "function"',
3538
+ ') {rs(res);}',
3539
+ '});',
3540
+ '};'
3541
+ ].join('');
3542
+ return Function(['Promise', 'fn'], body)(Promise$3, fn);
3543
+ }
3544
+ function denodeifyWithoutCount(fn) {
3545
+ var fnLength = Math.max(fn.length - 1, 3);
3546
+ var args = [];
3547
+ for (var i = 0; i < fnLength; i++) {
3548
+ args.push('a' + i);
3549
+ }
3550
+ var body = [
3551
+ 'return function (' + args.join(',') + ') {',
3552
+ 'var self = this;',
3553
+ 'var args;',
3554
+ 'var argLength = arguments.length;',
3555
+ 'if (arguments.length > ' + fnLength + ') {',
3556
+ 'args = new Array(arguments.length + 1);',
3557
+ 'for (var i = 0; i < arguments.length; i++) {',
3558
+ 'args[i] = arguments[i];',
3559
+ '}',
3560
+ '}',
3561
+ 'return new Promise(function (rs, rj) {',
3562
+ 'var cb = ' + callbackFn + ';',
3563
+ 'var res;',
3564
+ 'switch (argLength) {',
3565
+ args.concat(['extra']).map(function (_, index) {
3566
+ return (
3567
+ 'case ' + (index) + ':' +
3568
+ 'res = fn.call(' + ['self'].concat(args.slice(0, index)).concat('cb').join(',') + ');' +
3569
+ 'break;'
3570
+ );
3571
+ }).join(''),
3572
+ 'default:',
3573
+ 'args[argLength] = cb;',
3574
+ 'res = fn.apply(self, args);',
3575
+ '}',
3576
+
3577
+ 'if (res &&',
3578
+ '(typeof res === "object" || typeof res === "function") &&',
3579
+ 'typeof res.then === "function"',
3580
+ ') {rs(res);}',
3581
+ '});',
3582
+ '};'
3583
+ ].join('');
3584
+
3585
+ return Function(
3586
+ ['Promise', 'fn'],
3587
+ body
3588
+ )(Promise$3, fn);
3589
+ }
3590
+
3591
+ Promise$3.nodeify = function (fn) {
3592
+ return function () {
3593
+ var args = Array.prototype.slice.call(arguments);
3594
+ var callback =
3595
+ typeof args[args.length - 1] === 'function' ? args.pop() : null;
3596
+ var ctx = this;
3597
+ try {
3598
+ return fn.apply(this, arguments).nodeify(callback, ctx);
3599
+ } catch (ex) {
3600
+ if (callback === null || typeof callback == 'undefined') {
3601
+ return new Promise$3(function (resolve, reject) {
3602
+ reject(ex);
3603
+ });
3604
+ } else {
3605
+ asap(function () {
3606
+ callback.call(ctx, ex);
3607
+ });
3608
+ }
3609
+ }
3610
+ }
3611
+ };
3612
+
3613
+ Promise$3.prototype.nodeify = function (callback, ctx) {
3614
+ if (typeof callback != 'function') return this;
3615
+
3616
+ this.then(function (value) {
3617
+ asap(function () {
3618
+ callback.call(ctx, null, value);
3619
+ });
3620
+ }, function (err) {
3621
+ asap(function () {
3622
+ callback.call(ctx, err);
3623
+ });
3624
+ });
3625
+ };
3626
+
3627
+ var Promise$2 = core;
3628
+ Promise$2.enableSynchronous = function () {
3629
+ Promise$2.prototype.isPending = function() {
3630
+ return this.getState() == 0;
3631
+ };
3632
+
3633
+ Promise$2.prototype.isFulfilled = function() {
3634
+ return this.getState() == 1;
3635
+ };
3636
+
3637
+ Promise$2.prototype.isRejected = function() {
3638
+ return this.getState() == 2;
3639
+ };
3640
+
3641
+ Promise$2.prototype.getValue = function () {
3642
+ if (this._V === 3) {
3643
+ return this._W.getValue();
3644
+ }
3645
+
3646
+ if (!this.isFulfilled()) {
3647
+ throw new Error('Cannot get a value of an unfulfilled promise.');
3648
+ }
3649
+
3650
+ return this._W;
3651
+ };
3652
+
3653
+ Promise$2.prototype.getReason = function () {
3654
+ if (this._V === 3) {
3655
+ return this._W.getReason();
3656
+ }
3657
+
3658
+ if (!this.isRejected()) {
3659
+ throw new Error('Cannot get a rejection reason of a non-rejected promise.');
3660
+ }
3661
+
3662
+ return this._W;
3663
+ };
3664
+
3665
+ Promise$2.prototype.getState = function () {
3666
+ if (this._V === 3) {
3667
+ return this._W.getState();
3668
+ }
3669
+ if (this._V === -1 || this._V === -2) {
3670
+ return 0;
3671
+ }
3672
+
3673
+ return this._V;
3674
+ };
3675
+ };
3676
+
3677
+ Promise$2.disableSynchronous = function() {
3678
+ Promise$2.prototype.isPending = undefined;
3679
+ Promise$2.prototype.isFulfilled = undefined;
3680
+ Promise$2.prototype.isRejected = undefined;
3681
+ Promise$2.prototype.getValue = undefined;
3682
+ Promise$2.prototype.getReason = undefined;
3683
+ Promise$2.prototype.getState = undefined;
3684
+ };
3685
+
3686
+ var lib = core;
3687
+
3688
+ var promise = lib;
3689
+
3690
+ /**
3691
+ * @license
3692
+ * Copyright 2016 The AMP HTML Authors. All Rights Reserved.
3693
+ *
3694
+ * Licensed under the Apache License, Version 2.0 (the "License");
3695
+ * you may not use this file except in compliance with the License.
3696
+ * You may obtain a copy of the License at
3697
+ *
3698
+ * http://www.apache.org/licenses/LICENSE-2.0
3699
+ *
3700
+ * Unless required by applicable law or agreed to in writing, software
3701
+ * distributed under the License is distributed on an "AS-IS" BASIS,
3702
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3703
+ * See the License for the specific language governing permissions and
3704
+ * limitations under the license.
3705
+ */
3706
+
3707
+ const colors = safe.exports;
3708
+ const fs = fs__default;
3709
+ const http = http$1;
3710
+ const https = https$1;
3711
+ const program = commander.exports;
3712
+ const Promise$1 = promise;
3713
+ const vm = require$$10;
3714
+
3715
+ const DEFAULT_USER_AGENT = 'amphtml-validator';
3716
+
3717
+ /**
3718
+ * Determines if str begins with prefix.
3719
+ * @param {string} str
3720
+ * @param {string} prefix
3721
+ * @return {boolean}
3722
+ */
3723
+ function hasPrefix(str, prefix) {
3724
+ return str.indexOf(prefix) == 0;
3725
+ }
3726
+
3727
+ /**
3728
+ * Convenience function to detect whether an argument is a URL. If not,
3729
+ * it may be a local file.
3730
+ * @param {string} url
3731
+ * @return {boolean}
3732
+ */
3733
+ function isHttpOrHttpsUrl(url) {
3734
+ return hasPrefix(url, 'http://') || hasPrefix(url, 'https://');
3735
+ }
3736
+
3737
+ /**
3738
+ * Creates a promise which reads from a file.
3739
+ * @param {string} name
3740
+ * @return {Promise<string>}
3741
+ */
3742
+ function readFromFile(name) {
3743
+ return new Promise$1(function(resolve, reject) {
3744
+ fs.readFile(name, 'utf8', function(err, data) {
3745
+ if (err) {
3746
+ reject(err);
3747
+ } else {
3748
+ resolve(data.trim());
3749
+ }
3750
+ });
3751
+ });
3752
+ }
3753
+
3754
+ /**
3755
+ * Creates a promise which reads from a stream.
3756
+ * @param {string} name
3757
+ * @param {!stream.Readable} readable
3758
+ * @return {Promise<string>}
3759
+ */
3760
+ function readFromReadable(name, readable) {
3761
+ return new Promise$1(function(resolve, reject) {
3762
+ const chunks = [];
3763
+ readable.setEncoding('utf8');
3764
+ readable.on('data', function(chunk) {
3765
+ chunks.push(chunk);
3766
+ });
3767
+ readable.on('end', function() {
3768
+ resolve(chunks.join(''));
3769
+ });
3770
+ readable.on('error', function(error) {
3771
+ reject(new Error('Could not read from ' + name + ' - ' + error.message));
3772
+ });
3773
+ });
3774
+ }
3775
+
3776
+ /**
3777
+ * Creates a promise which reads from standard input. Even though it would
3778
+ * be easy to make a function that just returns the data, we return a promise
3779
+ * for consistency with readFromUrl and readFromFile.
3780
+ * @return {Promise<string>}
3781
+ */
3782
+ function readFromStdin() {
3783
+ return readFromReadable('stdin', process.stdin).then(function(data) {
3784
+ process.stdin.resume();
3785
+ return data;
3786
+ });
3787
+ }
3788
+
3789
+ /**
3790
+ * Creates a promise which reads from a URL or more precisely, fetches
3791
+ * the contents located at the URL by using the 'http' or 'https' module.
3792
+ * Any HTTP status other than 200 is interpreted as an error.
3793
+ * @param {string} url
3794
+ * @param {string} userAgent
3795
+ * @return {Promise<string>}
3796
+ */
3797
+ function readFromUrl(url, userAgent) {
3798
+ return new Promise$1(function(resolve, reject) {
3799
+ const clientModule = hasPrefix(url, 'http://') ? http : https;
3800
+ const req = clientModule.request(url, function(response) {
3801
+ if (response.statusCode !== 200) {
3802
+ // https://nodejs.org/api/http.html says: "[...] However, if
3803
+ // you add a 'response' event handler, then you must consume
3804
+ // the data from the response object, either by calling
3805
+ // response.read() whenever there is a 'readable' event, or by
3806
+ // adding a 'data' handler, or by calling the .resume()
3807
+ // method."
3808
+ response.resume();
3809
+ reject(new Error(
3810
+ 'Unable to fetch ' + url + ' - HTTP Status ' +
3811
+ response.statusCode));
3812
+ } else {
3813
+ resolve(response);
3814
+ }
3815
+ });
3816
+ req.setHeader('User-Agent', userAgent);
3817
+ req.on('error', function(error) { // E.g., DNS resolution errors.
3818
+ reject(
3819
+ new Error('Unable to fetch ' + url + ' - ' + error.message));
3820
+ });
3821
+ req.end();
3822
+ })
3823
+ .then(readFromReadable.bind(null, url));
3824
+ }
3825
+
3826
+ /**
3827
+ * ValidationResult is the record computed by the validator for each
3828
+ * document. It contains an overall status (PASS/FAIL) and the list of
3829
+ * errors, if any. This class corresponds to the ValidationResult
3830
+ * message in validator.proto in this directory.
3831
+ * @export
3832
+ * @constructor
3833
+ */
3834
+ function ValidationResult() {
3835
+ /**
3836
+ * Possible values are 'UNKNOWN', 'PASS', and 'FAIL'.
3837
+ * @type {string}
3838
+ */
3839
+ this.status = 'UNKNOWN';
3840
+ /** @type {!Array<!ValidationError>} */
3841
+ this.errors = [];
3842
+ }
3843
+
3844
+ /**
3845
+ * Each validation error describes a specific problem in a validated
3846
+ * document. This class corresponds to the ValidationError message in
3847
+ * validator.proto in this directory.
3848
+ * @export
3849
+ * @constructor
3850
+ */
3851
+ function ValidationError() {
3852
+ /**
3853
+ * The severity of the error - possible values are 'UNKNOWN_SEVERITY',
3854
+ * 'ERROR', and 'WARNING'.
3855
+ */
3856
+ this.severity = 'UNKNOWN_SEVERITY';
3857
+ /**
3858
+ * The line number at which the error was seen (1 is the first line).
3859
+ */
3860
+ this.line = 1;
3861
+ /**
3862
+ * The column number at which the error was seen (0 is the first column).
3863
+ */
3864
+ this.col = 0;
3865
+ /**
3866
+ * A human-readable error message for the validation error.
3867
+ * If you find yourself trying to write a parser against this string
3868
+ * to scrape out some detail, consider looking at the code and params
3869
+ * fields below.
3870
+ * @type {string}
3871
+ */
3872
+ this.message = '';
3873
+ /**
3874
+ * The spec URL is often added by the validator to provide additional
3875
+ * context for the error. In a user interface this would be shown
3876
+ * as a "Learn more" link.
3877
+ * @type {string}
3878
+ */
3879
+ this.specUrl = null;
3880
+ /**
3881
+ * This field is only useful when scripting against the validator,
3882
+ * it should not be displayed in a user interface as it adds nothing
3883
+ * for humans to read over the message field (see above).
3884
+ * Possible values are the codes listed in ValidationError.Code - see
3885
+ * validator.proto. Examples: 'UNKNOWN_CODE', 'MANDATORY_TAG_MISSING',
3886
+ * 'TAG_REQUIRED_BY_MISSING'. For each of these codes there is a
3887
+ * format string in validator-main.protoascii (look for error_formats),
3888
+ * which is used to assemble the message from the strings in params.
3889
+ * @type {string}
3890
+ */
3891
+ this.code = 'UNKNOWN_CODE';
3892
+ /**
3893
+ * This field is only useful when scripting against the validator,
3894
+ * it should not be displayed in a user interface as it adds nothing
3895
+ * for humans to read over the message field (see above).
3896
+ * @type {!Array<string>}
3897
+ */
3898
+ this.params = [];
3899
+ }
3900
+
3901
+ /**
3902
+ * The validator instance is a proxy object to a precompiled
3903
+ * validator_wasm.js script - in practice the script was either downloaded
3904
+ * from 'https://cdn.ampproject.org/v0/validator_wasm.js' or read from a
3905
+ * local file.
3906
+ * @param {string} scriptContents
3907
+ * @throws {!Error}
3908
+ * @constructor
3909
+ */
3910
+ function Validator(scriptContents) {
3911
+ // The 'sandbox' is a Javascript object (dictionary) which holds
3912
+ // the results of evaluating the validatorJs / scriptContents, so
3913
+ // basically, it holds functions, prototypes, etc. As a
3914
+ // side-effect of evaluating, the VM will compile this code and
3915
+ // it's worth holding onto it. Hence, this validate function is
3916
+ // reached via 2 codepaths - either the sandbox came from the
3917
+ // cache, precompiledByValidatorJs - or we just varructed it
3918
+ // after downloading and evaluating the script. The API is fancier
3919
+ // here, vm.Script / vm.createContext / vm.runInContext and all
3920
+ // that, but it's quite similar to a Javascript eval.
3921
+ this.sandbox = vm.createContext();
3922
+ try {
3923
+ new vm.Script(scriptContents).runInContext(this.sandbox);
3924
+ } catch (error) {
3925
+ throw new Error('Could not instantiate validator_wasm.js - ' +
3926
+ error.message);
3927
+ }
3928
+ }
3929
+
3930
+ /**
3931
+ * Initialize the validator.
3932
+ * @return {Promise<undefined>!}
3933
+ */
3934
+ Validator.prototype.init = function() {
3935
+ if (this.sandbox.amp.validator.init) {
3936
+ return this.sandbox.amp.validator.init();
3937
+ } else {
3938
+ return Promise$1.resolve(undefined);
3939
+ }
3940
+ };
3941
+
3942
+ /**
3943
+ * Validates the provided inputString; the htmlFormat can be 'AMP' or
3944
+ * 'AMP4ADS'; it defaults to 'AMP' if not specified.
3945
+ * @param {string} inputString
3946
+ * @param {string=} htmlFormat
3947
+ * @return {!ValidationResult}
3948
+ * @export
3949
+ */
3950
+ Validator.prototype.validateString = function(inputString, htmlFormat) {
3951
+ const internalResult =
3952
+ this.sandbox.amp.validator.validateString(inputString, htmlFormat);
3953
+ const result = new ValidationResult();
3954
+ result.status = internalResult.status;
3955
+ for (let ii = 0; ii < internalResult.errors.length; ii++) {
3956
+ const internalError = internalResult.errors[ii];
3957
+ const error = new ValidationError();
3958
+ error.severity = internalError.severity;
3959
+ error.line = internalError.line;
3960
+ error.col = internalError.col;
3961
+ error.message =
3962
+ this.sandbox.amp.validator.renderErrorMessage(internalError);
3963
+ error.specUrl = internalError.specUrl;
3964
+ error.code = internalError.code;
3965
+ error.params = internalError.params;
3966
+ result.errors.push(error);
3967
+ }
3968
+ return result;
3969
+ };
3970
+
3971
+ /**
3972
+ * A global static map used by the getInstance function to avoid loading
3973
+ * AMP Validators more than once.
3974
+ * @type {!Object<string, Validator>}
3975
+ */
3976
+ const instanceByValidatorJs = {};
3977
+
3978
+ /**
3979
+ * Provided a URL or a filename from which to fetch the validator_wasm.js
3980
+ * file, fetches, instantiates, and caches the validator instance
3981
+ * asynchronously. If you prefer to implement your own fetching /
3982
+ * caching logic, you may want to consider newInstance() instead,
3983
+ * which is synchronous and much simpler.
3984
+ *
3985
+ * @param {string=} opt_validatorJs
3986
+ * @param {string=} opt_userAgent
3987
+ * @return {!Promise<Validator>}
3988
+ * @export
3989
+ */
3990
+ function getInstance(opt_validatorJs, opt_userAgent) {
3991
+ const validatorJs =
3992
+ opt_validatorJs || 'https://cdn.ampproject.org/v0/validator_wasm.js';
3993
+ const userAgent = opt_userAgent || DEFAULT_USER_AGENT;
3994
+ if (instanceByValidatorJs.hasOwnProperty(validatorJs)) {
3995
+ return Promise$1.resolve(instanceByValidatorJs[validatorJs]);
3996
+ }
3997
+ const validatorJsPromise = isHttpOrHttpsUrl(validatorJs) ?
3998
+ readFromUrl(validatorJs, userAgent) :
3999
+ readFromFile(validatorJs);
4000
+ return validatorJsPromise.then(function(scriptContents) {
4001
+ let instance;
4002
+ try {
4003
+ instance = new Validator(scriptContents);
4004
+ } catch (error) {
4005
+ // It may be useful to cache errors and exceptions encountered
4006
+ // here, but for now we don't do this for e.g. http errors when
4007
+ // fetching the validator, so we shouldn't do it for syntax
4008
+ // errors etc. either (which lead to the varructor throwing an error).
4009
+ throw error;
4010
+ }
4011
+ instanceByValidatorJs[validatorJs] = instance;
4012
+ return instance;
4013
+ }).then(function(instance) {
4014
+ return instance.init().then(() => instance);
4015
+ });
4016
+ }
4017
+ var getInstance_1 = amphtmlValidator.getInstance = getInstance;
4018
+
4019
+ /**
4020
+ * Provided the contents of the validator_wasm.js file, e.g. as downloaded from
4021
+ * 'https://cdn.ampproject.org/v0/validator_wasm.js', returns a new validator
4022
+ * instance. The tradeoff between this function and getInstance() is that this
4023
+ * function is synchronous but requires the contents of the validator_wasm.js
4024
+ * file as a parameter, while getInstance is asynchronous, fetches files
4025
+ * from disk or the web, and caches them.
4026
+ *
4027
+ * @param {string} validatorJsContents
4028
+ * @return {!Validator}
4029
+ * @export
4030
+ */
4031
+ function newInstance(validatorJsContents) {
4032
+ return new Validator(validatorJsContents);
4033
+ }
4034
+ var newInstance_1 = amphtmlValidator.newInstance = newInstance;
4035
+
4036
+ // A note on emitting output to the console and process exit status:
4037
+ // Node.js prior to 0.11.8 did not support process.exitCode
4038
+ // (https://nodejs.org/api/process.html#process_process_exitcode), which
4039
+ // makes it difficult to emit output and errors from multiple callbacks
4040
+ // and set the appropriate exit code. We use the following workaround:
4041
+ // process.<<stream>>(<<some output>>, function() { process.exit(<<code>>); });
4042
+ // This will flush the appropriate stream (stdout or stderr) and then
4043
+ // exit with the provided code. For now, this makes the CLI work with
4044
+ // Node.js versions as old as v0.10.25.
4045
+
4046
+ /**
4047
+ * Logs a validation result to the console using process.stdout and
4048
+ * process.stderr as is appropriate.
4049
+ * @param {string} filename
4050
+ * @param {!ValidationResult} validationResult
4051
+ * @param {boolean} color
4052
+ */
4053
+ function logValidationResult(filename, validationResult, color) {
4054
+ if (validationResult.status === 'PASS') {
4055
+ process.stdout.write(
4056
+ filename + ': ' + (color ? colors.green('PASS') : 'PASS') + '\n');
4057
+ }
4058
+ for (let ii = 0; ii < validationResult.errors.length; ii++) {
4059
+ const error = validationResult.errors[ii];
4060
+ let msg = filename + ':' + error.line + ':' + error.col + ' ';
4061
+ if (color) {
4062
+ msg += (error.severity === 'ERROR' ? colors.red : colors.magenta)(
4063
+ error.message);
4064
+ } else {
4065
+ msg += error.message;
4066
+ }
4067
+ if (error.specUrl) {
4068
+ msg += ' (see ' + error.specUrl + ')';
4069
+ }
4070
+ // TODO(powdercloud): Should we distinguish error.severity === 'WARNING' ?
4071
+ process.stderr.write(msg + '\n');
4072
+ }
4073
+ }
4074
+
4075
+ /**
4076
+ * Main entry point into the command line tool.
4077
+ */
4078
+ function main() {
4079
+ program
4080
+ .usage(
4081
+ '[options] <fileOrUrlOrMinus...>\n\n' +
4082
+ ' Validates the files or urls provided as arguments. If "-" is\n' +
4083
+ ' specified, reads from stdin instead.')
4084
+ .option(
4085
+ '--validator_js <fileOrUrl>',
4086
+ 'The Validator Javascript.\n' +
4087
+ ' Latest published version by default, or\n' +
4088
+ ' dist/validator_minified.js (built with build.py)\n' +
4089
+ ' for development.',
4090
+ 'https://cdn.ampproject.org/v0/validator_wasm.js')
4091
+ .option(
4092
+ '--user-agent <userAgent>', 'User agent string to use in requests.',
4093
+ DEFAULT_USER_AGENT)
4094
+ .option(
4095
+ '--html_format <AMP|AMP4ADS|AMP4EMAIL>',
4096
+ 'The input format to be validated.\n' +
4097
+ ' AMP by default.',
4098
+ 'AMP')
4099
+ .option(
4100
+ '--format <color|text|json>',
4101
+ 'How to format the output.\n' +
4102
+ ' "color" displays errors/warnings/success in\n' +
4103
+ ' red/orange/green.\n' +
4104
+ ' "text" avoids color (e.g., useful in terminals not\n' +
4105
+ ' supporting color).\n' +
4106
+ ' "json" emits json corresponding to the ValidationResult\n' +
4107
+ ' message in validator.proto.',
4108
+ 'color')
4109
+ .parse(process.argv);
4110
+ const opts = program.opts();
4111
+ if (opts.length === 0) {
4112
+ program.outputHelp();
4113
+ process.exit(1);
4114
+ }
4115
+ if (opts.html_format !== 'AMP' && opts.html_format !== 'AMP4ADS' &&
4116
+ opts.html_format !== 'AMP4EMAIL') {
4117
+ process.stderr.write(
4118
+ '--html_format must be set to "AMP", "AMP4ADS", or "AMP4EMAIL".\n',
4119
+ function() {
4120
+ process.exit(1);
4121
+ });
4122
+ }
4123
+ if (opts.format !== 'color' && opts.format !== 'text' &&
4124
+ opts.format !== 'json') {
4125
+ process.stderr.write(
4126
+ '--format must be set to "color", "text", or "json".\n', function() {
4127
+ process.exit(1);
4128
+ });
4129
+ }
4130
+ const inputs = [];
4131
+ for (let ii = 0; ii < program.args.length; ii++) {
4132
+ const item = program.args[ii];
4133
+ if (item === '-') {
4134
+ inputs.push(readFromStdin());
4135
+ } else if (isHttpOrHttpsUrl(item)) {
4136
+ inputs.push(readFromUrl(item, opts.userAgent));
4137
+ } else {
4138
+ inputs.push(readFromFile(item));
4139
+ }
4140
+ }
4141
+ getInstance(opts.validator_js, opts.userAgent)
4142
+ .then(function(validator) {
4143
+ Promise$1.all(inputs)
4144
+ .then(function(resolvedInputs) {
4145
+ const jsonOut = {};
4146
+ let hasError = false;
4147
+ for (let ii = 0; ii < resolvedInputs.length; ii++) {
4148
+ const validationResult = validator.validateString(
4149
+ resolvedInputs[ii], opts.html_format);
4150
+ if (opts.format === 'json') {
4151
+ jsonOut[program.args[ii]] = validationResult;
4152
+ } else {
4153
+ logValidationResult(
4154
+ program.args[ii], validationResult,
4155
+ opts.format === 'color' ? true : false);
4156
+ }
4157
+ if (validationResult.status !== 'PASS') {
4158
+ hasError = true;
4159
+ }
4160
+ }
4161
+ if (opts.format === 'json') {
4162
+ process.stdout.write(
4163
+ JSON.stringify(jsonOut) + '\n', function() {
4164
+ process.exit(hasError ? 1 : 0);
4165
+ });
4166
+ } else if (hasError) {
4167
+ process.stderr.write('', function() {
4168
+ process.exit(1);
4169
+ });
4170
+ } else {
4171
+ process.stdout.write('', function() {
4172
+ process.exit(0);
4173
+ });
4174
+ }
4175
+ })
4176
+ .catch(function(error) {
4177
+ process.stderr.write(
4178
+ (opts.format == 'color' ? colors.red(error.message) :
4179
+ error.message) +
4180
+ '\n',
4181
+ function() {
4182
+ process.exit(1);
4183
+ });
4184
+ });
4185
+ })
4186
+ .catch(function(error) {
4187
+ process.stderr.write(
4188
+ (opts.format == 'color' ? colors.red(error.message) :
4189
+ error.message) +
4190
+ '\n',
4191
+ function() {
4192
+ process.exit(1);
4193
+ });
4194
+ });
4195
+ }
4196
+
4197
+ var main_1 = amphtmlValidator.main = main;
4198
+
4199
+ var index = /*#__PURE__*/Object.freeze(/*#__PURE__*/_mergeNamespaces({
4200
+ __proto__: null,
4201
+ 'default': amphtmlValidator,
4202
+ getInstance: getInstance_1,
4203
+ newInstance: newInstance_1,
4204
+ main: main_1
4205
+ }, [amphtmlValidator]));
4206
+
4207
+ export { index as i };