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

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