@sveltejs/kit 1.0.0-next.21 → 1.0.0-next.210

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