UNPKG

2.31 MBJavaScriptView Raw
1'use strict';
2
3var fs$w = require('fs');
4var path$A = require('path');
5var require$$0$6 = require('os');
6var require$$0$5 = require('tty');
7var require$$0$8 = require('util');
8var require$$4$1 = require('net');
9var require$$0$c = require('events');
10var require$$0$b = require('url');
11var require$$0$d = require('http');
12var require$$0$7 = require('stream');
13var resolve$4 = require('resolve');
14var require$$0$a = require('module');
15var require$$1$4 = require('https');
16var require$$4$2 = require('tls');
17var require$$1$2 = require('crypto');
18var require$$0$9 = require('zlib');
19var require$$6 = require('assert');
20var require$$0$e = require('buffer');
21var qs = require('querystring');
22var require$$3$1 = require('repl');
23var require$$4 = require('vm');
24var require$$7 = require('console');
25var esbuild = require('esbuild');
26var require$$1$3 = require('worker_threads');
27var require$$1$5 = require('child_process');
28var readline = require('readline');
29
30function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e['default'] : e; }
31
32function _interopNamespace(e) {
33 if (e && e.__esModule) return e;
34 var n = Object.create(null);
35 if (e) {
36 Object.keys(e).forEach(function (k) {
37 n[k] = e[k];
38 });
39 }
40 n['default'] = e;
41 return n;
42}
43
44var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs$w);
45var fs__namespace = /*#__PURE__*/_interopNamespace(fs$w);
46var path__default = /*#__PURE__*/_interopDefaultLegacy(path$A);
47var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$6);
48var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0$5);
49var require$$0__default$3 = /*#__PURE__*/_interopDefaultLegacy(require$$0$8);
50var require$$4__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$4$1);
51var require$$0__default$6 = /*#__PURE__*/_interopDefaultLegacy(require$$0$c);
52var require$$0__default$7 = /*#__PURE__*/_interopDefaultLegacy(require$$0$b);
53var require$$0__default$8 = /*#__PURE__*/_interopDefaultLegacy(require$$0$d);
54var require$$0__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$0$7);
55var resolve__default = /*#__PURE__*/_interopDefaultLegacy(resolve$4);
56var require$$0__default$5 = /*#__PURE__*/_interopDefaultLegacy(require$$0$a);
57var require$$1__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$1$4);
58var require$$4__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$4$2);
59var require$$1__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$1$2);
60var require$$0__default$4 = /*#__PURE__*/_interopDefaultLegacy(require$$0$9);
61var require$$6__default = /*#__PURE__*/_interopDefaultLegacy(require$$6);
62var require$$0__default$9 = /*#__PURE__*/_interopDefaultLegacy(require$$0$e);
63var qs__namespace = /*#__PURE__*/_interopNamespace(qs);
64var qs__default = /*#__PURE__*/_interopDefaultLegacy(qs);
65var require$$3__default = /*#__PURE__*/_interopDefaultLegacy(require$$3$1);
66var require$$4__default = /*#__PURE__*/_interopDefaultLegacy(require$$4);
67var require$$7__default = /*#__PURE__*/_interopDefaultLegacy(require$$7);
68var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1$3);
69var require$$1__default$3 = /*#__PURE__*/_interopDefaultLegacy(require$$1$5);
70var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);
71
72var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
73
74function getDefaultExportFromCjs (x) {
75 return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
76}
77
78function getAugmentedNamespace(n) {
79 if (n.__esModule) return n;
80 var a = Object.defineProperty({}, '__esModule', {value: true});
81 Object.keys(n).forEach(function (k) {
82 var d = Object.getOwnPropertyDescriptor(n, k);
83 Object.defineProperty(a, k, d.get ? d : {
84 enumerable: true,
85 get: function () {
86 return n[k];
87 }
88 });
89 });
90 return a;
91}
92
93function commonjsRequire (path) {
94 throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
95}
96
97var ansiStyles$2 = {exports: {}};
98
99var colorName$1 = {
100 "aliceblue": [240, 248, 255],
101 "antiquewhite": [250, 235, 215],
102 "aqua": [0, 255, 255],
103 "aquamarine": [127, 255, 212],
104 "azure": [240, 255, 255],
105 "beige": [245, 245, 220],
106 "bisque": [255, 228, 196],
107 "black": [0, 0, 0],
108 "blanchedalmond": [255, 235, 205],
109 "blue": [0, 0, 255],
110 "blueviolet": [138, 43, 226],
111 "brown": [165, 42, 42],
112 "burlywood": [222, 184, 135],
113 "cadetblue": [95, 158, 160],
114 "chartreuse": [127, 255, 0],
115 "chocolate": [210, 105, 30],
116 "coral": [255, 127, 80],
117 "cornflowerblue": [100, 149, 237],
118 "cornsilk": [255, 248, 220],
119 "crimson": [220, 20, 60],
120 "cyan": [0, 255, 255],
121 "darkblue": [0, 0, 139],
122 "darkcyan": [0, 139, 139],
123 "darkgoldenrod": [184, 134, 11],
124 "darkgray": [169, 169, 169],
125 "darkgreen": [0, 100, 0],
126 "darkgrey": [169, 169, 169],
127 "darkkhaki": [189, 183, 107],
128 "darkmagenta": [139, 0, 139],
129 "darkolivegreen": [85, 107, 47],
130 "darkorange": [255, 140, 0],
131 "darkorchid": [153, 50, 204],
132 "darkred": [139, 0, 0],
133 "darksalmon": [233, 150, 122],
134 "darkseagreen": [143, 188, 143],
135 "darkslateblue": [72, 61, 139],
136 "darkslategray": [47, 79, 79],
137 "darkslategrey": [47, 79, 79],
138 "darkturquoise": [0, 206, 209],
139 "darkviolet": [148, 0, 211],
140 "deeppink": [255, 20, 147],
141 "deepskyblue": [0, 191, 255],
142 "dimgray": [105, 105, 105],
143 "dimgrey": [105, 105, 105],
144 "dodgerblue": [30, 144, 255],
145 "firebrick": [178, 34, 34],
146 "floralwhite": [255, 250, 240],
147 "forestgreen": [34, 139, 34],
148 "fuchsia": [255, 0, 255],
149 "gainsboro": [220, 220, 220],
150 "ghostwhite": [248, 248, 255],
151 "gold": [255, 215, 0],
152 "goldenrod": [218, 165, 32],
153 "gray": [128, 128, 128],
154 "green": [0, 128, 0],
155 "greenyellow": [173, 255, 47],
156 "grey": [128, 128, 128],
157 "honeydew": [240, 255, 240],
158 "hotpink": [255, 105, 180],
159 "indianred": [205, 92, 92],
160 "indigo": [75, 0, 130],
161 "ivory": [255, 255, 240],
162 "khaki": [240, 230, 140],
163 "lavender": [230, 230, 250],
164 "lavenderblush": [255, 240, 245],
165 "lawngreen": [124, 252, 0],
166 "lemonchiffon": [255, 250, 205],
167 "lightblue": [173, 216, 230],
168 "lightcoral": [240, 128, 128],
169 "lightcyan": [224, 255, 255],
170 "lightgoldenrodyellow": [250, 250, 210],
171 "lightgray": [211, 211, 211],
172 "lightgreen": [144, 238, 144],
173 "lightgrey": [211, 211, 211],
174 "lightpink": [255, 182, 193],
175 "lightsalmon": [255, 160, 122],
176 "lightseagreen": [32, 178, 170],
177 "lightskyblue": [135, 206, 250],
178 "lightslategray": [119, 136, 153],
179 "lightslategrey": [119, 136, 153],
180 "lightsteelblue": [176, 196, 222],
181 "lightyellow": [255, 255, 224],
182 "lime": [0, 255, 0],
183 "limegreen": [50, 205, 50],
184 "linen": [250, 240, 230],
185 "magenta": [255, 0, 255],
186 "maroon": [128, 0, 0],
187 "mediumaquamarine": [102, 205, 170],
188 "mediumblue": [0, 0, 205],
189 "mediumorchid": [186, 85, 211],
190 "mediumpurple": [147, 112, 219],
191 "mediumseagreen": [60, 179, 113],
192 "mediumslateblue": [123, 104, 238],
193 "mediumspringgreen": [0, 250, 154],
194 "mediumturquoise": [72, 209, 204],
195 "mediumvioletred": [199, 21, 133],
196 "midnightblue": [25, 25, 112],
197 "mintcream": [245, 255, 250],
198 "mistyrose": [255, 228, 225],
199 "moccasin": [255, 228, 181],
200 "navajowhite": [255, 222, 173],
201 "navy": [0, 0, 128],
202 "oldlace": [253, 245, 230],
203 "olive": [128, 128, 0],
204 "olivedrab": [107, 142, 35],
205 "orange": [255, 165, 0],
206 "orangered": [255, 69, 0],
207 "orchid": [218, 112, 214],
208 "palegoldenrod": [238, 232, 170],
209 "palegreen": [152, 251, 152],
210 "paleturquoise": [175, 238, 238],
211 "palevioletred": [219, 112, 147],
212 "papayawhip": [255, 239, 213],
213 "peachpuff": [255, 218, 185],
214 "peru": [205, 133, 63],
215 "pink": [255, 192, 203],
216 "plum": [221, 160, 221],
217 "powderblue": [176, 224, 230],
218 "purple": [128, 0, 128],
219 "rebeccapurple": [102, 51, 153],
220 "red": [255, 0, 0],
221 "rosybrown": [188, 143, 143],
222 "royalblue": [65, 105, 225],
223 "saddlebrown": [139, 69, 19],
224 "salmon": [250, 128, 114],
225 "sandybrown": [244, 164, 96],
226 "seagreen": [46, 139, 87],
227 "seashell": [255, 245, 238],
228 "sienna": [160, 82, 45],
229 "silver": [192, 192, 192],
230 "skyblue": [135, 206, 235],
231 "slateblue": [106, 90, 205],
232 "slategray": [112, 128, 144],
233 "slategrey": [112, 128, 144],
234 "snow": [255, 250, 250],
235 "springgreen": [0, 255, 127],
236 "steelblue": [70, 130, 180],
237 "tan": [210, 180, 140],
238 "teal": [0, 128, 128],
239 "thistle": [216, 191, 216],
240 "tomato": [255, 99, 71],
241 "turquoise": [64, 224, 208],
242 "violet": [238, 130, 238],
243 "wheat": [245, 222, 179],
244 "white": [255, 255, 255],
245 "whitesmoke": [245, 245, 245],
246 "yellow": [255, 255, 0],
247 "yellowgreen": [154, 205, 50]
248};
249
250/* MIT license */
251
252/* eslint-disable no-mixed-operators */
253const cssKeywords$1 = colorName$1;
254
255// NOTE: conversions should only return primitive values (i.e. arrays, or
256// values that give correct `typeof` results).
257// do not use box values types (i.e. Number(), String(), etc.)
258
259const reverseKeywords$1 = {};
260for (const key of Object.keys(cssKeywords$1)) {
261 reverseKeywords$1[cssKeywords$1[key]] = key;
262}
263
264const convert$3 = {
265 rgb: {channels: 3, labels: 'rgb'},
266 hsl: {channels: 3, labels: 'hsl'},
267 hsv: {channels: 3, labels: 'hsv'},
268 hwb: {channels: 3, labels: 'hwb'},
269 cmyk: {channels: 4, labels: 'cmyk'},
270 xyz: {channels: 3, labels: 'xyz'},
271 lab: {channels: 3, labels: 'lab'},
272 lch: {channels: 3, labels: 'lch'},
273 hex: {channels: 1, labels: ['hex']},
274 keyword: {channels: 1, labels: ['keyword']},
275 ansi16: {channels: 1, labels: ['ansi16']},
276 ansi256: {channels: 1, labels: ['ansi256']},
277 hcg: {channels: 3, labels: ['h', 'c', 'g']},
278 apple: {channels: 3, labels: ['r16', 'g16', 'b16']},
279 gray: {channels: 1, labels: ['gray']}
280};
281
282var conversions$5 = convert$3;
283
284// Hide .channels and .labels properties
285for (const model of Object.keys(convert$3)) {
286 if (!('channels' in convert$3[model])) {
287 throw new Error('missing channels property: ' + model);
288 }
289
290 if (!('labels' in convert$3[model])) {
291 throw new Error('missing channel labels property: ' + model);
292 }
293
294 if (convert$3[model].labels.length !== convert$3[model].channels) {
295 throw new Error('channel and label counts mismatch: ' + model);
296 }
297
298 const {channels, labels} = convert$3[model];
299 delete convert$3[model].channels;
300 delete convert$3[model].labels;
301 Object.defineProperty(convert$3[model], 'channels', {value: channels});
302 Object.defineProperty(convert$3[model], 'labels', {value: labels});
303}
304
305convert$3.rgb.hsl = function (rgb) {
306 const r = rgb[0] / 255;
307 const g = rgb[1] / 255;
308 const b = rgb[2] / 255;
309 const min = Math.min(r, g, b);
310 const max = Math.max(r, g, b);
311 const delta = max - min;
312 let h;
313 let s;
314
315 if (max === min) {
316 h = 0;
317 } else if (r === max) {
318 h = (g - b) / delta;
319 } else if (g === max) {
320 h = 2 + (b - r) / delta;
321 } else if (b === max) {
322 h = 4 + (r - g) / delta;
323 }
324
325 h = Math.min(h * 60, 360);
326
327 if (h < 0) {
328 h += 360;
329 }
330
331 const l = (min + max) / 2;
332
333 if (max === min) {
334 s = 0;
335 } else if (l <= 0.5) {
336 s = delta / (max + min);
337 } else {
338 s = delta / (2 - max - min);
339 }
340
341 return [h, s * 100, l * 100];
342};
343
344convert$3.rgb.hsv = function (rgb) {
345 let rdif;
346 let gdif;
347 let bdif;
348 let h;
349 let s;
350
351 const r = rgb[0] / 255;
352 const g = rgb[1] / 255;
353 const b = rgb[2] / 255;
354 const v = Math.max(r, g, b);
355 const diff = v - Math.min(r, g, b);
356 const diffc = function (c) {
357 return (v - c) / 6 / diff + 1 / 2;
358 };
359
360 if (diff === 0) {
361 h = 0;
362 s = 0;
363 } else {
364 s = diff / v;
365 rdif = diffc(r);
366 gdif = diffc(g);
367 bdif = diffc(b);
368
369 if (r === v) {
370 h = bdif - gdif;
371 } else if (g === v) {
372 h = (1 / 3) + rdif - bdif;
373 } else if (b === v) {
374 h = (2 / 3) + gdif - rdif;
375 }
376
377 if (h < 0) {
378 h += 1;
379 } else if (h > 1) {
380 h -= 1;
381 }
382 }
383
384 return [
385 h * 360,
386 s * 100,
387 v * 100
388 ];
389};
390
391convert$3.rgb.hwb = function (rgb) {
392 const r = rgb[0];
393 const g = rgb[1];
394 let b = rgb[2];
395 const h = convert$3.rgb.hsl(rgb)[0];
396 const w = 1 / 255 * Math.min(r, Math.min(g, b));
397
398 b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
399
400 return [h, w * 100, b * 100];
401};
402
403convert$3.rgb.cmyk = function (rgb) {
404 const r = rgb[0] / 255;
405 const g = rgb[1] / 255;
406 const b = rgb[2] / 255;
407
408 const k = Math.min(1 - r, 1 - g, 1 - b);
409 const c = (1 - r - k) / (1 - k) || 0;
410 const m = (1 - g - k) / (1 - k) || 0;
411 const y = (1 - b - k) / (1 - k) || 0;
412
413 return [c * 100, m * 100, y * 100, k * 100];
414};
415
416function comparativeDistance$1(x, y) {
417 /*
418 See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
419 */
420 return (
421 ((x[0] - y[0]) ** 2) +
422 ((x[1] - y[1]) ** 2) +
423 ((x[2] - y[2]) ** 2)
424 );
425}
426
427convert$3.rgb.keyword = function (rgb) {
428 const reversed = reverseKeywords$1[rgb];
429 if (reversed) {
430 return reversed;
431 }
432
433 let currentClosestDistance = Infinity;
434 let currentClosestKeyword;
435
436 for (const keyword of Object.keys(cssKeywords$1)) {
437 const value = cssKeywords$1[keyword];
438
439 // Compute comparative distance
440 const distance = comparativeDistance$1(rgb, value);
441
442 // Check if its less, if so set as closest
443 if (distance < currentClosestDistance) {
444 currentClosestDistance = distance;
445 currentClosestKeyword = keyword;
446 }
447 }
448
449 return currentClosestKeyword;
450};
451
452convert$3.keyword.rgb = function (keyword) {
453 return cssKeywords$1[keyword];
454};
455
456convert$3.rgb.xyz = function (rgb) {
457 let r = rgb[0] / 255;
458 let g = rgb[1] / 255;
459 let b = rgb[2] / 255;
460
461 // Assume sRGB
462 r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92);
463 g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92);
464 b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92);
465
466 const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
467 const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
468 const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
469
470 return [x * 100, y * 100, z * 100];
471};
472
473convert$3.rgb.lab = function (rgb) {
474 const xyz = convert$3.rgb.xyz(rgb);
475 let x = xyz[0];
476 let y = xyz[1];
477 let z = xyz[2];
478
479 x /= 95.047;
480 y /= 100;
481 z /= 108.883;
482
483 x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);
484 y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);
485 z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);
486
487 const l = (116 * y) - 16;
488 const a = 500 * (x - y);
489 const b = 200 * (y - z);
490
491 return [l, a, b];
492};
493
494convert$3.hsl.rgb = function (hsl) {
495 const h = hsl[0] / 360;
496 const s = hsl[1] / 100;
497 const l = hsl[2] / 100;
498 let t2;
499 let t3;
500 let val;
501
502 if (s === 0) {
503 val = l * 255;
504 return [val, val, val];
505 }
506
507 if (l < 0.5) {
508 t2 = l * (1 + s);
509 } else {
510 t2 = l + s - l * s;
511 }
512
513 const t1 = 2 * l - t2;
514
515 const rgb = [0, 0, 0];
516 for (let i = 0; i < 3; i++) {
517 t3 = h + 1 / 3 * -(i - 1);
518 if (t3 < 0) {
519 t3++;
520 }
521
522 if (t3 > 1) {
523 t3--;
524 }
525
526 if (6 * t3 < 1) {
527 val = t1 + (t2 - t1) * 6 * t3;
528 } else if (2 * t3 < 1) {
529 val = t2;
530 } else if (3 * t3 < 2) {
531 val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
532 } else {
533 val = t1;
534 }
535
536 rgb[i] = val * 255;
537 }
538
539 return rgb;
540};
541
542convert$3.hsl.hsv = function (hsl) {
543 const h = hsl[0];
544 let s = hsl[1] / 100;
545 let l = hsl[2] / 100;
546 let smin = s;
547 const lmin = Math.max(l, 0.01);
548
549 l *= 2;
550 s *= (l <= 1) ? l : 2 - l;
551 smin *= lmin <= 1 ? lmin : 2 - lmin;
552 const v = (l + s) / 2;
553 const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);
554
555 return [h, sv * 100, v * 100];
556};
557
558convert$3.hsv.rgb = function (hsv) {
559 const h = hsv[0] / 60;
560 const s = hsv[1] / 100;
561 let v = hsv[2] / 100;
562 const hi = Math.floor(h) % 6;
563
564 const f = h - Math.floor(h);
565 const p = 255 * v * (1 - s);
566 const q = 255 * v * (1 - (s * f));
567 const t = 255 * v * (1 - (s * (1 - f)));
568 v *= 255;
569
570 switch (hi) {
571 case 0:
572 return [v, t, p];
573 case 1:
574 return [q, v, p];
575 case 2:
576 return [p, v, t];
577 case 3:
578 return [p, q, v];
579 case 4:
580 return [t, p, v];
581 case 5:
582 return [v, p, q];
583 }
584};
585
586convert$3.hsv.hsl = function (hsv) {
587 const h = hsv[0];
588 const s = hsv[1] / 100;
589 const v = hsv[2] / 100;
590 const vmin = Math.max(v, 0.01);
591 let sl;
592 let l;
593
594 l = (2 - s) * v;
595 const lmin = (2 - s) * vmin;
596 sl = s * vmin;
597 sl /= (lmin <= 1) ? lmin : 2 - lmin;
598 sl = sl || 0;
599 l /= 2;
600
601 return [h, sl * 100, l * 100];
602};
603
604// http://dev.w3.org/csswg/css-color/#hwb-to-rgb
605convert$3.hwb.rgb = function (hwb) {
606 const h = hwb[0] / 360;
607 let wh = hwb[1] / 100;
608 let bl = hwb[2] / 100;
609 const ratio = wh + bl;
610 let f;
611
612 // Wh + bl cant be > 1
613 if (ratio > 1) {
614 wh /= ratio;
615 bl /= ratio;
616 }
617
618 const i = Math.floor(6 * h);
619 const v = 1 - bl;
620 f = 6 * h - i;
621
622 if ((i & 0x01) !== 0) {
623 f = 1 - f;
624 }
625
626 const n = wh + f * (v - wh); // Linear interpolation
627
628 let r;
629 let g;
630 let b;
631 /* eslint-disable max-statements-per-line,no-multi-spaces */
632 switch (i) {
633 default:
634 case 6:
635 case 0: r = v; g = n; b = wh; break;
636 case 1: r = n; g = v; b = wh; break;
637 case 2: r = wh; g = v; b = n; break;
638 case 3: r = wh; g = n; b = v; break;
639 case 4: r = n; g = wh; b = v; break;
640 case 5: r = v; g = wh; b = n; break;
641 }
642 /* eslint-enable max-statements-per-line,no-multi-spaces */
643
644 return [r * 255, g * 255, b * 255];
645};
646
647convert$3.cmyk.rgb = function (cmyk) {
648 const c = cmyk[0] / 100;
649 const m = cmyk[1] / 100;
650 const y = cmyk[2] / 100;
651 const k = cmyk[3] / 100;
652
653 const r = 1 - Math.min(1, c * (1 - k) + k);
654 const g = 1 - Math.min(1, m * (1 - k) + k);
655 const b = 1 - Math.min(1, y * (1 - k) + k);
656
657 return [r * 255, g * 255, b * 255];
658};
659
660convert$3.xyz.rgb = function (xyz) {
661 const x = xyz[0] / 100;
662 const y = xyz[1] / 100;
663 const z = xyz[2] / 100;
664 let r;
665 let g;
666 let b;
667
668 r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
669 g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
670 b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
671
672 // Assume sRGB
673 r = r > 0.0031308
674 ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055)
675 : r * 12.92;
676
677 g = g > 0.0031308
678 ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055)
679 : g * 12.92;
680
681 b = b > 0.0031308
682 ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055)
683 : b * 12.92;
684
685 r = Math.min(Math.max(0, r), 1);
686 g = Math.min(Math.max(0, g), 1);
687 b = Math.min(Math.max(0, b), 1);
688
689 return [r * 255, g * 255, b * 255];
690};
691
692convert$3.xyz.lab = function (xyz) {
693 let x = xyz[0];
694 let y = xyz[1];
695 let z = xyz[2];
696
697 x /= 95.047;
698 y /= 100;
699 z /= 108.883;
700
701 x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);
702 y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);
703 z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);
704
705 const l = (116 * y) - 16;
706 const a = 500 * (x - y);
707 const b = 200 * (y - z);
708
709 return [l, a, b];
710};
711
712convert$3.lab.xyz = function (lab) {
713 const l = lab[0];
714 const a = lab[1];
715 const b = lab[2];
716 let x;
717 let y;
718 let z;
719
720 y = (l + 16) / 116;
721 x = a / 500 + y;
722 z = y - b / 200;
723
724 const y2 = y ** 3;
725 const x2 = x ** 3;
726 const z2 = z ** 3;
727 y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
728 x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
729 z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
730
731 x *= 95.047;
732 y *= 100;
733 z *= 108.883;
734
735 return [x, y, z];
736};
737
738convert$3.lab.lch = function (lab) {
739 const l = lab[0];
740 const a = lab[1];
741 const b = lab[2];
742 let h;
743
744 const hr = Math.atan2(b, a);
745 h = hr * 360 / 2 / Math.PI;
746
747 if (h < 0) {
748 h += 360;
749 }
750
751 const c = Math.sqrt(a * a + b * b);
752
753 return [l, c, h];
754};
755
756convert$3.lch.lab = function (lch) {
757 const l = lch[0];
758 const c = lch[1];
759 const h = lch[2];
760
761 const hr = h / 360 * 2 * Math.PI;
762 const a = c * Math.cos(hr);
763 const b = c * Math.sin(hr);
764
765 return [l, a, b];
766};
767
768convert$3.rgb.ansi16 = function (args, saturation = null) {
769 const [r, g, b] = args;
770 let value = saturation === null ? convert$3.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization
771
772 value = Math.round(value / 50);
773
774 if (value === 0) {
775 return 30;
776 }
777
778 let ansi = 30
779 + ((Math.round(b / 255) << 2)
780 | (Math.round(g / 255) << 1)
781 | Math.round(r / 255));
782
783 if (value === 2) {
784 ansi += 60;
785 }
786
787 return ansi;
788};
789
790convert$3.hsv.ansi16 = function (args) {
791 // Optimization here; we already know the value and don't need to get
792 // it converted for us.
793 return convert$3.rgb.ansi16(convert$3.hsv.rgb(args), args[2]);
794};
795
796convert$3.rgb.ansi256 = function (args) {
797 const r = args[0];
798 const g = args[1];
799 const b = args[2];
800
801 // We use the extended greyscale palette here, with the exception of
802 // black and white. normal palette only has 4 greyscale shades.
803 if (r === g && g === b) {
804 if (r < 8) {
805 return 16;
806 }
807
808 if (r > 248) {
809 return 231;
810 }
811
812 return Math.round(((r - 8) / 247) * 24) + 232;
813 }
814
815 const ansi = 16
816 + (36 * Math.round(r / 255 * 5))
817 + (6 * Math.round(g / 255 * 5))
818 + Math.round(b / 255 * 5);
819
820 return ansi;
821};
822
823convert$3.ansi16.rgb = function (args) {
824 let color = args % 10;
825
826 // Handle greyscale
827 if (color === 0 || color === 7) {
828 if (args > 50) {
829 color += 3.5;
830 }
831
832 color = color / 10.5 * 255;
833
834 return [color, color, color];
835 }
836
837 const mult = (~~(args > 50) + 1) * 0.5;
838 const r = ((color & 1) * mult) * 255;
839 const g = (((color >> 1) & 1) * mult) * 255;
840 const b = (((color >> 2) & 1) * mult) * 255;
841
842 return [r, g, b];
843};
844
845convert$3.ansi256.rgb = function (args) {
846 // Handle greyscale
847 if (args >= 232) {
848 const c = (args - 232) * 10 + 8;
849 return [c, c, c];
850 }
851
852 args -= 16;
853
854 let rem;
855 const r = Math.floor(args / 36) / 5 * 255;
856 const g = Math.floor((rem = args % 36) / 6) / 5 * 255;
857 const b = (rem % 6) / 5 * 255;
858
859 return [r, g, b];
860};
861
862convert$3.rgb.hex = function (args) {
863 const integer = ((Math.round(args[0]) & 0xFF) << 16)
864 + ((Math.round(args[1]) & 0xFF) << 8)
865 + (Math.round(args[2]) & 0xFF);
866
867 const string = integer.toString(16).toUpperCase();
868 return '000000'.substring(string.length) + string;
869};
870
871convert$3.hex.rgb = function (args) {
872 const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
873 if (!match) {
874 return [0, 0, 0];
875 }
876
877 let colorString = match[0];
878
879 if (match[0].length === 3) {
880 colorString = colorString.split('').map(char => {
881 return char + char;
882 }).join('');
883 }
884
885 const integer = parseInt(colorString, 16);
886 const r = (integer >> 16) & 0xFF;
887 const g = (integer >> 8) & 0xFF;
888 const b = integer & 0xFF;
889
890 return [r, g, b];
891};
892
893convert$3.rgb.hcg = function (rgb) {
894 const r = rgb[0] / 255;
895 const g = rgb[1] / 255;
896 const b = rgb[2] / 255;
897 const max = Math.max(Math.max(r, g), b);
898 const min = Math.min(Math.min(r, g), b);
899 const chroma = (max - min);
900 let grayscale;
901 let hue;
902
903 if (chroma < 1) {
904 grayscale = min / (1 - chroma);
905 } else {
906 grayscale = 0;
907 }
908
909 if (chroma <= 0) {
910 hue = 0;
911 } else
912 if (max === r) {
913 hue = ((g - b) / chroma) % 6;
914 } else
915 if (max === g) {
916 hue = 2 + (b - r) / chroma;
917 } else {
918 hue = 4 + (r - g) / chroma;
919 }
920
921 hue /= 6;
922 hue %= 1;
923
924 return [hue * 360, chroma * 100, grayscale * 100];
925};
926
927convert$3.hsl.hcg = function (hsl) {
928 const s = hsl[1] / 100;
929 const l = hsl[2] / 100;
930
931 const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l));
932
933 let f = 0;
934 if (c < 1.0) {
935 f = (l - 0.5 * c) / (1.0 - c);
936 }
937
938 return [hsl[0], c * 100, f * 100];
939};
940
941convert$3.hsv.hcg = function (hsv) {
942 const s = hsv[1] / 100;
943 const v = hsv[2] / 100;
944
945 const c = s * v;
946 let f = 0;
947
948 if (c < 1.0) {
949 f = (v - c) / (1 - c);
950 }
951
952 return [hsv[0], c * 100, f * 100];
953};
954
955convert$3.hcg.rgb = function (hcg) {
956 const h = hcg[0] / 360;
957 const c = hcg[1] / 100;
958 const g = hcg[2] / 100;
959
960 if (c === 0.0) {
961 return [g * 255, g * 255, g * 255];
962 }
963
964 const pure = [0, 0, 0];
965 const hi = (h % 1) * 6;
966 const v = hi % 1;
967 const w = 1 - v;
968 let mg = 0;
969
970 /* eslint-disable max-statements-per-line */
971 switch (Math.floor(hi)) {
972 case 0:
973 pure[0] = 1; pure[1] = v; pure[2] = 0; break;
974 case 1:
975 pure[0] = w; pure[1] = 1; pure[2] = 0; break;
976 case 2:
977 pure[0] = 0; pure[1] = 1; pure[2] = v; break;
978 case 3:
979 pure[0] = 0; pure[1] = w; pure[2] = 1; break;
980 case 4:
981 pure[0] = v; pure[1] = 0; pure[2] = 1; break;
982 default:
983 pure[0] = 1; pure[1] = 0; pure[2] = w;
984 }
985 /* eslint-enable max-statements-per-line */
986
987 mg = (1.0 - c) * g;
988
989 return [
990 (c * pure[0] + mg) * 255,
991 (c * pure[1] + mg) * 255,
992 (c * pure[2] + mg) * 255
993 ];
994};
995
996convert$3.hcg.hsv = function (hcg) {
997 const c = hcg[1] / 100;
998 const g = hcg[2] / 100;
999
1000 const v = c + g * (1.0 - c);
1001 let f = 0;
1002
1003 if (v > 0.0) {
1004 f = c / v;
1005 }
1006
1007 return [hcg[0], f * 100, v * 100];
1008};
1009
1010convert$3.hcg.hsl = function (hcg) {
1011 const c = hcg[1] / 100;
1012 const g = hcg[2] / 100;
1013
1014 const l = g * (1.0 - c) + 0.5 * c;
1015 let s = 0;
1016
1017 if (l > 0.0 && l < 0.5) {
1018 s = c / (2 * l);
1019 } else
1020 if (l >= 0.5 && l < 1.0) {
1021 s = c / (2 * (1 - l));
1022 }
1023
1024 return [hcg[0], s * 100, l * 100];
1025};
1026
1027convert$3.hcg.hwb = function (hcg) {
1028 const c = hcg[1] / 100;
1029 const g = hcg[2] / 100;
1030 const v = c + g * (1.0 - c);
1031 return [hcg[0], (v - c) * 100, (1 - v) * 100];
1032};
1033
1034convert$3.hwb.hcg = function (hwb) {
1035 const w = hwb[1] / 100;
1036 const b = hwb[2] / 100;
1037 const v = 1 - b;
1038 const c = v - w;
1039 let g = 0;
1040
1041 if (c < 1) {
1042 g = (v - c) / (1 - c);
1043 }
1044
1045 return [hwb[0], c * 100, g * 100];
1046};
1047
1048convert$3.apple.rgb = function (apple) {
1049 return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];
1050};
1051
1052convert$3.rgb.apple = function (rgb) {
1053 return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];
1054};
1055
1056convert$3.gray.rgb = function (args) {
1057 return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
1058};
1059
1060convert$3.gray.hsl = function (args) {
1061 return [0, 0, args[0]];
1062};
1063
1064convert$3.gray.hsv = convert$3.gray.hsl;
1065
1066convert$3.gray.hwb = function (gray) {
1067 return [0, 100, gray[0]];
1068};
1069
1070convert$3.gray.cmyk = function (gray) {
1071 return [0, 0, 0, gray[0]];
1072};
1073
1074convert$3.gray.lab = function (gray) {
1075 return [gray[0], 0, 0];
1076};
1077
1078convert$3.gray.hex = function (gray) {
1079 const val = Math.round(gray[0] / 100 * 255) & 0xFF;
1080 const integer = (val << 16) + (val << 8) + val;
1081
1082 const string = integer.toString(16).toUpperCase();
1083 return '000000'.substring(string.length) + string;
1084};
1085
1086convert$3.rgb.gray = function (rgb) {
1087 const val = (rgb[0] + rgb[1] + rgb[2]) / 3;
1088 return [val / 255 * 100];
1089};
1090
1091const conversions$4 = conversions$5;
1092
1093/*
1094 This function routes a model to all other models.
1095
1096 all functions that are routed have a property `.conversion` attached
1097 to the returned synthetic function. This property is an array
1098 of strings, each with the steps in between the 'from' and 'to'
1099 color models (inclusive).
1100
1101 conversions that are not possible simply are not included.
1102*/
1103
1104function buildGraph$1() {
1105 const graph = {};
1106 // https://jsperf.com/object-keys-vs-for-in-with-closure/3
1107 const models = Object.keys(conversions$4);
1108
1109 for (let len = models.length, i = 0; i < len; i++) {
1110 graph[models[i]] = {
1111 // http://jsperf.com/1-vs-infinity
1112 // micro-opt, but this is simple.
1113 distance: -1,
1114 parent: null
1115 };
1116 }
1117
1118 return graph;
1119}
1120
1121// https://en.wikipedia.org/wiki/Breadth-first_search
1122function deriveBFS$1(fromModel) {
1123 const graph = buildGraph$1();
1124 const queue = [fromModel]; // Unshift -> queue -> pop
1125
1126 graph[fromModel].distance = 0;
1127
1128 while (queue.length) {
1129 const current = queue.pop();
1130 const adjacents = Object.keys(conversions$4[current]);
1131
1132 for (let len = adjacents.length, i = 0; i < len; i++) {
1133 const adjacent = adjacents[i];
1134 const node = graph[adjacent];
1135
1136 if (node.distance === -1) {
1137 node.distance = graph[current].distance + 1;
1138 node.parent = current;
1139 queue.unshift(adjacent);
1140 }
1141 }
1142 }
1143
1144 return graph;
1145}
1146
1147function link$1(from, to) {
1148 return function (args) {
1149 return to(from(args));
1150 };
1151}
1152
1153function wrapConversion$1(toModel, graph) {
1154 const path = [graph[toModel].parent, toModel];
1155 let fn = conversions$4[graph[toModel].parent][toModel];
1156
1157 let cur = graph[toModel].parent;
1158 while (graph[cur].parent) {
1159 path.unshift(graph[cur].parent);
1160 fn = link$1(conversions$4[graph[cur].parent][cur], fn);
1161 cur = graph[cur].parent;
1162 }
1163
1164 fn.conversion = path;
1165 return fn;
1166}
1167
1168var route$3 = function (fromModel) {
1169 const graph = deriveBFS$1(fromModel);
1170 const conversion = {};
1171
1172 const models = Object.keys(graph);
1173 for (let len = models.length, i = 0; i < len; i++) {
1174 const toModel = models[i];
1175 const node = graph[toModel];
1176
1177 if (node.parent === null) {
1178 // No possible conversion, or this node is the source model.
1179 continue;
1180 }
1181
1182 conversion[toModel] = wrapConversion$1(toModel, graph);
1183 }
1184
1185 return conversion;
1186};
1187
1188const conversions$3 = conversions$5;
1189const route$2 = route$3;
1190
1191const convert$2 = {};
1192
1193const models$1 = Object.keys(conversions$3);
1194
1195function wrapRaw$1(fn) {
1196 const wrappedFn = function (...args) {
1197 const arg0 = args[0];
1198 if (arg0 === undefined || arg0 === null) {
1199 return arg0;
1200 }
1201
1202 if (arg0.length > 1) {
1203 args = arg0;
1204 }
1205
1206 return fn(args);
1207 };
1208
1209 // Preserve .conversion property if there is one
1210 if ('conversion' in fn) {
1211 wrappedFn.conversion = fn.conversion;
1212 }
1213
1214 return wrappedFn;
1215}
1216
1217function wrapRounded$1(fn) {
1218 const wrappedFn = function (...args) {
1219 const arg0 = args[0];
1220
1221 if (arg0 === undefined || arg0 === null) {
1222 return arg0;
1223 }
1224
1225 if (arg0.length > 1) {
1226 args = arg0;
1227 }
1228
1229 const result = fn(args);
1230
1231 // We're assuming the result is an array here.
1232 // see notice in conversions.js; don't use box types
1233 // in conversion functions.
1234 if (typeof result === 'object') {
1235 for (let len = result.length, i = 0; i < len; i++) {
1236 result[i] = Math.round(result[i]);
1237 }
1238 }
1239
1240 return result;
1241 };
1242
1243 // Preserve .conversion property if there is one
1244 if ('conversion' in fn) {
1245 wrappedFn.conversion = fn.conversion;
1246 }
1247
1248 return wrappedFn;
1249}
1250
1251models$1.forEach(fromModel => {
1252 convert$2[fromModel] = {};
1253
1254 Object.defineProperty(convert$2[fromModel], 'channels', {value: conversions$3[fromModel].channels});
1255 Object.defineProperty(convert$2[fromModel], 'labels', {value: conversions$3[fromModel].labels});
1256
1257 const routes = route$2(fromModel);
1258 const routeModels = Object.keys(routes);
1259
1260 routeModels.forEach(toModel => {
1261 const fn = routes[toModel];
1262
1263 convert$2[fromModel][toModel] = wrapRounded$1(fn);
1264 convert$2[fromModel][toModel].raw = wrapRaw$1(fn);
1265 });
1266});
1267
1268var colorConvert$1 = convert$2;
1269
1270(function (module) {
1271
1272const wrapAnsi16 = (fn, offset) => (...args) => {
1273 const code = fn(...args);
1274 return `\u001B[${code + offset}m`;
1275};
1276
1277const wrapAnsi256 = (fn, offset) => (...args) => {
1278 const code = fn(...args);
1279 return `\u001B[${38 + offset};5;${code}m`;
1280};
1281
1282const wrapAnsi16m = (fn, offset) => (...args) => {
1283 const rgb = fn(...args);
1284 return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
1285};
1286
1287const ansi2ansi = n => n;
1288const rgb2rgb = (r, g, b) => [r, g, b];
1289
1290const setLazyProperty = (object, property, get) => {
1291 Object.defineProperty(object, property, {
1292 get: () => {
1293 const value = get();
1294
1295 Object.defineProperty(object, property, {
1296 value,
1297 enumerable: true,
1298 configurable: true
1299 });
1300
1301 return value;
1302 },
1303 enumerable: true,
1304 configurable: true
1305 });
1306};
1307
1308/** @type {typeof import('color-convert')} */
1309let colorConvert;
1310const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => {
1311 if (colorConvert === undefined) {
1312 colorConvert = colorConvert$1;
1313 }
1314
1315 const offset = isBackground ? 10 : 0;
1316 const styles = {};
1317
1318 for (const [sourceSpace, suite] of Object.entries(colorConvert)) {
1319 const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace;
1320 if (sourceSpace === targetSpace) {
1321 styles[name] = wrap(identity, offset);
1322 } else if (typeof suite === 'object') {
1323 styles[name] = wrap(suite[targetSpace], offset);
1324 }
1325 }
1326
1327 return styles;
1328};
1329
1330function assembleStyles() {
1331 const codes = new Map();
1332 const styles = {
1333 modifier: {
1334 reset: [0, 0],
1335 // 21 isn't widely supported and 22 does the same thing
1336 bold: [1, 22],
1337 dim: [2, 22],
1338 italic: [3, 23],
1339 underline: [4, 24],
1340 inverse: [7, 27],
1341 hidden: [8, 28],
1342 strikethrough: [9, 29]
1343 },
1344 color: {
1345 black: [30, 39],
1346 red: [31, 39],
1347 green: [32, 39],
1348 yellow: [33, 39],
1349 blue: [34, 39],
1350 magenta: [35, 39],
1351 cyan: [36, 39],
1352 white: [37, 39],
1353
1354 // Bright color
1355 blackBright: [90, 39],
1356 redBright: [91, 39],
1357 greenBright: [92, 39],
1358 yellowBright: [93, 39],
1359 blueBright: [94, 39],
1360 magentaBright: [95, 39],
1361 cyanBright: [96, 39],
1362 whiteBright: [97, 39]
1363 },
1364 bgColor: {
1365 bgBlack: [40, 49],
1366 bgRed: [41, 49],
1367 bgGreen: [42, 49],
1368 bgYellow: [43, 49],
1369 bgBlue: [44, 49],
1370 bgMagenta: [45, 49],
1371 bgCyan: [46, 49],
1372 bgWhite: [47, 49],
1373
1374 // Bright color
1375 bgBlackBright: [100, 49],
1376 bgRedBright: [101, 49],
1377 bgGreenBright: [102, 49],
1378 bgYellowBright: [103, 49],
1379 bgBlueBright: [104, 49],
1380 bgMagentaBright: [105, 49],
1381 bgCyanBright: [106, 49],
1382 bgWhiteBright: [107, 49]
1383 }
1384 };
1385
1386 // Alias bright black as gray (and grey)
1387 styles.color.gray = styles.color.blackBright;
1388 styles.bgColor.bgGray = styles.bgColor.bgBlackBright;
1389 styles.color.grey = styles.color.blackBright;
1390 styles.bgColor.bgGrey = styles.bgColor.bgBlackBright;
1391
1392 for (const [groupName, group] of Object.entries(styles)) {
1393 for (const [styleName, style] of Object.entries(group)) {
1394 styles[styleName] = {
1395 open: `\u001B[${style[0]}m`,
1396 close: `\u001B[${style[1]}m`
1397 };
1398
1399 group[styleName] = styles[styleName];
1400
1401 codes.set(style[0], style[1]);
1402 }
1403
1404 Object.defineProperty(styles, groupName, {
1405 value: group,
1406 enumerable: false
1407 });
1408 }
1409
1410 Object.defineProperty(styles, 'codes', {
1411 value: codes,
1412 enumerable: false
1413 });
1414
1415 styles.color.close = '\u001B[39m';
1416 styles.bgColor.close = '\u001B[49m';
1417
1418 setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false));
1419 setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false));
1420 setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false));
1421 setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true));
1422 setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true));
1423 setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true));
1424
1425 return styles;
1426}
1427
1428// Make the export immutable
1429Object.defineProperty(module, 'exports', {
1430 enumerable: true,
1431 get: assembleStyles
1432});
1433}(ansiStyles$2));
1434
1435var hasFlag$3 = (flag, argv = process.argv) => {
1436 const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');
1437 const position = argv.indexOf(prefix + flag);
1438 const terminatorPosition = argv.indexOf('--');
1439 return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
1440};
1441
1442const os$5 = require$$0__default$1;
1443const tty = require$$0__default;
1444const hasFlag$2 = hasFlag$3;
1445
1446const {env: env$2} = process;
1447
1448let forceColor$1;
1449if (hasFlag$2('no-color') ||
1450 hasFlag$2('no-colors') ||
1451 hasFlag$2('color=false') ||
1452 hasFlag$2('color=never')) {
1453 forceColor$1 = 0;
1454} else if (hasFlag$2('color') ||
1455 hasFlag$2('colors') ||
1456 hasFlag$2('color=true') ||
1457 hasFlag$2('color=always')) {
1458 forceColor$1 = 1;
1459}
1460
1461if ('FORCE_COLOR' in env$2) {
1462 if (env$2.FORCE_COLOR === 'true') {
1463 forceColor$1 = 1;
1464 } else if (env$2.FORCE_COLOR === 'false') {
1465 forceColor$1 = 0;
1466 } else {
1467 forceColor$1 = env$2.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$2.FORCE_COLOR, 10), 3);
1468 }
1469}
1470
1471function translateLevel$1(level) {
1472 if (level === 0) {
1473 return false;
1474 }
1475
1476 return {
1477 level,
1478 hasBasic: true,
1479 has256: level >= 2,
1480 has16m: level >= 3
1481 };
1482}
1483
1484function supportsColor$1(haveStream, streamIsTTY) {
1485 if (forceColor$1 === 0) {
1486 return 0;
1487 }
1488
1489 if (hasFlag$2('color=16m') ||
1490 hasFlag$2('color=full') ||
1491 hasFlag$2('color=truecolor')) {
1492 return 3;
1493 }
1494
1495 if (hasFlag$2('color=256')) {
1496 return 2;
1497 }
1498
1499 if (haveStream && !streamIsTTY && forceColor$1 === undefined) {
1500 return 0;
1501 }
1502
1503 const min = forceColor$1 || 0;
1504
1505 if (env$2.TERM === 'dumb') {
1506 return min;
1507 }
1508
1509 if (process.platform === 'win32') {
1510 // Windows 10 build 10586 is the first Windows release that supports 256 colors.
1511 // Windows 10 build 14931 is the first release that supports 16m/TrueColor.
1512 const osRelease = os$5.release().split('.');
1513 if (
1514 Number(osRelease[0]) >= 10 &&
1515 Number(osRelease[2]) >= 10586
1516 ) {
1517 return Number(osRelease[2]) >= 14931 ? 3 : 2;
1518 }
1519
1520 return 1;
1521 }
1522
1523 if ('CI' in env$2) {
1524 if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env$2) || env$2.CI_NAME === 'codeship') {
1525 return 1;
1526 }
1527
1528 return min;
1529 }
1530
1531 if ('TEAMCITY_VERSION' in env$2) {
1532 return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$2.TEAMCITY_VERSION) ? 1 : 0;
1533 }
1534
1535 if (env$2.COLORTERM === 'truecolor') {
1536 return 3;
1537 }
1538
1539 if ('TERM_PROGRAM' in env$2) {
1540 const version = parseInt((env$2.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
1541
1542 switch (env$2.TERM_PROGRAM) {
1543 case 'iTerm.app':
1544 return version >= 3 ? 3 : 2;
1545 case 'Apple_Terminal':
1546 return 2;
1547 // No default
1548 }
1549 }
1550
1551 if (/-256(color)?$/i.test(env$2.TERM)) {
1552 return 2;
1553 }
1554
1555 if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$2.TERM)) {
1556 return 1;
1557 }
1558
1559 if ('COLORTERM' in env$2) {
1560 return 1;
1561 }
1562
1563 return min;
1564}
1565
1566function getSupportLevel$1(stream) {
1567 const level = supportsColor$1(stream, stream && stream.isTTY);
1568 return translateLevel$1(level);
1569}
1570
1571var supportsColor_1$1 = {
1572 supportsColor: getSupportLevel$1,
1573 stdout: translateLevel$1(supportsColor$1(true, tty.isatty(1))),
1574 stderr: translateLevel$1(supportsColor$1(true, tty.isatty(2)))
1575};
1576
1577const stringReplaceAll$1 = (string, substring, replacer) => {
1578 let index = string.indexOf(substring);
1579 if (index === -1) {
1580 return string;
1581 }
1582
1583 const substringLength = substring.length;
1584 let endIndex = 0;
1585 let returnValue = '';
1586 do {
1587 returnValue += string.substr(endIndex, index - endIndex) + substring + replacer;
1588 endIndex = index + substringLength;
1589 index = string.indexOf(substring, endIndex);
1590 } while (index !== -1);
1591
1592 returnValue += string.substr(endIndex);
1593 return returnValue;
1594};
1595
1596const stringEncaseCRLFWithFirstIndex$1 = (string, prefix, postfix, index) => {
1597 let endIndex = 0;
1598 let returnValue = '';
1599 do {
1600 const gotCR = string[index - 1] === '\r';
1601 returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
1602 endIndex = index + 1;
1603 index = string.indexOf('\n', endIndex);
1604 } while (index !== -1);
1605
1606 returnValue += string.substr(endIndex);
1607 return returnValue;
1608};
1609
1610var util$a = {
1611 stringReplaceAll: stringReplaceAll$1,
1612 stringEncaseCRLFWithFirstIndex: stringEncaseCRLFWithFirstIndex$1
1613};
1614
1615const TEMPLATE_REGEX$1 = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
1616const STYLE_REGEX$1 = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
1617const STRING_REGEX$1 = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
1618const ESCAPE_REGEX$1 = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi;
1619
1620const ESCAPES$1 = new Map([
1621 ['n', '\n'],
1622 ['r', '\r'],
1623 ['t', '\t'],
1624 ['b', '\b'],
1625 ['f', '\f'],
1626 ['v', '\v'],
1627 ['0', '\0'],
1628 ['\\', '\\'],
1629 ['e', '\u001B'],
1630 ['a', '\u0007']
1631]);
1632
1633function unescape$2(c) {
1634 const u = c[0] === 'u';
1635 const bracket = c[1] === '{';
1636
1637 if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) {
1638 return String.fromCharCode(parseInt(c.slice(1), 16));
1639 }
1640
1641 if (u && bracket) {
1642 return String.fromCodePoint(parseInt(c.slice(2, -1), 16));
1643 }
1644
1645 return ESCAPES$1.get(c) || c;
1646}
1647
1648function parseArguments$1(name, arguments_) {
1649 const results = [];
1650 const chunks = arguments_.trim().split(/\s*,\s*/g);
1651 let matches;
1652
1653 for (const chunk of chunks) {
1654 const number = Number(chunk);
1655 if (!Number.isNaN(number)) {
1656 results.push(number);
1657 } else if ((matches = chunk.match(STRING_REGEX$1))) {
1658 results.push(matches[2].replace(ESCAPE_REGEX$1, (m, escape, character) => escape ? unescape$2(escape) : character));
1659 } else {
1660 throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
1661 }
1662 }
1663
1664 return results;
1665}
1666
1667function parseStyle$1(style) {
1668 STYLE_REGEX$1.lastIndex = 0;
1669
1670 const results = [];
1671 let matches;
1672
1673 while ((matches = STYLE_REGEX$1.exec(style)) !== null) {
1674 const name = matches[1];
1675
1676 if (matches[2]) {
1677 const args = parseArguments$1(name, matches[2]);
1678 results.push([name].concat(args));
1679 } else {
1680 results.push([name]);
1681 }
1682 }
1683
1684 return results;
1685}
1686
1687function buildStyle$1(chalk, styles) {
1688 const enabled = {};
1689
1690 for (const layer of styles) {
1691 for (const style of layer.styles) {
1692 enabled[style[0]] = layer.inverse ? null : style.slice(1);
1693 }
1694 }
1695
1696 let current = chalk;
1697 for (const [styleName, styles] of Object.entries(enabled)) {
1698 if (!Array.isArray(styles)) {
1699 continue;
1700 }
1701
1702 if (!(styleName in current)) {
1703 throw new Error(`Unknown Chalk style: ${styleName}`);
1704 }
1705
1706 current = styles.length > 0 ? current[styleName](...styles) : current[styleName];
1707 }
1708
1709 return current;
1710}
1711
1712var templates$1 = (chalk, temporary) => {
1713 const styles = [];
1714 const chunks = [];
1715 let chunk = [];
1716
1717 // eslint-disable-next-line max-params
1718 temporary.replace(TEMPLATE_REGEX$1, (m, escapeCharacter, inverse, style, close, character) => {
1719 if (escapeCharacter) {
1720 chunk.push(unescape$2(escapeCharacter));
1721 } else if (style) {
1722 const string = chunk.join('');
1723 chunk = [];
1724 chunks.push(styles.length === 0 ? string : buildStyle$1(chalk, styles)(string));
1725 styles.push({inverse, styles: parseStyle$1(style)});
1726 } else if (close) {
1727 if (styles.length === 0) {
1728 throw new Error('Found extraneous } in Chalk template literal');
1729 }
1730
1731 chunks.push(buildStyle$1(chalk, styles)(chunk.join('')));
1732 chunk = [];
1733 styles.pop();
1734 } else {
1735 chunk.push(character);
1736 }
1737 });
1738
1739 chunks.push(chunk.join(''));
1740
1741 if (styles.length > 0) {
1742 const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
1743 throw new Error(errMessage);
1744 }
1745
1746 return chunks.join('');
1747};
1748
1749const ansiStyles$1 = ansiStyles$2.exports;
1750const {stdout: stdoutColor, stderr: stderrColor} = supportsColor_1$1;
1751const {
1752 stringReplaceAll,
1753 stringEncaseCRLFWithFirstIndex
1754} = util$a;
1755
1756const {isArray: isArray$4} = Array;
1757
1758// `supportsColor.level` → `ansiStyles.color[name]` mapping
1759const levelMapping = [
1760 'ansi',
1761 'ansi',
1762 'ansi256',
1763 'ansi16m'
1764];
1765
1766const styles = Object.create(null);
1767
1768const applyOptions = (object, options = {}) => {
1769 if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
1770 throw new Error('The `level` option should be an integer from 0 to 3');
1771 }
1772
1773 // Detect level if not set manually
1774 const colorLevel = stdoutColor ? stdoutColor.level : 0;
1775 object.level = options.level === undefined ? colorLevel : options.level;
1776};
1777
1778class ChalkClass {
1779 constructor(options) {
1780 // eslint-disable-next-line no-constructor-return
1781 return chalkFactory(options);
1782 }
1783}
1784
1785const chalkFactory = options => {
1786 const chalk = {};
1787 applyOptions(chalk, options);
1788
1789 chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_);
1790
1791 Object.setPrototypeOf(chalk, Chalk.prototype);
1792 Object.setPrototypeOf(chalk.template, chalk);
1793
1794 chalk.template.constructor = () => {
1795 throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.');
1796 };
1797
1798 chalk.template.Instance = ChalkClass;
1799
1800 return chalk.template;
1801};
1802
1803function Chalk(options) {
1804 return chalkFactory(options);
1805}
1806
1807for (const [styleName, style] of Object.entries(ansiStyles$1)) {
1808 styles[styleName] = {
1809 get() {
1810 const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty);
1811 Object.defineProperty(this, styleName, {value: builder});
1812 return builder;
1813 }
1814 };
1815}
1816
1817styles.visible = {
1818 get() {
1819 const builder = createBuilder(this, this._styler, true);
1820 Object.defineProperty(this, 'visible', {value: builder});
1821 return builder;
1822 }
1823};
1824
1825const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256'];
1826
1827for (const model of usedModels) {
1828 styles[model] = {
1829 get() {
1830 const {level} = this;
1831 return function (...arguments_) {
1832 const styler = createStyler(ansiStyles$1.color[levelMapping[level]][model](...arguments_), ansiStyles$1.color.close, this._styler);
1833 return createBuilder(this, styler, this._isEmpty);
1834 };
1835 }
1836 };
1837}
1838
1839for (const model of usedModels) {
1840 const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
1841 styles[bgModel] = {
1842 get() {
1843 const {level} = this;
1844 return function (...arguments_) {
1845 const styler = createStyler(ansiStyles$1.bgColor[levelMapping[level]][model](...arguments_), ansiStyles$1.bgColor.close, this._styler);
1846 return createBuilder(this, styler, this._isEmpty);
1847 };
1848 }
1849 };
1850}
1851
1852const proto$1 = Object.defineProperties(() => {}, {
1853 ...styles,
1854 level: {
1855 enumerable: true,
1856 get() {
1857 return this._generator.level;
1858 },
1859 set(level) {
1860 this._generator.level = level;
1861 }
1862 }
1863});
1864
1865const createStyler = (open, close, parent) => {
1866 let openAll;
1867 let closeAll;
1868 if (parent === undefined) {
1869 openAll = open;
1870 closeAll = close;
1871 } else {
1872 openAll = parent.openAll + open;
1873 closeAll = close + parent.closeAll;
1874 }
1875
1876 return {
1877 open,
1878 close,
1879 openAll,
1880 closeAll,
1881 parent
1882 };
1883};
1884
1885const createBuilder = (self, _styler, _isEmpty) => {
1886 const builder = (...arguments_) => {
1887 if (isArray$4(arguments_[0]) && isArray$4(arguments_[0].raw)) {
1888 // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}`
1889 return applyStyle(builder, chalkTag(builder, ...arguments_));
1890 }
1891
1892 // Single argument is hot path, implicit coercion is faster than anything
1893 // eslint-disable-next-line no-implicit-coercion
1894 return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' '));
1895 };
1896
1897 // We alter the prototype because we must return a function, but there is
1898 // no way to create a function with a different prototype
1899 Object.setPrototypeOf(builder, proto$1);
1900
1901 builder._generator = self;
1902 builder._styler = _styler;
1903 builder._isEmpty = _isEmpty;
1904
1905 return builder;
1906};
1907
1908const applyStyle = (self, string) => {
1909 if (self.level <= 0 || !string) {
1910 return self._isEmpty ? '' : string;
1911 }
1912
1913 let styler = self._styler;
1914
1915 if (styler === undefined) {
1916 return string;
1917 }
1918
1919 const {openAll, closeAll} = styler;
1920 if (string.indexOf('\u001B') !== -1) {
1921 while (styler !== undefined) {
1922 // Replace any instances already present with a re-opening code
1923 // otherwise only the part of the string until said closing code
1924 // will be colored, and the rest will simply be 'plain'.
1925 string = stringReplaceAll(string, styler.close, styler.open);
1926
1927 styler = styler.parent;
1928 }
1929 }
1930
1931 // We can move both next actions out of loop, because remaining actions in loop won't have
1932 // any/visible effect on parts we add here. Close the styling before a linebreak and reopen
1933 // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92
1934 const lfIndex = string.indexOf('\n');
1935 if (lfIndex !== -1) {
1936 string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
1937 }
1938
1939 return openAll + string + closeAll;
1940};
1941
1942let template;
1943const chalkTag = (chalk, ...strings) => {
1944 const [firstString] = strings;
1945
1946 if (!isArray$4(firstString) || !isArray$4(firstString.raw)) {
1947 // If chalk() was called by itself or with a string,
1948 // return the string itself as a string.
1949 return strings.join(' ');
1950 }
1951
1952 const arguments_ = strings.slice(1);
1953 const parts = [firstString.raw[0]];
1954
1955 for (let i = 1; i < firstString.length; i++) {
1956 parts.push(
1957 String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'),
1958 String(firstString.raw[i])
1959 );
1960 }
1961
1962 if (template === undefined) {
1963 template = templates$1;
1964 }
1965
1966 return template(chalk, parts.join(''));
1967};
1968
1969Object.defineProperties(Chalk.prototype, styles);
1970
1971const chalk$2 = Chalk(); // eslint-disable-line new-cap
1972chalk$2.supportsColor = stdoutColor;
1973chalk$2.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap
1974chalk$2.stderr.supportsColor = stderrColor;
1975
1976var source = chalk$2;
1977
1978var dist$4 = {};
1979
1980var Stream$1 = require$$0__default$2;
1981var writeMethods = ["write", "end", "destroy"];
1982var readMethods = ["resume", "pause"];
1983var readEvents = ["data", "close"];
1984var slice$2 = Array.prototype.slice;
1985
1986var duplexer$1 = duplex;
1987
1988function forEach (arr, fn) {
1989 if (arr.forEach) {
1990 return arr.forEach(fn)
1991 }
1992
1993 for (var i = 0; i < arr.length; i++) {
1994 fn(arr[i], i);
1995 }
1996}
1997
1998function duplex(writer, reader) {
1999 var stream = new Stream$1();
2000 var ended = false;
2001
2002 forEach(writeMethods, proxyWriter);
2003
2004 forEach(readMethods, proxyReader);
2005
2006 forEach(readEvents, proxyStream);
2007
2008 reader.on("end", handleEnd);
2009
2010 writer.on("drain", function() {
2011 stream.emit("drain");
2012 });
2013
2014 writer.on("error", reemit);
2015 reader.on("error", reemit);
2016
2017 stream.writable = writer.writable;
2018 stream.readable = reader.readable;
2019
2020 return stream
2021
2022 function proxyWriter(methodName) {
2023 stream[methodName] = method;
2024
2025 function method() {
2026 return writer[methodName].apply(writer, arguments)
2027 }
2028 }
2029
2030 function proxyReader(methodName) {
2031 stream[methodName] = method;
2032
2033 function method() {
2034 stream.emit(methodName);
2035 var func = reader[methodName];
2036 if (func) {
2037 return func.apply(reader, arguments)
2038 }
2039 reader.emit(methodName);
2040 }
2041 }
2042
2043 function proxyStream(methodName) {
2044 reader.on(methodName, reemit);
2045
2046 function reemit() {
2047 var args = slice$2.call(arguments);
2048 args.unshift(methodName);
2049 stream.emit.apply(stream, args);
2050 }
2051 }
2052
2053 function handleEnd() {
2054 if (ended) {
2055 return
2056 }
2057 ended = true;
2058 var args = slice$2.call(arguments);
2059 args.unshift("end");
2060 stream.emit.apply(stream, args);
2061 }
2062
2063 function reemit(err) {
2064 stream.emit("error", err);
2065 }
2066}
2067
2068Object.defineProperty(dist$4, "__esModule", { value: true });
2069const zlib_1 = require$$0__default$4;
2070const stream_1$a = require$$0__default$2;
2071const fs_1 = fs__default;
2072const util_1$1 = require$$0__default$3;
2073const duplexer = duplexer$1;
2074const readFilePromise = util_1$1.promisify(fs_1.readFile);
2075const bufferFormatter = (incoming) => typeof incoming === 'string' ? Buffer.from(incoming, 'utf8') : incoming;
2076const optionFormatter = (passed, toEncode) => ({
2077 params: {
2078 [zlib_1.constants.BROTLI_PARAM_MODE]: passed && 'mode' in passed && passed.mode || zlib_1.constants.BROTLI_DEFAULT_MODE,
2079 [zlib_1.constants.BROTLI_PARAM_QUALITY]: passed && 'quality' in passed && passed.quality || zlib_1.constants.BROTLI_MAX_QUALITY,
2080 [zlib_1.constants.BROTLI_PARAM_SIZE_HINT]: toEncode ? toEncode.byteLength : 0,
2081 }
2082});
2083/**
2084 * @param incoming Either a Buffer or string of the value to encode.
2085 * @param options Subset of Encoding Parameters.
2086 * @return Promise that resolves with the encoded Buffer length.
2087 */
2088async function size(incoming, options) {
2089 const buffer = bufferFormatter(incoming);
2090 return new Promise(function (resolve, reject) {
2091 zlib_1.brotliCompress(buffer, optionFormatter(options, buffer), (error, result) => {
2092 if (error !== null) {
2093 reject(error);
2094 }
2095 resolve(result.byteLength);
2096 });
2097 });
2098}
2099var _default = dist$4.default = size;
2100/**
2101 * @param incoming Either a Buffer or string of the value to encode.
2102 * @param options Subset of Encoding Parameters.
2103 * @return Length of encoded Buffer.
2104 */
2105function sync$e(incoming, options) {
2106 const buffer = bufferFormatter(incoming);
2107 return zlib_1.brotliCompressSync(buffer, optionFormatter(options, buffer)).byteLength;
2108}
2109dist$4.sync = sync$e;
2110/**
2111 * @param options
2112 * @return PassThroughStream for the contents being compressed
2113 */
2114function stream$c(options) {
2115 const input = new stream_1$a.PassThrough();
2116 const output = new stream_1$a.PassThrough();
2117 const wrapper = duplexer(input, output);
2118 let size = 0;
2119 const brotli = zlib_1.createBrotliCompress(optionFormatter(options))
2120 .on('data', buf => {
2121 size += buf.length;
2122 })
2123 .on('error', () => {
2124 wrapper.brotliSize = 0;
2125 })
2126 .on('end', () => {
2127 wrapper.brotliSize = size;
2128 wrapper.emit('brotli-size', size);
2129 output.end();
2130 });
2131 input.pipe(brotli);
2132 input.pipe(output, { end: false });
2133 return wrapper;
2134}
2135dist$4.stream = stream$c;
2136/**
2137 * @param path File Path for the file to compress.
2138 * @param options Subset of Encoding Parameters.
2139 * @return Promise that resolves with size of encoded file.
2140 */
2141async function file(path, options) {
2142 const file = await readFilePromise(path);
2143 return (await size(file, options));
2144}
2145dist$4.file = file;
2146/**
2147 * @param path File Path for the file to compress.
2148 * @param options Subset of Encoding Parameters.
2149 * @return size of encoded file.
2150 */
2151function fileSync(path, options) {
2152 const file = fs_1.readFileSync(path);
2153 return sync$e(file, options);
2154}
2155dist$4.fileSync = fileSync;
2156
2157var src$4 = {exports: {}};
2158
2159var browser$3 = {exports: {}};
2160
2161/**
2162 * Helpers.
2163 */
2164
2165var s$2 = 1000;
2166var m$2 = s$2 * 60;
2167var h$2 = m$2 * 60;
2168var d$2 = h$2 * 24;
2169var w$1 = d$2 * 7;
2170var y$2 = d$2 * 365.25;
2171
2172/**
2173 * Parse or format the given `val`.
2174 *
2175 * Options:
2176 *
2177 * - `long` verbose formatting [false]
2178 *
2179 * @param {String|Number} val
2180 * @param {Object} [options]
2181 * @throws {Error} throw an error if val is not a non-empty string or a number
2182 * @return {String|Number}
2183 * @api public
2184 */
2185
2186var ms$2 = function(val, options) {
2187 options = options || {};
2188 var type = typeof val;
2189 if (type === 'string' && val.length > 0) {
2190 return parse$m(val);
2191 } else if (type === 'number' && isFinite(val)) {
2192 return options.long ? fmtLong$2(val) : fmtShort$2(val);
2193 }
2194 throw new Error(
2195 'val is not a non-empty string or a valid number. val=' +
2196 JSON.stringify(val)
2197 );
2198};
2199
2200/**
2201 * Parse the given `str` and return milliseconds.
2202 *
2203 * @param {String} str
2204 * @return {Number}
2205 * @api private
2206 */
2207
2208function parse$m(str) {
2209 str = String(str);
2210 if (str.length > 100) {
2211 return;
2212 }
2213 var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
2214 str
2215 );
2216 if (!match) {
2217 return;
2218 }
2219 var n = parseFloat(match[1]);
2220 var type = (match[2] || 'ms').toLowerCase();
2221 switch (type) {
2222 case 'years':
2223 case 'year':
2224 case 'yrs':
2225 case 'yr':
2226 case 'y':
2227 return n * y$2;
2228 case 'weeks':
2229 case 'week':
2230 case 'w':
2231 return n * w$1;
2232 case 'days':
2233 case 'day':
2234 case 'd':
2235 return n * d$2;
2236 case 'hours':
2237 case 'hour':
2238 case 'hrs':
2239 case 'hr':
2240 case 'h':
2241 return n * h$2;
2242 case 'minutes':
2243 case 'minute':
2244 case 'mins':
2245 case 'min':
2246 case 'm':
2247 return n * m$2;
2248 case 'seconds':
2249 case 'second':
2250 case 'secs':
2251 case 'sec':
2252 case 's':
2253 return n * s$2;
2254 case 'milliseconds':
2255 case 'millisecond':
2256 case 'msecs':
2257 case 'msec':
2258 case 'ms':
2259 return n;
2260 default:
2261 return undefined;
2262 }
2263}
2264
2265/**
2266 * Short format for `ms`.
2267 *
2268 * @param {Number} ms
2269 * @return {String}
2270 * @api private
2271 */
2272
2273function fmtShort$2(ms) {
2274 var msAbs = Math.abs(ms);
2275 if (msAbs >= d$2) {
2276 return Math.round(ms / d$2) + 'd';
2277 }
2278 if (msAbs >= h$2) {
2279 return Math.round(ms / h$2) + 'h';
2280 }
2281 if (msAbs >= m$2) {
2282 return Math.round(ms / m$2) + 'm';
2283 }
2284 if (msAbs >= s$2) {
2285 return Math.round(ms / s$2) + 's';
2286 }
2287 return ms + 'ms';
2288}
2289
2290/**
2291 * Long format for `ms`.
2292 *
2293 * @param {Number} ms
2294 * @return {String}
2295 * @api private
2296 */
2297
2298function fmtLong$2(ms) {
2299 var msAbs = Math.abs(ms);
2300 if (msAbs >= d$2) {
2301 return plural$2(ms, msAbs, d$2, 'day');
2302 }
2303 if (msAbs >= h$2) {
2304 return plural$2(ms, msAbs, h$2, 'hour');
2305 }
2306 if (msAbs >= m$2) {
2307 return plural$2(ms, msAbs, m$2, 'minute');
2308 }
2309 if (msAbs >= s$2) {
2310 return plural$2(ms, msAbs, s$2, 'second');
2311 }
2312 return ms + ' ms';
2313}
2314
2315/**
2316 * Pluralization helper.
2317 */
2318
2319function plural$2(ms, msAbs, n, name) {
2320 var isPlural = msAbs >= n * 1.5;
2321 return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
2322}
2323
2324/**
2325 * This is the common logic for both the Node.js and web browser
2326 * implementations of `debug()`.
2327 */
2328
2329function setup$1(env) {
2330 createDebug.debug = createDebug;
2331 createDebug.default = createDebug;
2332 createDebug.coerce = coerce;
2333 createDebug.disable = disable;
2334 createDebug.enable = enable;
2335 createDebug.enabled = enabled;
2336 createDebug.humanize = ms$2;
2337 createDebug.destroy = destroy;
2338
2339 Object.keys(env).forEach(key => {
2340 createDebug[key] = env[key];
2341 });
2342
2343 /**
2344 * The currently active debug mode names, and names to skip.
2345 */
2346
2347 createDebug.names = [];
2348 createDebug.skips = [];
2349
2350 /**
2351 * Map of special "%n" handling functions, for the debug "format" argument.
2352 *
2353 * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
2354 */
2355 createDebug.formatters = {};
2356
2357 /**
2358 * Selects a color for a debug namespace
2359 * @param {String} namespace The namespace string for the for the debug instance to be colored
2360 * @return {Number|String} An ANSI color code for the given namespace
2361 * @api private
2362 */
2363 function selectColor(namespace) {
2364 let hash = 0;
2365
2366 for (let i = 0; i < namespace.length; i++) {
2367 hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
2368 hash |= 0; // Convert to 32bit integer
2369 }
2370
2371 return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
2372 }
2373 createDebug.selectColor = selectColor;
2374
2375 /**
2376 * Create a debugger with the given `namespace`.
2377 *
2378 * @param {String} namespace
2379 * @return {Function}
2380 * @api public
2381 */
2382 function createDebug(namespace) {
2383 let prevTime;
2384 let enableOverride = null;
2385 let namespacesCache;
2386 let enabledCache;
2387
2388 function debug(...args) {
2389 // Disabled?
2390 if (!debug.enabled) {
2391 return;
2392 }
2393
2394 const self = debug;
2395
2396 // Set `diff` timestamp
2397 const curr = Number(new Date());
2398 const ms = curr - (prevTime || curr);
2399 self.diff = ms;
2400 self.prev = prevTime;
2401 self.curr = curr;
2402 prevTime = curr;
2403
2404 args[0] = createDebug.coerce(args[0]);
2405
2406 if (typeof args[0] !== 'string') {
2407 // Anything else let's inspect with %O
2408 args.unshift('%O');
2409 }
2410
2411 // Apply any `formatters` transformations
2412 let index = 0;
2413 args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
2414 // If we encounter an escaped % then don't increase the array index
2415 if (match === '%%') {
2416 return '%';
2417 }
2418 index++;
2419 const formatter = createDebug.formatters[format];
2420 if (typeof formatter === 'function') {
2421 const val = args[index];
2422 match = formatter.call(self, val);
2423
2424 // Now we need to remove `args[index]` since it's inlined in the `format`
2425 args.splice(index, 1);
2426 index--;
2427 }
2428 return match;
2429 });
2430
2431 // Apply env-specific formatting (colors, etc.)
2432 createDebug.formatArgs.call(self, args);
2433
2434 const logFn = self.log || createDebug.log;
2435 logFn.apply(self, args);
2436 }
2437
2438 debug.namespace = namespace;
2439 debug.useColors = createDebug.useColors();
2440 debug.color = createDebug.selectColor(namespace);
2441 debug.extend = extend;
2442 debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
2443
2444 Object.defineProperty(debug, 'enabled', {
2445 enumerable: true,
2446 configurable: false,
2447 get: () => {
2448 if (enableOverride !== null) {
2449 return enableOverride;
2450 }
2451 if (namespacesCache !== createDebug.namespaces) {
2452 namespacesCache = createDebug.namespaces;
2453 enabledCache = createDebug.enabled(namespace);
2454 }
2455
2456 return enabledCache;
2457 },
2458 set: v => {
2459 enableOverride = v;
2460 }
2461 });
2462
2463 // Env-specific initialization logic for debug instances
2464 if (typeof createDebug.init === 'function') {
2465 createDebug.init(debug);
2466 }
2467
2468 return debug;
2469 }
2470
2471 function extend(namespace, delimiter) {
2472 const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
2473 newDebug.log = this.log;
2474 return newDebug;
2475 }
2476
2477 /**
2478 * Enables a debug mode by namespaces. This can include modes
2479 * separated by a colon and wildcards.
2480 *
2481 * @param {String} namespaces
2482 * @api public
2483 */
2484 function enable(namespaces) {
2485 createDebug.save(namespaces);
2486 createDebug.namespaces = namespaces;
2487
2488 createDebug.names = [];
2489 createDebug.skips = [];
2490
2491 let i;
2492 const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
2493 const len = split.length;
2494
2495 for (i = 0; i < len; i++) {
2496 if (!split[i]) {
2497 // ignore empty strings
2498 continue;
2499 }
2500
2501 namespaces = split[i].replace(/\*/g, '.*?');
2502
2503 if (namespaces[0] === '-') {
2504 createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
2505 } else {
2506 createDebug.names.push(new RegExp('^' + namespaces + '$'));
2507 }
2508 }
2509 }
2510
2511 /**
2512 * Disable debug output.
2513 *
2514 * @return {String} namespaces
2515 * @api public
2516 */
2517 function disable() {
2518 const namespaces = [
2519 ...createDebug.names.map(toNamespace),
2520 ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
2521 ].join(',');
2522 createDebug.enable('');
2523 return namespaces;
2524 }
2525
2526 /**
2527 * Returns true if the given mode name is enabled, false otherwise.
2528 *
2529 * @param {String} name
2530 * @return {Boolean}
2531 * @api public
2532 */
2533 function enabled(name) {
2534 if (name[name.length - 1] === '*') {
2535 return true;
2536 }
2537
2538 let i;
2539 let len;
2540
2541 for (i = 0, len = createDebug.skips.length; i < len; i++) {
2542 if (createDebug.skips[i].test(name)) {
2543 return false;
2544 }
2545 }
2546
2547 for (i = 0, len = createDebug.names.length; i < len; i++) {
2548 if (createDebug.names[i].test(name)) {
2549 return true;
2550 }
2551 }
2552
2553 return false;
2554 }
2555
2556 /**
2557 * Convert regexp to namespace
2558 *
2559 * @param {RegExp} regxep
2560 * @return {String} namespace
2561 * @api private
2562 */
2563 function toNamespace(regexp) {
2564 return regexp.toString()
2565 .substring(2, regexp.toString().length - 2)
2566 .replace(/\.\*\?$/, '*');
2567 }
2568
2569 /**
2570 * Coerce `val`.
2571 *
2572 * @param {Mixed} val
2573 * @return {Mixed}
2574 * @api private
2575 */
2576 function coerce(val) {
2577 if (val instanceof Error) {
2578 return val.stack || val.message;
2579 }
2580 return val;
2581 }
2582
2583 /**
2584 * XXX DO NOT USE. This is a temporary stub function.
2585 * XXX It WILL be removed in the next major release.
2586 */
2587 function destroy() {
2588 console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
2589 }
2590
2591 createDebug.enable(createDebug.load());
2592
2593 return createDebug;
2594}
2595
2596var common$f = setup$1;
2597
2598/* eslint-env browser */
2599
2600(function (module, exports) {
2601/**
2602 * This is the web browser implementation of `debug()`.
2603 */
2604
2605exports.formatArgs = formatArgs;
2606exports.save = save;
2607exports.load = load;
2608exports.useColors = useColors;
2609exports.storage = localstorage();
2610exports.destroy = (() => {
2611 let warned = false;
2612
2613 return () => {
2614 if (!warned) {
2615 warned = true;
2616 console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
2617 }
2618 };
2619})();
2620
2621/**
2622 * Colors.
2623 */
2624
2625exports.colors = [
2626 '#0000CC',
2627 '#0000FF',
2628 '#0033CC',
2629 '#0033FF',
2630 '#0066CC',
2631 '#0066FF',
2632 '#0099CC',
2633 '#0099FF',
2634 '#00CC00',
2635 '#00CC33',
2636 '#00CC66',
2637 '#00CC99',
2638 '#00CCCC',
2639 '#00CCFF',
2640 '#3300CC',
2641 '#3300FF',
2642 '#3333CC',
2643 '#3333FF',
2644 '#3366CC',
2645 '#3366FF',
2646 '#3399CC',
2647 '#3399FF',
2648 '#33CC00',
2649 '#33CC33',
2650 '#33CC66',
2651 '#33CC99',
2652 '#33CCCC',
2653 '#33CCFF',
2654 '#6600CC',
2655 '#6600FF',
2656 '#6633CC',
2657 '#6633FF',
2658 '#66CC00',
2659 '#66CC33',
2660 '#9900CC',
2661 '#9900FF',
2662 '#9933CC',
2663 '#9933FF',
2664 '#99CC00',
2665 '#99CC33',
2666 '#CC0000',
2667 '#CC0033',
2668 '#CC0066',
2669 '#CC0099',
2670 '#CC00CC',
2671 '#CC00FF',
2672 '#CC3300',
2673 '#CC3333',
2674 '#CC3366',
2675 '#CC3399',
2676 '#CC33CC',
2677 '#CC33FF',
2678 '#CC6600',
2679 '#CC6633',
2680 '#CC9900',
2681 '#CC9933',
2682 '#CCCC00',
2683 '#CCCC33',
2684 '#FF0000',
2685 '#FF0033',
2686 '#FF0066',
2687 '#FF0099',
2688 '#FF00CC',
2689 '#FF00FF',
2690 '#FF3300',
2691 '#FF3333',
2692 '#FF3366',
2693 '#FF3399',
2694 '#FF33CC',
2695 '#FF33FF',
2696 '#FF6600',
2697 '#FF6633',
2698 '#FF9900',
2699 '#FF9933',
2700 '#FFCC00',
2701 '#FFCC33'
2702];
2703
2704/**
2705 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
2706 * and the Firebug extension (any Firefox version) are known
2707 * to support "%c" CSS customizations.
2708 *
2709 * TODO: add a `localStorage` variable to explicitly enable/disable colors
2710 */
2711
2712// eslint-disable-next-line complexity
2713function useColors() {
2714 // NB: In an Electron preload script, document will be defined but not fully
2715 // initialized. Since we know we're in Chrome, we'll just detect this case
2716 // explicitly
2717 if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
2718 return true;
2719 }
2720
2721 // Internet Explorer and Edge do not support colors.
2722 if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
2723 return false;
2724 }
2725
2726 // Is webkit? http://stackoverflow.com/a/16459606/376773
2727 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
2728 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
2729 // Is firebug? http://stackoverflow.com/a/398120/376773
2730 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
2731 // Is firefox >= v31?
2732 // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
2733 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
2734 // Double check webkit in userAgent just in case we are in a worker
2735 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
2736}
2737
2738/**
2739 * Colorize log arguments if enabled.
2740 *
2741 * @api public
2742 */
2743
2744function formatArgs(args) {
2745 args[0] = (this.useColors ? '%c' : '') +
2746 this.namespace +
2747 (this.useColors ? ' %c' : ' ') +
2748 args[0] +
2749 (this.useColors ? '%c ' : ' ') +
2750 '+' + module.exports.humanize(this.diff);
2751
2752 if (!this.useColors) {
2753 return;
2754 }
2755
2756 const c = 'color: ' + this.color;
2757 args.splice(1, 0, c, 'color: inherit');
2758
2759 // The final "%c" is somewhat tricky, because there could be other
2760 // arguments passed either before or after the %c, so we need to
2761 // figure out the correct index to insert the CSS into
2762 let index = 0;
2763 let lastC = 0;
2764 args[0].replace(/%[a-zA-Z%]/g, match => {
2765 if (match === '%%') {
2766 return;
2767 }
2768 index++;
2769 if (match === '%c') {
2770 // We only are interested in the *last* %c
2771 // (the user may have provided their own)
2772 lastC = index;
2773 }
2774 });
2775
2776 args.splice(lastC, 0, c);
2777}
2778
2779/**
2780 * Invokes `console.debug()` when available.
2781 * No-op when `console.debug` is not a "function".
2782 * If `console.debug` is not available, falls back
2783 * to `console.log`.
2784 *
2785 * @api public
2786 */
2787exports.log = console.debug || console.log || (() => {});
2788
2789/**
2790 * Save `namespaces`.
2791 *
2792 * @param {String} namespaces
2793 * @api private
2794 */
2795function save(namespaces) {
2796 try {
2797 if (namespaces) {
2798 exports.storage.setItem('debug', namespaces);
2799 } else {
2800 exports.storage.removeItem('debug');
2801 }
2802 } catch (error) {
2803 // Swallow
2804 // XXX (@Qix-) should we be logging these?
2805 }
2806}
2807
2808/**
2809 * Load `namespaces`.
2810 *
2811 * @return {String} returns the previously persisted debug modes
2812 * @api private
2813 */
2814function load() {
2815 let r;
2816 try {
2817 r = exports.storage.getItem('debug');
2818 } catch (error) {
2819 // Swallow
2820 // XXX (@Qix-) should we be logging these?
2821 }
2822
2823 // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
2824 if (!r && typeof process !== 'undefined' && 'env' in process) {
2825 r = process.env.DEBUG;
2826 }
2827
2828 return r;
2829}
2830
2831/**
2832 * Localstorage attempts to return the localstorage.
2833 *
2834 * This is necessary because safari throws
2835 * when a user disables cookies/localstorage
2836 * and you attempt to access it.
2837 *
2838 * @return {LocalStorage}
2839 * @api private
2840 */
2841
2842function localstorage() {
2843 try {
2844 // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
2845 // The Browser also has localStorage in the global context.
2846 return localStorage;
2847 } catch (error) {
2848 // Swallow
2849 // XXX (@Qix-) should we be logging these?
2850 }
2851}
2852
2853module.exports = common$f(exports);
2854
2855const {formatters} = module.exports;
2856
2857/**
2858 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
2859 */
2860
2861formatters.j = function (v) {
2862 try {
2863 return JSON.stringify(v);
2864 } catch (error) {
2865 return '[UnexpectedJSONParseError]: ' + error.message;
2866 }
2867};
2868}(browser$3, browser$3.exports));
2869
2870var node$3 = {exports: {}};
2871
2872/**
2873 * Module dependencies.
2874 */
2875
2876(function (module, exports) {
2877const tty = require$$0__default;
2878const util = require$$0__default$3;
2879
2880/**
2881 * This is the Node.js implementation of `debug()`.
2882 */
2883
2884exports.init = init;
2885exports.log = log;
2886exports.formatArgs = formatArgs;
2887exports.save = save;
2888exports.load = load;
2889exports.useColors = useColors;
2890exports.destroy = util.deprecate(
2891 () => {},
2892 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'
2893);
2894
2895/**
2896 * Colors.
2897 */
2898
2899exports.colors = [6, 2, 3, 4, 5, 1];
2900
2901try {
2902 // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
2903 // eslint-disable-next-line import/no-extraneous-dependencies
2904 const supportsColor = supportsColor_1$1;
2905
2906 if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
2907 exports.colors = [
2908 20,
2909 21,
2910 26,
2911 27,
2912 32,
2913 33,
2914 38,
2915 39,
2916 40,
2917 41,
2918 42,
2919 43,
2920 44,
2921 45,
2922 56,
2923 57,
2924 62,
2925 63,
2926 68,
2927 69,
2928 74,
2929 75,
2930 76,
2931 77,
2932 78,
2933 79,
2934 80,
2935 81,
2936 92,
2937 93,
2938 98,
2939 99,
2940 112,
2941 113,
2942 128,
2943 129,
2944 134,
2945 135,
2946 148,
2947 149,
2948 160,
2949 161,
2950 162,
2951 163,
2952 164,
2953 165,
2954 166,
2955 167,
2956 168,
2957 169,
2958 170,
2959 171,
2960 172,
2961 173,
2962 178,
2963 179,
2964 184,
2965 185,
2966 196,
2967 197,
2968 198,
2969 199,
2970 200,
2971 201,
2972 202,
2973 203,
2974 204,
2975 205,
2976 206,
2977 207,
2978 208,
2979 209,
2980 214,
2981 215,
2982 220,
2983 221
2984 ];
2985 }
2986} catch (error) {
2987 // Swallow - we only care if `supports-color` is available; it doesn't have to be.
2988}
2989
2990/**
2991 * Build up the default `inspectOpts` object from the environment variables.
2992 *
2993 * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
2994 */
2995
2996exports.inspectOpts = Object.keys(process.env).filter(key => {
2997 return /^debug_/i.test(key);
2998}).reduce((obj, key) => {
2999 // Camel-case
3000 const prop = key
3001 .substring(6)
3002 .toLowerCase()
3003 .replace(/_([a-z])/g, (_, k) => {
3004 return k.toUpperCase();
3005 });
3006
3007 // Coerce string value into JS value
3008 let val = process.env[key];
3009 if (/^(yes|on|true|enabled)$/i.test(val)) {
3010 val = true;
3011 } else if (/^(no|off|false|disabled)$/i.test(val)) {
3012 val = false;
3013 } else if (val === 'null') {
3014 val = null;
3015 } else {
3016 val = Number(val);
3017 }
3018
3019 obj[prop] = val;
3020 return obj;
3021}, {});
3022
3023/**
3024 * Is stdout a TTY? Colored output is enabled when `true`.
3025 */
3026
3027function useColors() {
3028 return 'colors' in exports.inspectOpts ?
3029 Boolean(exports.inspectOpts.colors) :
3030 tty.isatty(process.stderr.fd);
3031}
3032
3033/**
3034 * Adds ANSI color escape codes if enabled.
3035 *
3036 * @api public
3037 */
3038
3039function formatArgs(args) {
3040 const {namespace: name, useColors} = this;
3041
3042 if (useColors) {
3043 const c = this.color;
3044 const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
3045 const prefix = ` ${colorCode};1m${name} \u001B[0m`;
3046
3047 args[0] = prefix + args[0].split('\n').join('\n' + prefix);
3048 args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
3049 } else {
3050 args[0] = getDate() + name + ' ' + args[0];
3051 }
3052}
3053
3054function getDate() {
3055 if (exports.inspectOpts.hideDate) {
3056 return '';
3057 }
3058 return new Date().toISOString() + ' ';
3059}
3060
3061/**
3062 * Invokes `util.format()` with the specified arguments and writes to stderr.
3063 */
3064
3065function log(...args) {
3066 return process.stderr.write(util.format(...args) + '\n');
3067}
3068
3069/**
3070 * Save `namespaces`.
3071 *
3072 * @param {String} namespaces
3073 * @api private
3074 */
3075function save(namespaces) {
3076 if (namespaces) {
3077 process.env.DEBUG = namespaces;
3078 } else {
3079 // If you set a process.env field to null or undefined, it gets cast to the
3080 // string 'null' or 'undefined'. Just delete instead.
3081 delete process.env.DEBUG;
3082 }
3083}
3084
3085/**
3086 * Load `namespaces`.
3087 *
3088 * @return {String} returns the previously persisted debug modes
3089 * @api private
3090 */
3091
3092function load() {
3093 return process.env.DEBUG;
3094}
3095
3096/**
3097 * Init logic for `debug` instances.
3098 *
3099 * Create a new `inspectOpts` object in case `useColors` is set
3100 * differently for a particular `debug` instance.
3101 */
3102
3103function init(debug) {
3104 debug.inspectOpts = {};
3105
3106 const keys = Object.keys(exports.inspectOpts);
3107 for (let i = 0; i < keys.length; i++) {
3108 debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
3109 }
3110}
3111
3112module.exports = common$f(exports);
3113
3114const {formatters} = module.exports;
3115
3116/**
3117 * Map %o to `util.inspect()`, all on a single line.
3118 */
3119
3120formatters.o = function (v) {
3121 this.inspectOpts.colors = this.useColors;
3122 return util.inspect(v, this.inspectOpts)
3123 .split('\n')
3124 .map(str => str.trim())
3125 .join(' ');
3126};
3127
3128/**
3129 * Map %O to `util.inspect()`, allowing multiple lines if needed.
3130 */
3131
3132formatters.O = function (v) {
3133 this.inspectOpts.colors = this.useColors;
3134 return util.inspect(v, this.inspectOpts);
3135};
3136}(node$3, node$3.exports));
3137
3138/**
3139 * Detect Electron renderer / nwjs process, which is node, but we should
3140 * treat as a browser.
3141 */
3142
3143if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
3144 src$4.exports = browser$3.exports;
3145} else {
3146 src$4.exports = node$3.exports;
3147}
3148
3149var debug$c = src$4.exports;
3150
3151const DEFAULT_MAIN_FIELDS = [
3152 'module',
3153 'jsnext:main',
3154 'jsnext'
3155];
3156const DEFAULT_EXTENSIONS = [
3157 '.mjs',
3158 '.js',
3159 '.ts',
3160 '.jsx',
3161 '.tsx',
3162 '.json'
3163];
3164const JS_TYPES_RE = /\.(?:j|t)sx?$|\.mjs$/;
3165const OPTIMIZABLE_ENTRY_RE = /\.(?:m?js|ts)$/;
3166const SPECIAL_QUERY_RE = /[\?&](?:worker|sharedworker|raw|url)\b/;
3167/**
3168 * Prefix for resolved fs paths, since windows paths may not be valid as URLs.
3169 */
3170const FS_PREFIX = `/@fs/`;
3171/**
3172 * Prefix for resolved Ids that are not valid browser import specifiers
3173 */
3174const VALID_ID_PREFIX = `/@id/`;
3175/**
3176 * Some Rollup plugins use ids that starts with the null byte \0 to avoid
3177 * collisions, but it is not permitted in import URLs so we have to replace
3178 * them.
3179 */
3180const NULL_BYTE_PLACEHOLDER = `__x00__`;
3181const CLIENT_PUBLIC_PATH = `/@vite/client`;
3182const ENV_PUBLIC_PATH = `/@vite/env`;
3183// eslint-disable-next-line node/no-missing-require
3184const CLIENT_ENTRY = require.resolve('vite/dist/client/client.mjs');
3185// eslint-disable-next-line node/no-missing-require
3186const ENV_ENTRY = require.resolve('vite/dist/client/env.mjs');
3187const CLIENT_DIR = path__default.dirname(CLIENT_ENTRY);
3188const KNOWN_ASSET_TYPES = [
3189 // images
3190 'png',
3191 'jpe?g',
3192 'gif',
3193 'svg',
3194 'ico',
3195 'webp',
3196 'avif',
3197 // media
3198 'mp4',
3199 'webm',
3200 'ogg',
3201 'mp3',
3202 'wav',
3203 'flac',
3204 'aac',
3205 // fonts
3206 'woff2?',
3207 'eot',
3208 'ttf',
3209 'otf',
3210 // other
3211 'wasm'
3212];
3213const DEFAULT_ASSETS_RE = new RegExp(`\\.(` + KNOWN_ASSET_TYPES.join('|') + `)(\\?.*)?$`);
3214const DEP_VERSION_RE = /[\?&](v=[\w\.-]+)\b/;
3215
3216const {builtinModules} = require$$0__default$5;
3217
3218const ignoreList = [
3219 'sys'
3220];
3221
3222// eslint-disable-next-line node/no-deprecated-api
3223var builtinModules_1 = (builtinModules || Object.keys(process.binding('natives')))
3224 .filter(x => !/^_|^(internal|v8|node-inspect)\/|\//.test(x) && !ignoreList.includes(x))
3225 .sort();
3226
3227var charToInteger$1 = {};
3228var chars$2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
3229for (var i$2 = 0; i$2 < chars$2.length; i$2++) {
3230 charToInteger$1[chars$2.charCodeAt(i$2)] = i$2;
3231}
3232function decode(mappings) {
3233 var decoded = [];
3234 var line = [];
3235 var segment = [
3236 0,
3237 0,
3238 0,
3239 0,
3240 0,
3241 ];
3242 var j = 0;
3243 for (var i = 0, shift = 0, value = 0; i < mappings.length; i++) {
3244 var c = mappings.charCodeAt(i);
3245 if (c === 44) { // ","
3246 segmentify(line, segment, j);
3247 j = 0;
3248 }
3249 else if (c === 59) { // ";"
3250 segmentify(line, segment, j);
3251 j = 0;
3252 decoded.push(line);
3253 line = [];
3254 segment[0] = 0;
3255 }
3256 else {
3257 var integer = charToInteger$1[c];
3258 if (integer === undefined) {
3259 throw new Error('Invalid character (' + String.fromCharCode(c) + ')');
3260 }
3261 var hasContinuationBit = integer & 32;
3262 integer &= 31;
3263 value += integer << shift;
3264 if (hasContinuationBit) {
3265 shift += 5;
3266 }
3267 else {
3268 var shouldNegate = value & 1;
3269 value >>>= 1;
3270 if (shouldNegate) {
3271 value = value === 0 ? -0x80000000 : -value;
3272 }
3273 segment[j] += value;
3274 j++;
3275 value = shift = 0; // reset
3276 }
3277 }
3278 }
3279 segmentify(line, segment, j);
3280 decoded.push(line);
3281 return decoded;
3282}
3283function segmentify(line, segment, j) {
3284 // This looks ugly, but we're creating specialized arrays with a specific
3285 // length. This is much faster than creating a new array (which v8 expands to
3286 // a capacity of 17 after pushing the first item), or slicing out a subarray
3287 // (which is slow). Length 4 is assumed to be the most frequent, followed by
3288 // length 5 (since not everything will have an associated name), followed by
3289 // length 1 (it's probably rare for a source substring to not have an
3290 // associated segment data).
3291 if (j === 4)
3292 line.push([segment[0], segment[1], segment[2], segment[3]]);
3293 else if (j === 5)
3294 line.push([segment[0], segment[1], segment[2], segment[3], segment[4]]);
3295 else if (j === 1)
3296 line.push([segment[0]]);
3297}
3298function encode$1(decoded) {
3299 var sourceFileIndex = 0; // second field
3300 var sourceCodeLine = 0; // third field
3301 var sourceCodeColumn = 0; // fourth field
3302 var nameIndex = 0; // fifth field
3303 var mappings = '';
3304 for (var i = 0; i < decoded.length; i++) {
3305 var line = decoded[i];
3306 if (i > 0)
3307 mappings += ';';
3308 if (line.length === 0)
3309 continue;
3310 var generatedCodeColumn = 0; // first field
3311 var lineMappings = [];
3312 for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
3313 var segment = line_1[_i];
3314 var segmentMappings = encodeInteger$1(segment[0] - generatedCodeColumn);
3315 generatedCodeColumn = segment[0];
3316 if (segment.length > 1) {
3317 segmentMappings +=
3318 encodeInteger$1(segment[1] - sourceFileIndex) +
3319 encodeInteger$1(segment[2] - sourceCodeLine) +
3320 encodeInteger$1(segment[3] - sourceCodeColumn);
3321 sourceFileIndex = segment[1];
3322 sourceCodeLine = segment[2];
3323 sourceCodeColumn = segment[3];
3324 }
3325 if (segment.length === 5) {
3326 segmentMappings += encodeInteger$1(segment[4] - nameIndex);
3327 nameIndex = segment[4];
3328 }
3329 lineMappings.push(segmentMappings);
3330 }
3331 mappings += lineMappings.join(',');
3332 }
3333 return mappings;
3334}
3335function encodeInteger$1(num) {
3336 var result = '';
3337 num = num < 0 ? (-num << 1) | 1 : num << 1;
3338 do {
3339 var clamped = num & 31;
3340 num >>>= 5;
3341 if (num > 0) {
3342 clamped |= 32;
3343 }
3344 result += chars$2[clamped];
3345 } while (num > 0);
3346 return result;
3347}
3348
3349/**
3350 * Copyright 2019 The AMP HTML Authors. All Rights Reserved.
3351 *
3352 * Licensed under the Apache License, Version 2.0 (the "License");
3353 * you may not use this file except in compliance with the License.
3354 * You may obtain a copy of the License at
3355 *
3356 * http://www.apache.org/licenses/LICENSE-2.0
3357 *
3358 * Unless required by applicable law or agreed to in writing, software
3359 * distributed under the License is distributed on an "AS IS" BASIS,
3360 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3361 * See the License for the specific language governing permissions and
3362 * limitations under the License.
3363 */
3364/**
3365 * Creates a brand new (prototype-less) object with the enumerable-own
3366 * properties of `target`. Any enumerable-own properties from `source` which
3367 * are not present on `target` will be copied as well.
3368 */
3369function defaults(target, source) {
3370 return Object.assign(Object.create(null), source, target);
3371}
3372
3373/**
3374 * Copyright 2019 The AMP HTML Authors. All Rights Reserved.
3375 *
3376 * Licensed under the Apache License, Version 2.0 (the "License");
3377 * you may not use this file except in compliance with the License.
3378 * You may obtain a copy of the License at
3379 *
3380 * http://www.apache.org/licenses/LICENSE-2.0
3381 *
3382 * Unless required by applicable law or agreed to in writing, software
3383 * distributed under the License is distributed on an "AS IS" BASIS,
3384 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3385 * See the License for the specific language governing permissions and
3386 * limitations under the License.
3387 */
3388/**
3389 * Decodes an input sourcemap into a `DecodedSourceMap` sourcemap object.
3390 *
3391 * Valid input maps include a `DecodedSourceMap`, a `RawSourceMap`, or JSON
3392 * representations of either type.
3393 */
3394function decodeSourceMap(map) {
3395 if (typeof map === 'string') {
3396 map = JSON.parse(map);
3397 }
3398 let { mappings } = map;
3399 if (typeof mappings === 'string') {
3400 mappings = sortMappings(decode(mappings), true);
3401 }
3402 else {
3403 // Clone the Line so that we can sort it. We don't want to mutate an array
3404 // that we don't own directly.
3405 mappings = sortMappings(mappings, false);
3406 }
3407 return defaults({ mappings }, map);
3408}
3409function firstUnsortedSegmentLine(mappings) {
3410 for (let i = 0; i < mappings.length; i++) {
3411 const segments = mappings[i];
3412 for (let j = 1; j < segments.length; j++) {
3413 if (segments[j][0] < segments[j - 1][0]) {
3414 return i;
3415 }
3416 }
3417 }
3418 return mappings.length;
3419}
3420function sortMappings(mappings, owned) {
3421 const unosrtedIndex = firstUnsortedSegmentLine(mappings);
3422 if (unosrtedIndex === mappings.length)
3423 return mappings;
3424 if (!owned)
3425 mappings = mappings.slice();
3426 for (let i = unosrtedIndex; i < mappings.length; i++) {
3427 mappings[i] = sortSegments(mappings[i], owned);
3428 }
3429 return mappings;
3430}
3431function sortSegments(segments, owned) {
3432 if (!owned)
3433 segments = segments.slice();
3434 return segments.sort(segmentComparator);
3435}
3436function segmentComparator(a, b) {
3437 return a[0] - b[0];
3438}
3439
3440/**
3441 * Copyright 2019 The AMP HTML Authors. All Rights Reserved.
3442 *
3443 * Licensed under the Apache License, Version 2.0 (the "License");
3444 * you may not use this file except in compliance with the License.
3445 * You may obtain a copy of the License at
3446 *
3447 * http://www.apache.org/licenses/LICENSE-2.0
3448 *
3449 * Unless required by applicable law or agreed to in writing, software
3450 * distributed under the License is distributed on an "AS IS" BASIS,
3451 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3452 * See the License for the specific language governing permissions and
3453 * limitations under the License.
3454 */
3455/**
3456 * A "leaf" node in the sourcemap tree, representing an original, unmodified
3457 * source file. Recursive segment tracing ends at the `OriginalSource`.
3458 */
3459class OriginalSource {
3460 constructor(filename, content) {
3461 this.filename = filename;
3462 this.content = content;
3463 }
3464 /**
3465 * Tracing a `SourceMapSegment` ends when we get to an `OriginalSource`,
3466 * meaning this line/column location originated from this source file.
3467 */
3468 traceSegment(line, column, name) {
3469 return { column, line, name, source: this };
3470 }
3471}
3472
3473/* istanbul ignore next */
3474const Url$1 = (typeof URL !== 'undefined' ? URL : require('url').URL);
3475// Matches "..", which must be preceeded by "/" or the start of the string, and
3476// must be followed by a "/". We do not eat the following "/", so that the next
3477// iteration can match on it.
3478const parentRegex = /(^|\/)\.\.(?=\/|$)/g;
3479function isAbsoluteUrl(url) {
3480 try {
3481 return !!new Url$1(url);
3482 }
3483 catch (e) {
3484 return false;
3485 }
3486}
3487/**
3488 * Creates a directory name that is guaranteed to not be in `str`.
3489 */
3490function uniqInStr(str) {
3491 let uniq = String(Math.random()).slice(2);
3492 while (str.indexOf(uniq) > -1) {
3493 /* istanbul ignore next */
3494 uniq += uniq;
3495 }
3496 return uniq;
3497}
3498/**
3499 * Removes the filename from the path (everything trailing the last "/"). This
3500 * is only safe to call on a path, never call with an absolute or protocol
3501 * relative URL.
3502 */
3503function stripPathFilename(path) {
3504 path = normalizePath$5(path);
3505 const index = path.lastIndexOf('/');
3506 return path.slice(0, index + 1);
3507}
3508/**
3509 * Normalizes a protocol-relative URL, but keeps it protocol relative by
3510 * stripping out the protocl before returning it.
3511 */
3512function normalizeProtocolRelative(input, absoluteBase) {
3513 const { href, protocol } = new Url$1(input, absoluteBase);
3514 return href.slice(protocol.length);
3515}
3516/**
3517 * Normalizes a simple path (one that has no ".."s, or is absolute so ".."s can
3518 * be normalized absolutely).
3519 */
3520function normalizeSimplePath(input) {
3521 const { href } = new Url$1(input, 'https://foo.com/');
3522 return href.slice('https://foo.com/'.length);
3523}
3524/**
3525 * Normalizes a path, ensuring that excess ".."s are preserved for relative
3526 * paths in the output.
3527 *
3528 * If the input is absolute, this will return an absolutey normalized path, but
3529 * it will not have a leading "/".
3530 *
3531 * If the input has a leading "..", the output will have a leading "..".
3532 *
3533 * If the input has a leading ".", the output will not have a leading "."
3534 * unless there are too many ".."s, in which case there will be a leading "..".
3535 */
3536function normalizePath$5(input) {
3537 // If there are no ".."s, we can treat this as if it were an absolute path.
3538 // The return won't be an absolute path, so it's easy.
3539 if (!parentRegex.test(input))
3540 return normalizeSimplePath(input);
3541 // We already found one "..". Let's see how many there are.
3542 let total = 1;
3543 while (parentRegex.test(input))
3544 total++;
3545 // If there are ".."s, we need to prefix the the path with the same number of
3546 // unique directories. This is to ensure that we "remember" how many parent
3547 // directories we are accessing. Eg, "../../.." must keep 3, and "foo/../.."
3548 // must keep 1.
3549 const uniqDirectory = `z${uniqInStr(input)}/`;
3550 // uniqDirectory is just a "z", followed by numbers, followed by a "/". So
3551 // generating a runtime regex from it is safe. We'll use this search regex to
3552 // strip out our uniq directory names and insert any needed ".."s.
3553 const search = new RegExp(`^(?:${uniqDirectory})*`);
3554 // Now we can resolve the total path. If there are excess ".."s, they will
3555 // eliminate one or more of the unique directories we prefix with.
3556 const relative = normalizeSimplePath(uniqDirectory.repeat(total) + input);
3557 // We can now count the number of unique directories that were eliminated. If
3558 // there were 3, and 1 was eliminated, we know we only need to add 1 "..". If
3559 // 2 were eliminated, we need to insert 2 ".."s. If all 3 were eliminated,
3560 // then we need 3, etc. This replace is guranteed to match (it may match 0 or
3561 // more times), and we can count the total match to see how many were eliminated.
3562 return relative.replace(search, (all) => {
3563 const leftover = all.length / uniqDirectory.length;
3564 return '../'.repeat(total - leftover);
3565 });
3566}
3567/**
3568 * Attempts to resolve `input` URL relative to `base`.
3569 */
3570function resolve$3(input, base) {
3571 if (!base)
3572 base = '';
3573 // Absolute URLs are very easy to resolve right.
3574 if (isAbsoluteUrl(input))
3575 return new Url$1(input).href;
3576 if (base) {
3577 // Absolute URLs are easy...
3578 if (isAbsoluteUrl(base))
3579 return new Url$1(input, base).href;
3580 // If base is protocol relative, we'll resolve with it but keep the result
3581 // protocol relative.
3582 if (base.startsWith('//'))
3583 return normalizeProtocolRelative(input, `https:${base}`);
3584 }
3585 // Normalize input, but keep it protocol relative. We know base doesn't supply
3586 // a protocol, because that would have been handled above.
3587 if (input.startsWith('//'))
3588 return normalizeProtocolRelative(input, 'https://foo.com/');
3589 // We now know that base (if there is one) and input are paths. We've handled
3590 // both absolute and protocol-relative variations above.
3591 // Absolute paths don't need any special handling, because they cannot have
3592 // extra "." or ".."s. That'll all be stripped away. Input takes priority here,
3593 // because if input is an absolute path, base path won't affect it in any way.
3594 if (input.startsWith('/'))
3595 return '/' + normalizeSimplePath(input);
3596 // Since input and base are paths, we need to join them to do any further
3597 // processing. Paths are joined at the directory level, so we need to remove
3598 // the base's filename before joining. We also know that input does not have a
3599 // leading slash, and that the stripped base will have a trailing slash if
3600 // there are any directories (or it'll be empty).
3601 const joined = stripPathFilename(base) + input;
3602 // If base is an absolute path, then input will be relative to it.
3603 if (base.startsWith('/'))
3604 return '/' + normalizeSimplePath(joined);
3605 // We now know both base (if there is one) and input are relative paths.
3606 const relative = normalizePath$5(joined);
3607 // If base started with a leading ".", or there is no base and input started
3608 // with a ".", then we need to ensure that the relative path starts with a
3609 // ".". We don't know if relative starts with a "..", though, so check before
3610 // prepending.
3611 if ((base || input).startsWith('.') && !relative.startsWith('.')) {
3612 return './' + relative;
3613 }
3614 return relative;
3615}
3616
3617/**
3618 * Copyright 2019 The AMP HTML Authors. All Rights Reserved.
3619 *
3620 * Licensed under the Apache License, Version 2.0 (the "License");
3621 * you may not use this file except in compliance with the License.
3622 * You may obtain a copy of the License at
3623 *
3624 * http://www.apache.org/licenses/LICENSE-2.0
3625 *
3626 * Unless required by applicable law or agreed to in writing, software
3627 * distributed under the License is distributed on an "AS IS" BASIS,
3628 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3629 * See the License for the specific language governing permissions and
3630 * limitations under the License.
3631 */
3632function resolve$1$1(input, base) {
3633 // The base is always treated as a directory, if it's not empty.
3634 // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327
3635 // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401
3636 if (base && !base.endsWith('/'))
3637 base += '/';
3638 return resolve$3(input, base);
3639}
3640
3641/**
3642 * Copyright 2019 The AMP HTML Authors. All Rights Reserved.
3643 *
3644 * Licensed under the Apache License, Version 2.0 (the "License");
3645 * you may not use this file except in compliance with the License.
3646 * You may obtain a copy of the License at
3647 *
3648 * http://www.apache.org/licenses/LICENSE-2.0
3649 *
3650 * Unless required by applicable law or agreed to in writing, software
3651 * distributed under the License is distributed on an "AS IS" BASIS,
3652 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3653 * See the License for the specific language governing permissions and
3654 * limitations under the License.
3655 */
3656/**
3657 * A binary search implementation that returns the index if a match is found,
3658 * or the negated index of where the `needle` should be inserted.
3659 *
3660 * The `comparator` callback receives both the `item` under comparison and the
3661 * needle we are searching for. It must return `0` if the `item` is a match,
3662 * any negative number if `item` is too small (and we must search after it), or
3663 * any positive number if the `item` is too large (and we must search before
3664 * it).
3665 *
3666 * If no match is found, a negated index of where to insert the `needle` is
3667 * returned. This negated index is guaranteed to be less than 0. To insert an
3668 * item, negate it (again) and splice:
3669 *
3670 * ```js
3671 * const array = [1, 3];
3672 * const needle = 2;
3673 * const index = binarySearch(array, needle, (item, needle) => item - needle);
3674 *
3675 * assert.equal(index, -2);
3676 * assert.equal(~index, 1);
3677 * array.splice(~index, 0, needle);
3678 * assert.deepEqual(array, [1, 2, 3]);
3679 * ```
3680 */
3681function binarySearch$2(haystack, needle, comparator, low, high) {
3682 low = Math.max(low, 0);
3683 while (low <= high) {
3684 const mid = low + ((high - low) >> 1);
3685 const cmp = comparator(haystack[mid], needle);
3686 if (cmp === 0) {
3687 return mid;
3688 }
3689 if (cmp < 0) {
3690 low = mid + 1;
3691 }
3692 else {
3693 high = mid - 1;
3694 }
3695 }
3696 return ~low;
3697}
3698
3699/**
3700 * Copyright 2019 The AMP HTML Authors. All Rights Reserved.
3701 *
3702 * Licensed under the Apache License, Version 2.0 (the "License");
3703 * you may not use this file except in compliance with the License.
3704 * You may obtain a copy of the License at
3705 *
3706 * http://www.apache.org/licenses/LICENSE-2.0
3707 *
3708 * Unless required by applicable law or agreed to in writing, software
3709 * distributed under the License is distributed on an "AS IS" BASIS,
3710 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3711 * See the License for the specific language governing permissions and
3712 * limitations under the License.
3713 */
3714/**
3715 * FastStringArray acts like a `Set` (allowing only one occurrence of a string
3716 * `key`), but provides the index of the `key` in the backing array.
3717 *
3718 * This is designed to allow synchronizing a second array with the contents of
3719 * the backing array, like how `sourcesContent[i]` is the source content
3720 * associated with `source[i]`, and there are never duplicates.
3721 */
3722class FastStringArray {
3723 constructor() {
3724 this.indexes = Object.create(null);
3725 this.array = [];
3726 }
3727 /**
3728 * Puts `key` into the backing array, if it is not already present. Returns
3729 * the index of the `key` in the backing array.
3730 */
3731 put(key) {
3732 const { array, indexes } = this;
3733 // The key may or may not be present. If it is present, it's a number.
3734 let index = indexes[key];
3735 // If it's not yet present, we need to insert it and track the index in the
3736 // indexes.
3737 if (index === undefined) {
3738 index = indexes[key] = array.length;
3739 array.push(key);
3740 }
3741 return index;
3742 }
3743}
3744
3745/**
3746 * Copyright 2019 The AMP HTML Authors. All Rights Reserved.
3747 *
3748 * Licensed under the Apache License, Version 2.0 (the "License");
3749 * you may not use this file except in compliance with the License.
3750 * You may obtain a copy of the License at
3751 *
3752 * http://www.apache.org/licenses/LICENSE-2.0
3753 *
3754 * Unless required by applicable law or agreed to in writing, software
3755 * distributed under the License is distributed on an "AS IS" BASIS,
3756 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3757 * See the License for the specific language governing permissions and
3758 * limitations under the License.
3759 */
3760/**
3761 * SourceMapTree represents a single sourcemap, with the ability to trace
3762 * mappings into its child nodes (which may themselves be SourceMapTrees).
3763 */
3764class SourceMapTree {
3765 constructor(map, sources) {
3766 this.map = map;
3767 this.sources = sources;
3768 this.lastLine = 0;
3769 this.lastColumn = 0;
3770 this.lastIndex = 0;
3771 }
3772 /**
3773 * traceMappings is only called on the root level SourceMapTree, and begins
3774 * the process of resolving each mapping in terms of the original source
3775 * files.
3776 */
3777 traceMappings() {
3778 const mappings = [];
3779 const names = new FastStringArray();
3780 const sources = new FastStringArray();
3781 const sourcesContent = [];
3782 const { mappings: rootMappings, names: rootNames } = this.map;
3783 for (let i = 0; i < rootMappings.length; i++) {
3784 const segments = rootMappings[i];
3785 const tracedSegments = [];
3786 let lastTraced = undefined;
3787 for (let j = 0; j < segments.length; j++) {
3788 const segment = segments[j];
3789 // 1-length segments only move the current generated column, there's no
3790 // source information to gather from it.
3791 if (segment.length === 1)
3792 continue;
3793 const source = this.sources[segment[1]];
3794 const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : '');
3795 if (!traced)
3796 continue;
3797 // So we traced a segment down into its original source file. Now push a
3798 // new segment pointing to this location.
3799 const { column, line, name } = traced;
3800 const { content, filename } = traced.source;
3801 // Store the source location, and ensure we keep sourcesContent up to
3802 // date with the sources array.
3803 const sourceIndex = sources.put(filename);
3804 sourcesContent[sourceIndex] = content;
3805 if (lastTraced &&
3806 lastTraced[1] === sourceIndex &&
3807 lastTraced[2] === line &&
3808 lastTraced[3] === column) {
3809 // This is a duplicate mapping pointing at the exact same starting point in the source file.
3810 // It doesn't provide any new information, and only bloats the sourcemap.
3811 continue;
3812 }
3813 // This looks like unnecessary duplication, but it noticeably increases
3814 // performance. If we were to push the nameIndex onto length-4 array, v8
3815 // would internally allocate 22 slots! That's 68 wasted bytes! Array
3816 // literals have the same capacity as their length, saving memory.
3817 if (name) {
3818 lastTraced = [segment[0], sourceIndex, line, column, names.put(name)];
3819 }
3820 else {
3821 lastTraced = [segment[0], sourceIndex, line, column];
3822 }
3823 tracedSegments.push(lastTraced);
3824 }
3825 mappings.push(tracedSegments);
3826 }
3827 // TODO: Make all sources relative to the sourceRoot.
3828 return defaults({
3829 mappings,
3830 names: names.array,
3831 sources: sources.array,
3832 sourcesContent,
3833 }, this.map);
3834 }
3835 /**
3836 * traceSegment is only called on children SourceMapTrees. It recurses down
3837 * into its own child SourceMapTrees, until we find the original source map.
3838 */
3839 traceSegment(line, column, name) {
3840 const { mappings, names } = this.map;
3841 // It's common for parent sourcemaps to have pointers to lines that have no
3842 // mapping (like a "//# sourceMappingURL=") at the end of the child file.
3843 if (line >= mappings.length)
3844 return null;
3845 const segments = mappings[line];
3846 if (segments.length === 0)
3847 return null;
3848 let low = 0;
3849 let high = segments.length - 1;
3850 if (line === this.lastLine) {
3851 if (column >= this.lastColumn) {
3852 low = this.lastIndex;
3853 }
3854 else {
3855 high = this.lastIndex;
3856 }
3857 }
3858 let index = binarySearch$2(segments, column, segmentComparator$1, low, high);
3859 this.lastLine = line;
3860 this.lastColumn = column;
3861 if (index === -1) {
3862 this.lastIndex = index;
3863 return null; // we come before any mapped segment
3864 }
3865 // If we can't find a segment that lines up to this column, we use the
3866 // segment before.
3867 if (index < 0) {
3868 index = ~index - 1;
3869 }
3870 this.lastIndex = index;
3871 const segment = segments[index];
3872 // 1-length segments only move the current generated column, there's no
3873 // source information to gather from it.
3874 if (segment.length === 1)
3875 return null;
3876 const source = this.sources[segment[1]];
3877 // So now we can recurse down, until we hit the original source file.
3878 return source.traceSegment(segment[2], segment[3],
3879 // A child map's recorded name for this segment takes precedence over the
3880 // parent's mapped name. Imagine a mangler changing the name over, etc.
3881 segment.length === 5 ? names[segment[4]] : name);
3882 }
3883}
3884function segmentComparator$1(segment, column) {
3885 return segment[0] - column;
3886}
3887
3888/**
3889 * Copyright 2019 The AMP HTML Authors. All Rights Reserved.
3890 *
3891 * Licensed under the Apache License, Version 2.0 (the "License");
3892 * you may not use this file except in compliance with the License.
3893 * You may obtain a copy of the License at
3894 *
3895 * http://www.apache.org/licenses/LICENSE-2.0
3896 *
3897 * Unless required by applicable law or agreed to in writing, software
3898 * distributed under the License is distributed on an "AS IS" BASIS,
3899 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3900 * See the License for the specific language governing permissions and
3901 * limitations under the License.
3902 */
3903/**
3904 * Removes the filename from a path.
3905 */
3906function stripFilename(path) {
3907 if (!path)
3908 return '';
3909 const index = path.lastIndexOf('/');
3910 return path.slice(0, index + 1);
3911}
3912
3913/**
3914 * Copyright 2019 The AMP HTML Authors. All Rights Reserved.
3915 *
3916 * Licensed under the Apache License, Version 2.0 (the "License");
3917 * you may not use this file except in compliance with the License.
3918 * You may obtain a copy of the License at
3919 *
3920 * http://www.apache.org/licenses/LICENSE-2.0
3921 *
3922 * Unless required by applicable law or agreed to in writing, software
3923 * distributed under the License is distributed on an "AS IS" BASIS,
3924 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3925 * See the License for the specific language governing permissions and
3926 * limitations under the License.
3927 */
3928function asArray(value) {
3929 if (Array.isArray(value))
3930 return value;
3931 return [value];
3932}
3933/**
3934 * Recursively builds a tree structure out of sourcemap files, with each node
3935 * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of
3936 * `OriginalSource`s and `SourceMapTree`s.
3937 *
3938 * Every sourcemap is composed of a collection of source files and mappings
3939 * into locations of those source files. When we generate a `SourceMapTree` for
3940 * the sourcemap, we attempt to load each source file's own sourcemap. If it
3941 * does not have an associated sourcemap, it is considered an original,
3942 * unmodified source file.
3943 */
3944function buildSourceMapTree(input, loader, relativeRoot) {
3945 const maps = asArray(input).map(decodeSourceMap);
3946 const map = maps.pop();
3947 for (let i = 0; i < maps.length; i++) {
3948 if (maps[i].sources.length !== 1) {
3949 throw new Error(`Transformation map ${i} must have exactly one source file.\n` +
3950 'Did you specify these with the most recent transformation maps first?');
3951 }
3952 }
3953 const { sourceRoot, sources, sourcesContent } = map;
3954 const children = sources.map((sourceFile, i) => {
3955 // Each source file is loaded relative to the sourcemap's own sourceRoot,
3956 // which is itself relative to the sourcemap's parent.
3957 const uri = resolve$1$1(sourceFile || '', resolve$1$1(sourceRoot || '', stripFilename(relativeRoot)));
3958 // Use the provided loader callback to retrieve the file's sourcemap.
3959 // TODO: We should eventually support async loading of sourcemap files.
3960 const sourceMap = loader(uri);
3961 // If there is no sourcemap, then it is an unmodified source file.
3962 if (!sourceMap) {
3963 // The source file's actual contents must be included in the sourcemap
3964 // (done when generating the sourcemap) for it to be included as a
3965 // sourceContent in the output sourcemap.
3966 const sourceContent = sourcesContent ? sourcesContent[i] : null;
3967 return new OriginalSource(uri, sourceContent);
3968 }
3969 // Else, it's a real sourcemap, and we need to recurse into it to load its
3970 // source files.
3971 return buildSourceMapTree(decodeSourceMap(sourceMap), loader, uri);
3972 });
3973 let tree = new SourceMapTree(map, children);
3974 for (let i = maps.length - 1; i >= 0; i--) {
3975 tree = new SourceMapTree(maps[i], [tree]);
3976 }
3977 return tree;
3978}
3979
3980/**
3981 * Copyright 2019 The AMP HTML Authors. All Rights Reserved.
3982 *
3983 * Licensed under the Apache License, Version 2.0 (the "License");
3984 * you may not use this file except in compliance with the License.
3985 * You may obtain a copy of the License at
3986 *
3987 * http://www.apache.org/licenses/LICENSE-2.0
3988 *
3989 * Unless required by applicable law or agreed to in writing, software
3990 * distributed under the License is distributed on an "AS IS" BASIS,
3991 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3992 * See the License for the specific language governing permissions and
3993 * limitations under the License.
3994 */
3995/**
3996 * A SourceMap v3 compatible sourcemap, which only includes fields that were
3997 * provided to it.
3998 */
3999class SourceMap$1 {
4000 constructor(map, options) {
4001 this.version = 3; // SourceMap spec says this should be first.
4002 if ('file' in map)
4003 this.file = map.file;
4004 this.mappings = options.decodedMappings ? map.mappings : encode$1(map.mappings);
4005 this.names = map.names;
4006 // TODO: We first need to make all source URIs relative to the sourceRoot
4007 // before we can support a sourceRoot.
4008 // if ('sourceRoot' in map) this.sourceRoot = map.sourceRoot;
4009 this.sources = map.sources;
4010 if (!options.excludeContent && 'sourcesContent' in map) {
4011 this.sourcesContent = map.sourcesContent;
4012 }
4013 }
4014 toString() {
4015 return JSON.stringify(this);
4016 }
4017}
4018
4019/**
4020 * Copyright 2019 The AMP HTML Authors. All Rights Reserved.
4021 *
4022 * Licensed under the Apache License, Version 2.0 (the "License");
4023 * you may not use this file except in compliance with the License.
4024 * You may obtain a copy of the License at
4025 *
4026 * http://www.apache.org/licenses/LICENSE-2.0
4027 *
4028 * Unless required by applicable law or agreed to in writing, software
4029 * distributed under the License is distributed on an "AS IS" BASIS,
4030 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4031 * See the License for the specific language governing permissions and
4032 * limitations under the License.
4033 */
4034/**
4035 * Traces through all the mappings in the root sourcemap, through the sources
4036 * (and their sourcemaps), all the way back to the original source location.
4037 *
4038 * `loader` will be called every time we encounter a source file. If it returns
4039 * a sourcemap, we will recurse into that sourcemap to continue the trace. If
4040 * it returns a falsey value, that source file is treated as an original,
4041 * unmodified source file.
4042 *
4043 * Pass `excludeContent` to exclude any self-containing source file content
4044 * from the output sourcemap.
4045 *
4046 * Pass `decodedMappings` to receive a SourceMap with decoded (instead of
4047 * VLQ encoded) mappings.
4048 */
4049function remapping(input, loader, options) {
4050 const opts = typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false };
4051 const graph = buildSourceMapTree(input, loader);
4052 return new SourceMap$1(graph.traceMappings(), opts);
4053}
4054
4055function slash$3(p) {
4056 return p.replace(/\\/g, '/');
4057}
4058// Strip valid id prefix. This is prepended to resolved Ids that are
4059// not valid browser import specifiers by the importAnalysis plugin.
4060function unwrapId$1(id) {
4061 return id.startsWith(VALID_ID_PREFIX) ? id.slice(VALID_ID_PREFIX.length) : id;
4062}
4063const flattenId = (id) => id.replace(/[\/\.]/g, '_');
4064function isBuiltin(id) {
4065 return builtinModules_1.includes(id);
4066}
4067const bareImportRE = /^[\w@](?!.*:\/\/)/;
4068const deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\//;
4069let isRunningWithYarnPnp;
4070try {
4071 isRunningWithYarnPnp = Boolean(require('pnpapi'));
4072}
4073catch { }
4074const ssrExtensions = ['.js', '.json', '.node'];
4075function resolveFrom$3(id, basedir, ssr = false) {
4076 return resolve__default.sync(id, {
4077 basedir,
4078 extensions: ssr ? ssrExtensions : DEFAULT_EXTENSIONS,
4079 // necessary to work with pnpm
4080 preserveSymlinks: isRunningWithYarnPnp || false
4081 });
4082}
4083// set in bin/vite.js
4084const filter$1 = process.env.VITE_DEBUG_FILTER;
4085const DEBUG$1 = process.env.DEBUG;
4086function createDebugger(ns, options = {}) {
4087 const log = debug$c(ns);
4088 const { onlyWhenFocused } = options;
4089 const focus = typeof onlyWhenFocused === 'string' ? onlyWhenFocused : ns;
4090 return (msg, ...args) => {
4091 if (filter$1 && !msg.includes(filter$1)) {
4092 return;
4093 }
4094 if (onlyWhenFocused && !(DEBUG$1 === null || DEBUG$1 === void 0 ? void 0 : DEBUG$1.includes(focus))) {
4095 return;
4096 }
4097 log(msg, ...args);
4098 };
4099}
4100const isWindows$4 = require$$0__default$1.platform() === 'win32';
4101const VOLUME_RE = /^[A-Z]:/i;
4102function normalizePath$4(id) {
4103 return path__default.posix.normalize(isWindows$4 ? slash$3(id) : id);
4104}
4105function fsPathFromId(id) {
4106 const fsPath = normalizePath$4(id.slice(FS_PREFIX.length));
4107 return fsPath.startsWith('/') || fsPath.match(VOLUME_RE)
4108 ? fsPath
4109 : `/${fsPath}`;
4110}
4111function ensureVolumeInPath(file) {
4112 return isWindows$4 ? path__default.resolve(file) : file;
4113}
4114const queryRE = /\?.*$/;
4115const hashRE = /#.*$/;
4116const cleanUrl = (url) => url.replace(hashRE, '').replace(queryRE, '');
4117const externalRE = /^(https?:)?\/\//;
4118const isExternalUrl = (url) => externalRE.test(url);
4119const dataUrlRE = /^\s*data:/i;
4120const isDataUrl = (url) => dataUrlRE.test(url);
4121const knownJsSrcRE = /\.((j|t)sx?|mjs|vue|marko|svelte)($|\?)/;
4122const isJSRequest = (url) => {
4123 url = cleanUrl(url);
4124 if (knownJsSrcRE.test(url)) {
4125 return true;
4126 }
4127 if (!path__default.extname(url) && !url.endsWith('/')) {
4128 return true;
4129 }
4130 return false;
4131};
4132const importQueryRE = /(\?|&)import=?(?:&|$)/;
4133const trailingSeparatorRE = /[\?&]$/;
4134const isImportRequest = (url) => importQueryRE.test(url);
4135function removeImportQuery(url) {
4136 return url.replace(importQueryRE, '$1').replace(trailingSeparatorRE, '');
4137}
4138function injectQuery(url, queryToInject) {
4139 // encode percents for consistent behavior with pathToFileURL
4140 // see #2614 for details
4141 let resolvedUrl = new require$$0$b.URL(url.replace(/%/g, '%25'), 'relative:///');
4142 if (resolvedUrl.protocol !== 'relative:') {
4143 resolvedUrl = require$$0$b.pathToFileURL(url);
4144 }
4145 let { protocol, pathname, search, hash } = resolvedUrl;
4146 if (protocol === 'file:') {
4147 pathname = pathname.slice(1);
4148 }
4149 pathname = decodeURIComponent(pathname);
4150 return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ''}${hash || ''}`;
4151}
4152const timestampRE = /\bt=\d{13}&?\b/;
4153function removeTimestampQuery(url) {
4154 return url.replace(timestampRE, '').replace(trailingSeparatorRE, '');
4155}
4156async function asyncReplace(input, re, replacer) {
4157 let match;
4158 let remaining = input;
4159 let rewritten = '';
4160 while ((match = re.exec(remaining))) {
4161 rewritten += remaining.slice(0, match.index);
4162 rewritten += await replacer(match);
4163 remaining = remaining.slice(match.index + match[0].length);
4164 }
4165 rewritten += remaining;
4166 return rewritten;
4167}
4168function timeFrom(start, subtract = 0) {
4169 const time = Date.now() - start - subtract;
4170 const timeString = (time + `ms`).padEnd(5, ' ');
4171 if (time < 10) {
4172 return source.green(timeString);
4173 }
4174 else if (time < 50) {
4175 return source.yellow(timeString);
4176 }
4177 else {
4178 return source.red(timeString);
4179 }
4180}
4181/**
4182 * pretty url for logging.
4183 */
4184function prettifyUrl(url, root) {
4185 url = removeTimestampQuery(url);
4186 const isAbsoluteFile = url.startsWith(root);
4187 if (isAbsoluteFile || url.startsWith(FS_PREFIX)) {
4188 let file = path__default.relative(root, isAbsoluteFile ? url : fsPathFromId(url));
4189 const seg = file.split('/');
4190 const npmIndex = seg.indexOf(`node_modules`);
4191 const isSourceMap = file.endsWith('.map');
4192 if (npmIndex > 0) {
4193 file = seg[npmIndex + 1];
4194 if (file.startsWith('@')) {
4195 file = `${file}/${seg[npmIndex + 2]}`;
4196 }
4197 file = `npm: ${source.dim(file)}${isSourceMap ? ` (source map)` : ``}`;
4198 }
4199 return source.dim(file);
4200 }
4201 else {
4202 return source.dim(url);
4203 }
4204}
4205function isObject$3(value) {
4206 return Object.prototype.toString.call(value) === '[object Object]';
4207}
4208function isDefined(value) {
4209 return value !== undefined && value !== null;
4210}
4211function lookupFile(dir, formats, pathOnly = false) {
4212 for (const format of formats) {
4213 const fullPath = path__default.join(dir, format);
4214 if (fs__default.existsSync(fullPath) && fs__default.statSync(fullPath).isFile()) {
4215 return pathOnly ? fullPath : fs__default.readFileSync(fullPath, 'utf-8');
4216 }
4217 }
4218 const parentDir = path__default.dirname(dir);
4219 if (parentDir !== dir) {
4220 return lookupFile(parentDir, formats, pathOnly);
4221 }
4222}
4223const splitRE = /\r?\n/;
4224const range$1 = 2;
4225function pad$1(source, n = 2) {
4226 const lines = source.split(splitRE);
4227 return lines.map((l) => ` `.repeat(n) + l).join(`\n`);
4228}
4229function posToNumber(source, pos) {
4230 if (typeof pos === 'number')
4231 return pos;
4232 const lines = source.split(splitRE);
4233 const { line, column } = pos;
4234 let start = 0;
4235 for (let i = 0; i < line - 1; i++) {
4236 start += lines[i].length + 1;
4237 }
4238 return start + column;
4239}
4240function numberToPos(source, offset) {
4241 if (typeof offset !== 'number')
4242 return offset;
4243 if (offset > source.length) {
4244 throw new Error('offset is longer than source length!');
4245 }
4246 const lines = source.split(splitRE);
4247 let counted = 0;
4248 let line = 0;
4249 let column = 0;
4250 for (; line < lines.length; line++) {
4251 const lineLength = lines[line].length + 1;
4252 if (counted + lineLength >= offset) {
4253 column = offset - counted + 1;
4254 break;
4255 }
4256 counted += lineLength;
4257 }
4258 return { line: line + 1, column };
4259}
4260function generateCodeFrame(source, start = 0, end) {
4261 start = posToNumber(source, start);
4262 end = end || start;
4263 const lines = source.split(splitRE);
4264 let count = 0;
4265 const res = [];
4266 for (let i = 0; i < lines.length; i++) {
4267 count += lines[i].length + 1;
4268 if (count >= start) {
4269 for (let j = i - range$1; j <= i + range$1 || end > count; j++) {
4270 if (j < 0 || j >= lines.length)
4271 continue;
4272 const line = j + 1;
4273 res.push(`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`);
4274 const lineLength = lines[j].length;
4275 if (j === i) {
4276 // push underline
4277 const pad = start - (count - lineLength) + 1;
4278 const length = Math.max(1, end > count ? lineLength - pad : end - start);
4279 res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
4280 }
4281 else if (j > i) {
4282 if (end > count) {
4283 const length = Math.max(Math.min(end - count, lineLength), 1);
4284 res.push(` | ` + '^'.repeat(length));
4285 }
4286 count += lineLength + 1;
4287 }
4288 }
4289 break;
4290 }
4291 }
4292 return res.join('\n');
4293}
4294function writeFile(filename, content) {
4295 const dir = path__default.dirname(filename);
4296 if (!fs__default.existsSync(dir)) {
4297 fs__default.mkdirSync(dir, { recursive: true });
4298 }
4299 fs__default.writeFileSync(filename, content);
4300}
4301/**
4302 * Delete every file and subdirectory. **The given directory must exist.**
4303 * Pass an optional `skip` array to preserve files in the root directory.
4304 */
4305function emptyDir(dir, skip) {
4306 for (const file of fs__default.readdirSync(dir)) {
4307 if (skip === null || skip === void 0 ? void 0 : skip.includes(file)) {
4308 continue;
4309 }
4310 const abs = path__default.resolve(dir, file);
4311 // baseline is Node 12 so can't use rmSync :(
4312 if (fs__default.lstatSync(abs).isDirectory()) {
4313 emptyDir(abs);
4314 fs__default.rmdirSync(abs);
4315 }
4316 else {
4317 fs__default.unlinkSync(abs);
4318 }
4319 }
4320}
4321function copyDir(srcDir, destDir) {
4322 fs__default.mkdirSync(destDir, { recursive: true });
4323 for (const file of fs__default.readdirSync(srcDir)) {
4324 const srcFile = path__default.resolve(srcDir, file);
4325 const destFile = path__default.resolve(destDir, file);
4326 const stat = fs__default.statSync(srcFile);
4327 if (stat.isDirectory()) {
4328 copyDir(srcFile, destFile);
4329 }
4330 else {
4331 fs__default.copyFileSync(srcFile, destFile);
4332 }
4333 }
4334}
4335function ensureLeadingSlash(path) {
4336 return !path.startsWith('/') ? '/' + path : path;
4337}
4338function ensureWatchedFile(watcher, file, root) {
4339 if (file &&
4340 // only need to watch if out of root
4341 !file.startsWith(root + '/') &&
4342 // some rollup plugins use null bytes for private resolved Ids
4343 !file.includes('\0') &&
4344 fs__default.existsSync(file)) {
4345 // resolve file to normalized system path
4346 watcher.add(path__default.resolve(file));
4347 }
4348}
4349const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g;
4350async function processSrcSet(srcs, replacer) {
4351 const imageCandidates = srcs
4352 .split(',')
4353 .map((s) => {
4354 const [url, descriptor] = s
4355 .replace(escapedSpaceCharacters, ' ')
4356 .trim()
4357 .split(' ', 2);
4358 return { url, descriptor };
4359 })
4360 .filter(({ url }) => !!url);
4361 const ret = await Promise.all(imageCandidates.map(async ({ url, descriptor }) => {
4362 return {
4363 url: await replacer({ url, descriptor }),
4364 descriptor
4365 };
4366 }));
4367 const url = ret.reduce((prev, { url, descriptor }, index) => {
4368 descriptor = descriptor || '';
4369 return (prev +=
4370 url + ` ${descriptor}${index === ret.length - 1 ? '' : ', '}`);
4371 }, '');
4372 return url;
4373}
4374// based on https://github.com/sveltejs/svelte/blob/abf11bb02b2afbd3e4cac509a0f70e318c306364/src/compiler/utils/mapped_code.ts#L221
4375const nullSourceMap = {
4376 names: [],
4377 sources: [],
4378 mappings: '',
4379 version: 3
4380};
4381function combineSourcemaps(filename, sourcemapList) {
4382 if (sourcemapList.length === 0 ||
4383 sourcemapList.every((m) => m.sources.length === 0)) {
4384 return { ...nullSourceMap };
4385 }
4386 let map;
4387 let mapIndex = 1;
4388 const useArrayInterface = sourcemapList.slice(0, -1).find((m) => m.sources.length !== 1) === undefined;
4389 if (useArrayInterface) {
4390 map = remapping(sourcemapList, () => null, true);
4391 }
4392 else {
4393 map = remapping(sourcemapList[0], function loader(sourcefile) {
4394 if (sourcefile === filename && sourcemapList[mapIndex]) {
4395 return sourcemapList[mapIndex++];
4396 }
4397 else {
4398 return { ...nullSourceMap };
4399 }
4400 }, true);
4401 }
4402 if (!map.file) {
4403 delete map.file;
4404 }
4405 return map;
4406}
4407function unique(arr) {
4408 return Array.from(new Set(arr));
4409}
4410function resolveHostname(optionsHost) {
4411 let host;
4412 if (optionsHost === undefined ||
4413 optionsHost === false ||
4414 optionsHost === 'localhost') {
4415 // Use a secure default
4416 host = '127.0.0.1';
4417 }
4418 else if (optionsHost === true) {
4419 // If passed --host in the CLI without arguments
4420 host = undefined; // undefined typically means 0.0.0.0 or :: (listen on all IPs)
4421 }
4422 else {
4423 host = optionsHost;
4424 }
4425 // Set host name to localhost when possible, unless the user explicitly asked for '127.0.0.1'
4426 const name = (optionsHost !== '127.0.0.1' && host === '127.0.0.1') ||
4427 host === '0.0.0.0' ||
4428 host === '::' ||
4429 host === undefined
4430 ? 'localhost'
4431 : host;
4432 return { host, name };
4433}
4434
4435/* eslint no-console: 0 */
4436const LogLevels = {
4437 silent: 0,
4438 error: 1,
4439 warn: 2,
4440 info: 3
4441};
4442let lastType;
4443let lastMsg;
4444let sameCount = 0;
4445function clearScreen() {
4446 const repeatCount = process.stdout.rows - 2;
4447 const blank = repeatCount > 0 ? '\n'.repeat(repeatCount) : '';
4448 console.log(blank);
4449 readline__default.cursorTo(process.stdout, 0, 0);
4450 readline__default.clearScreenDown(process.stdout);
4451}
4452function createLogger(level = 'info', options = {}) {
4453 const { prefix = '[vite]', allowClearScreen = true } = options;
4454 const thresh = LogLevels[level];
4455 const clear = allowClearScreen && process.stdout.isTTY && !process.env.CI
4456 ? clearScreen
4457 : () => { };
4458 function output(type, msg, options = {}) {
4459 if (thresh >= LogLevels[type]) {
4460 const method = type === 'info' ? 'log' : type;
4461 const format = () => {
4462 if (options.timestamp) {
4463 const tag = type === 'info'
4464 ? source.cyan.bold(prefix)
4465 : type === 'warn'
4466 ? source.yellow.bold(prefix)
4467 : source.red.bold(prefix);
4468 return `${source.dim(new Date().toLocaleTimeString())} ${tag} ${msg}`;
4469 }
4470 else {
4471 return msg;
4472 }
4473 };
4474 if (type === lastType && msg === lastMsg) {
4475 sameCount++;
4476 clear();
4477 console[method](format(), source.yellow(`(x${sameCount + 1})`));
4478 }
4479 else {
4480 sameCount = 0;
4481 lastMsg = msg;
4482 lastType = type;
4483 if (options.clear) {
4484 clear();
4485 }
4486 console[method](format());
4487 }
4488 }
4489 }
4490 const warnedMessages = new Set();
4491 const logger = {
4492 hasWarned: false,
4493 info(msg, opts) {
4494 output('info', msg, opts);
4495 },
4496 warn(msg, opts) {
4497 logger.hasWarned = true;
4498 output('warn', msg, opts);
4499 },
4500 warnOnce(msg, opts) {
4501 if (warnedMessages.has(msg))
4502 return;
4503 logger.hasWarned = true;
4504 output('warn', msg, opts);
4505 warnedMessages.add(msg);
4506 },
4507 error(msg, opts) {
4508 logger.hasWarned = true;
4509 output('error', msg, opts);
4510 },
4511 clearScreen(type) {
4512 if (thresh >= LogLevels[type]) {
4513 clear();
4514 }
4515 }
4516 };
4517 return logger;
4518}
4519function printServerUrls(hostname, protocol, port, base, info) {
4520 if (hostname.host === '127.0.0.1') {
4521 const url = `${protocol}://${hostname.name}:${source.bold(port)}${base}`;
4522 info(` > Local: ${source.cyan(url)}`);
4523 if (hostname.name !== '127.0.0.1') {
4524 info(` > Network: ${source.dim('use `--host` to expose')}`);
4525 }
4526 }
4527 else {
4528 Object.values(require$$0__default$1.networkInterfaces())
4529 .flatMap((nInterface) => nInterface !== null && nInterface !== void 0 ? nInterface : [])
4530 .filter((detail) => detail.family === 'IPv4')
4531 .map((detail) => {
4532 const type = detail.address.includes('127.0.0.1')
4533 ? 'Local: '
4534 : 'Network: ';
4535 const host = detail.address.replace('127.0.0.1', hostname.name);
4536 const url = `${protocol}://${host}:${source.bold(port)}${base}`;
4537 return ` > ${type} ${source.cyan(url)}`;
4538 })
4539 .forEach((msg) => info(msg));
4540 }
4541}
4542
4543const writeColors = {
4544 [0 /* JS */]: source.cyan,
4545 [1 /* CSS */]: source.magenta,
4546 [2 /* ASSET */]: source.green,
4547 [3 /* HTML */]: source.blue,
4548 [4 /* SOURCE_MAP */]: source.gray
4549};
4550function buildReporterPlugin(config) {
4551 const chunkLimit = config.build.chunkSizeWarningLimit;
4552 function isLarge(code) {
4553 // bail out on particularly large chunks
4554 return code.length / 1024 > chunkLimit;
4555 }
4556 async function getCompressedSize(code) {
4557 if (config.build.ssr || !config.build.brotliSize) {
4558 return '';
4559 }
4560 if (isLarge(code)) {
4561 return ' / brotli: skipped (large chunk)';
4562 }
4563 return ` / brotli: ${((await _default(typeof code === 'string' ? code : Buffer.from(code))) / 1024).toFixed(2)}kb`;
4564 }
4565 function printFileInfo(filePath, content, type, maxLength, compressedSize = '') {
4566 const outDir = normalizePath$4(path__default.relative(config.root, path__default.resolve(config.root, config.build.outDir))) + '/';
4567 const kbs = content.length / 1024;
4568 const sizeColor = kbs > chunkLimit ? source.yellow : source.dim;
4569 config.logger.info(`${source.gray(source.white.dim(outDir))}${writeColors[type](filePath.padEnd(maxLength + 2))} ${sizeColor(`${kbs.toFixed(2)}kb${compressedSize}`)}`);
4570 }
4571 const tty = process.stdout.isTTY && !process.env.CI;
4572 const shouldLogInfo = LogLevels[config.logLevel || 'info'] >= LogLevels.info;
4573 let hasTransformed = false;
4574 let hasRenderedChunk = false;
4575 let transformedCount = 0;
4576 let chunkCount = 0;
4577 const logTransform = throttle((id) => {
4578 writeLine(`transforming (${transformedCount}) ${source.dim(path__default.relative(config.root, id))}`);
4579 });
4580 return {
4581 name: 'vite:reporter',
4582 transform(_, id) {
4583 transformedCount++;
4584 if (shouldLogInfo) {
4585 if (!tty) {
4586 if (!hasTransformed) {
4587 config.logger.info(`transforming...`);
4588 }
4589 }
4590 else {
4591 if (id.includes(`?`))
4592 return;
4593 logTransform(id);
4594 }
4595 hasTransformed = true;
4596 }
4597 return null;
4598 },
4599 buildEnd() {
4600 if (shouldLogInfo) {
4601 if (tty) {
4602 process.stdout.clearLine(0);
4603 process.stdout.cursorTo(0);
4604 }
4605 config.logger.info(`${source.green(`✓`)} ${transformedCount} modules transformed.`);
4606 }
4607 },
4608 renderStart() {
4609 chunkCount = 0;
4610 },
4611 renderChunk() {
4612 chunkCount++;
4613 if (shouldLogInfo) {
4614 if (!tty) {
4615 if (!hasRenderedChunk) {
4616 config.logger.info('rendering chunks...');
4617 }
4618 }
4619 else {
4620 writeLine(`rendering chunks (${chunkCount})...`);
4621 }
4622 hasRenderedChunk = true;
4623 }
4624 return null;
4625 },
4626 generateBundle() {
4627 if (shouldLogInfo && tty) {
4628 process.stdout.clearLine(0);
4629 process.stdout.cursorTo(0);
4630 }
4631 },
4632 async writeBundle(_, output) {
4633 let hasLargeChunks = false;
4634 if (shouldLogInfo) {
4635 let longest = 0;
4636 for (const file in output) {
4637 const l = output[file].fileName.length;
4638 if (l > longest)
4639 longest = l;
4640 }
4641 // large chunks are deferred to be logged at the end so they are more
4642 // visible.
4643 const deferredLogs = [];
4644 await Promise.all(Object.keys(output).map(async (file) => {
4645 const chunk = output[file];
4646 if (chunk.type === 'chunk') {
4647 const log = async () => {
4648 printFileInfo(chunk.fileName, chunk.code, 0 /* JS */, longest, await getCompressedSize(chunk.code));
4649 if (chunk.map) {
4650 printFileInfo(chunk.fileName + '.map', chunk.map.toString(), 4 /* SOURCE_MAP */, longest);
4651 }
4652 };
4653 if (isLarge(chunk.code)) {
4654 hasLargeChunks = true;
4655 deferredLogs.push(log);
4656 }
4657 else {
4658 await log();
4659 }
4660 }
4661 else if (chunk.source) {
4662 const isCSS = chunk.fileName.endsWith('.css');
4663 printFileInfo(chunk.fileName, chunk.source, isCSS ? 1 /* CSS */ : 2 /* ASSET */, longest, isCSS ? await getCompressedSize(chunk.source) : undefined);
4664 }
4665 }));
4666 await Promise.all(deferredLogs.map((l) => l()));
4667 }
4668 else {
4669 hasLargeChunks = Object.keys(output).some((file) => {
4670 const chunk = output[file];
4671 return chunk.type === 'chunk' && chunk.code.length / 1024 > chunkLimit;
4672 });
4673 }
4674 if (hasLargeChunks &&
4675 config.build.minify &&
4676 !config.build.lib &&
4677 !config.build.ssr) {
4678 config.logger.warn(source.yellow(`\n(!) Some chunks are larger than ${chunkLimit}kb after minification. Consider:\n` +
4679 `- Using dynamic import() to code-split the application\n` +
4680 `- Use build.rollupOptions.output.manualChunks to improve chunking: https://rollupjs.org/guide/en/#outputmanualchunks\n` +
4681 `- Adjust chunk size limit for this warning via build.chunkSizeWarningLimit.`));
4682 }
4683 }
4684 };
4685}
4686function writeLine(output) {
4687 process.stdout.clearLine(0);
4688 process.stdout.cursorTo(0);
4689 if (output.length < process.stdout.columns) {
4690 process.stdout.write(output);
4691 }
4692 else {
4693 process.stdout.write(output.substring(0, process.stdout.columns - 1));
4694 }
4695}
4696function throttle(fn) {
4697 let timerHandle = null;
4698 return (...args) => {
4699 if (timerHandle)
4700 return;
4701 fn(...args);
4702 timerHandle = setTimeout(() => {
4703 timerHandle = null;
4704 }, 100);
4705 };
4706}
4707
4708var charToInteger = {};
4709var chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
4710for (var i$1 = 0; i$1 < chars$1.length; i$1++) {
4711 charToInteger[chars$1.charCodeAt(i$1)] = i$1;
4712}
4713function encode(decoded) {
4714 var sourceFileIndex = 0; // second field
4715 var sourceCodeLine = 0; // third field
4716 var sourceCodeColumn = 0; // fourth field
4717 var nameIndex = 0; // fifth field
4718 var mappings = '';
4719 for (var i = 0; i < decoded.length; i++) {
4720 var line = decoded[i];
4721 if (i > 0)
4722 mappings += ';';
4723 if (line.length === 0)
4724 continue;
4725 var generatedCodeColumn = 0; // first field
4726 var lineMappings = [];
4727 for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
4728 var segment = line_1[_i];
4729 var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);
4730 generatedCodeColumn = segment[0];
4731 if (segment.length > 1) {
4732 segmentMappings +=
4733 encodeInteger(segment[1] - sourceFileIndex) +
4734 encodeInteger(segment[2] - sourceCodeLine) +
4735 encodeInteger(segment[3] - sourceCodeColumn);
4736 sourceFileIndex = segment[1];
4737 sourceCodeLine = segment[2];
4738 sourceCodeColumn = segment[3];
4739 }
4740 if (segment.length === 5) {
4741 segmentMappings += encodeInteger(segment[4] - nameIndex);
4742 nameIndex = segment[4];
4743 }
4744 lineMappings.push(segmentMappings);
4745 }
4746 mappings += lineMappings.join(',');
4747 }
4748 return mappings;
4749}
4750function encodeInteger(num) {
4751 var result = '';
4752 num = num < 0 ? (-num << 1) | 1 : num << 1;
4753 do {
4754 var clamped = num & 31;
4755 num >>>= 5;
4756 if (num > 0) {
4757 clamped |= 32;
4758 }
4759 result += chars$1[clamped];
4760 } while (num > 0);
4761 return result;
4762}
4763
4764var BitSet = function BitSet(arg) {
4765 this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
4766};
4767
4768BitSet.prototype.add = function add (n) {
4769 this.bits[n >> 5] |= 1 << (n & 31);
4770};
4771
4772BitSet.prototype.has = function has (n) {
4773 return !!(this.bits[n >> 5] & (1 << (n & 31)));
4774};
4775
4776var Chunk = function Chunk(start, end, content) {
4777 this.start = start;
4778 this.end = end;
4779 this.original = content;
4780
4781 this.intro = '';
4782 this.outro = '';
4783
4784 this.content = content;
4785 this.storeName = false;
4786 this.edited = false;
4787
4788 // we make these non-enumerable, for sanity while debugging
4789 Object.defineProperties(this, {
4790 previous: { writable: true, value: null },
4791 next: { writable: true, value: null }
4792 });
4793};
4794
4795Chunk.prototype.appendLeft = function appendLeft (content) {
4796 this.outro += content;
4797};
4798
4799Chunk.prototype.appendRight = function appendRight (content) {
4800 this.intro = this.intro + content;
4801};
4802
4803Chunk.prototype.clone = function clone () {
4804 var chunk = new Chunk(this.start, this.end, this.original);
4805
4806 chunk.intro = this.intro;
4807 chunk.outro = this.outro;
4808 chunk.content = this.content;
4809 chunk.storeName = this.storeName;
4810 chunk.edited = this.edited;
4811
4812 return chunk;
4813};
4814
4815Chunk.prototype.contains = function contains (index) {
4816 return this.start < index && index < this.end;
4817};
4818
4819Chunk.prototype.eachNext = function eachNext (fn) {
4820 var chunk = this;
4821 while (chunk) {
4822 fn(chunk);
4823 chunk = chunk.next;
4824 }
4825};
4826
4827Chunk.prototype.eachPrevious = function eachPrevious (fn) {
4828 var chunk = this;
4829 while (chunk) {
4830 fn(chunk);
4831 chunk = chunk.previous;
4832 }
4833};
4834
4835Chunk.prototype.edit = function edit (content, storeName, contentOnly) {
4836 this.content = content;
4837 if (!contentOnly) {
4838 this.intro = '';
4839 this.outro = '';
4840 }
4841 this.storeName = storeName;
4842
4843 this.edited = true;
4844
4845 return this;
4846};
4847
4848Chunk.prototype.prependLeft = function prependLeft (content) {
4849 this.outro = content + this.outro;
4850};
4851
4852Chunk.prototype.prependRight = function prependRight (content) {
4853 this.intro = content + this.intro;
4854};
4855
4856Chunk.prototype.split = function split (index) {
4857 var sliceIndex = index - this.start;
4858
4859 var originalBefore = this.original.slice(0, sliceIndex);
4860 var originalAfter = this.original.slice(sliceIndex);
4861
4862 this.original = originalBefore;
4863
4864 var newChunk = new Chunk(index, this.end, originalAfter);
4865 newChunk.outro = this.outro;
4866 this.outro = '';
4867
4868 this.end = index;
4869
4870 if (this.edited) {
4871 // TODO is this block necessary?...
4872 newChunk.edit('', false);
4873 this.content = '';
4874 } else {
4875 this.content = originalBefore;
4876 }
4877
4878 newChunk.next = this.next;
4879 if (newChunk.next) { newChunk.next.previous = newChunk; }
4880 newChunk.previous = this;
4881 this.next = newChunk;
4882
4883 return newChunk;
4884};
4885
4886Chunk.prototype.toString = function toString () {
4887 return this.intro + this.content + this.outro;
4888};
4889
4890Chunk.prototype.trimEnd = function trimEnd (rx) {
4891 this.outro = this.outro.replace(rx, '');
4892 if (this.outro.length) { return true; }
4893
4894 var trimmed = this.content.replace(rx, '');
4895
4896 if (trimmed.length) {
4897 if (trimmed !== this.content) {
4898 this.split(this.start + trimmed.length).edit('', undefined, true);
4899 }
4900 return true;
4901
4902 } else {
4903 this.edit('', undefined, true);
4904
4905 this.intro = this.intro.replace(rx, '');
4906 if (this.intro.length) { return true; }
4907 }
4908};
4909
4910Chunk.prototype.trimStart = function trimStart (rx) {
4911 this.intro = this.intro.replace(rx, '');
4912 if (this.intro.length) { return true; }
4913
4914 var trimmed = this.content.replace(rx, '');
4915
4916 if (trimmed.length) {
4917 if (trimmed !== this.content) {
4918 this.split(this.end - trimmed.length);
4919 this.edit('', undefined, true);
4920 }
4921 return true;
4922
4923 } else {
4924 this.edit('', undefined, true);
4925
4926 this.outro = this.outro.replace(rx, '');
4927 if (this.outro.length) { return true; }
4928 }
4929};
4930
4931var btoa$1 = function () {
4932 throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
4933};
4934if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
4935 btoa$1 = function (str) { return window.btoa(unescape(encodeURIComponent(str))); };
4936} else if (typeof Buffer === 'function') {
4937 btoa$1 = function (str) { return Buffer.from(str, 'utf-8').toString('base64'); };
4938}
4939
4940var SourceMap = function SourceMap(properties) {
4941 this.version = 3;
4942 this.file = properties.file;
4943 this.sources = properties.sources;
4944 this.sourcesContent = properties.sourcesContent;
4945 this.names = properties.names;
4946 this.mappings = encode(properties.mappings);
4947};
4948
4949SourceMap.prototype.toString = function toString () {
4950 return JSON.stringify(this);
4951};
4952
4953SourceMap.prototype.toUrl = function toUrl () {
4954 return 'data:application/json;charset=utf-8;base64,' + btoa$1(this.toString());
4955};
4956
4957function guessIndent(code) {
4958 var lines = code.split('\n');
4959
4960 var tabbed = lines.filter(function (line) { return /^\t+/.test(line); });
4961 var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); });
4962
4963 if (tabbed.length === 0 && spaced.length === 0) {
4964 return null;
4965 }
4966
4967 // More lines tabbed than spaced? Assume tabs, and
4968 // default to tabs in the case of a tie (or nothing
4969 // to go on)
4970 if (tabbed.length >= spaced.length) {
4971 return '\t';
4972 }
4973
4974 // Otherwise, we need to guess the multiple
4975 var min = spaced.reduce(function (previous, current) {
4976 var numSpaces = /^ +/.exec(current)[0].length;
4977 return Math.min(numSpaces, previous);
4978 }, Infinity);
4979
4980 return new Array(min + 1).join(' ');
4981}
4982
4983function getRelativePath(from, to) {
4984 var fromParts = from.split(/[/\\]/);
4985 var toParts = to.split(/[/\\]/);
4986
4987 fromParts.pop(); // get dirname
4988
4989 while (fromParts[0] === toParts[0]) {
4990 fromParts.shift();
4991 toParts.shift();
4992 }
4993
4994 if (fromParts.length) {
4995 var i = fromParts.length;
4996 while (i--) { fromParts[i] = '..'; }
4997 }
4998
4999 return fromParts.concat(toParts).join('/');
5000}
5001
5002var toString$3 = Object.prototype.toString;
5003
5004function isObject$2(thing) {
5005 return toString$3.call(thing) === '[object Object]';
5006}
5007
5008function getLocator(source) {
5009 var originalLines = source.split('\n');
5010 var lineOffsets = [];
5011
5012 for (var i = 0, pos = 0; i < originalLines.length; i++) {
5013 lineOffsets.push(pos);
5014 pos += originalLines[i].length + 1;
5015 }
5016
5017 return function locate(index) {
5018 var i = 0;
5019 var j = lineOffsets.length;
5020 while (i < j) {
5021 var m = (i + j) >> 1;
5022 if (index < lineOffsets[m]) {
5023 j = m;
5024 } else {
5025 i = m + 1;
5026 }
5027 }
5028 var line = i - 1;
5029 var column = index - lineOffsets[line];
5030 return { line: line, column: column };
5031 };
5032}
5033
5034var Mappings = function Mappings(hires) {
5035 this.hires = hires;
5036 this.generatedCodeLine = 0;
5037 this.generatedCodeColumn = 0;
5038 this.raw = [];
5039 this.rawSegments = this.raw[this.generatedCodeLine] = [];
5040 this.pending = null;
5041};
5042
5043Mappings.prototype.addEdit = function addEdit (sourceIndex, content, loc, nameIndex) {
5044 if (content.length) {
5045 var segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
5046 if (nameIndex >= 0) {
5047 segment.push(nameIndex);
5048 }
5049 this.rawSegments.push(segment);
5050 } else if (this.pending) {
5051 this.rawSegments.push(this.pending);
5052 }
5053
5054 this.advance(content);
5055 this.pending = null;
5056};
5057
5058Mappings.prototype.addUneditedChunk = function addUneditedChunk (sourceIndex, chunk, original, loc, sourcemapLocations) {
5059 var originalCharIndex = chunk.start;
5060 var first = true;
5061
5062 while (originalCharIndex < chunk.end) {
5063 if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
5064 this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
5065 }
5066
5067 if (original[originalCharIndex] === '\n') {
5068 loc.line += 1;
5069 loc.column = 0;
5070 this.generatedCodeLine += 1;
5071 this.raw[this.generatedCodeLine] = this.rawSegments = [];
5072 this.generatedCodeColumn = 0;
5073 first = true;
5074 } else {
5075 loc.column += 1;
5076 this.generatedCodeColumn += 1;
5077 first = false;
5078 }
5079
5080 originalCharIndex += 1;
5081 }
5082
5083 this.pending = null;
5084};
5085
5086Mappings.prototype.advance = function advance (str) {
5087 if (!str) { return; }
5088
5089 var lines = str.split('\n');
5090
5091 if (lines.length > 1) {
5092 for (var i = 0; i < lines.length - 1; i++) {
5093 this.generatedCodeLine++;
5094 this.raw[this.generatedCodeLine] = this.rawSegments = [];
5095 }
5096 this.generatedCodeColumn = 0;
5097 }
5098
5099 this.generatedCodeColumn += lines[lines.length - 1].length;
5100};
5101
5102var n = '\n';
5103
5104var warned$1 = {
5105 insertLeft: false,
5106 insertRight: false,
5107 storeName: false
5108};
5109
5110var MagicString = function MagicString(string, options) {
5111 if ( options === void 0 ) options = {};
5112
5113 var chunk = new Chunk(0, string.length, string);
5114
5115 Object.defineProperties(this, {
5116 original: { writable: true, value: string },
5117 outro: { writable: true, value: '' },
5118 intro: { writable: true, value: '' },
5119 firstChunk: { writable: true, value: chunk },
5120 lastChunk: { writable: true, value: chunk },
5121 lastSearchedChunk: { writable: true, value: chunk },
5122 byStart: { writable: true, value: {} },
5123 byEnd: { writable: true, value: {} },
5124 filename: { writable: true, value: options.filename },
5125 indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
5126 sourcemapLocations: { writable: true, value: new BitSet() },
5127 storedNames: { writable: true, value: {} },
5128 indentStr: { writable: true, value: guessIndent(string) }
5129 });
5130
5131 this.byStart[0] = chunk;
5132 this.byEnd[string.length] = chunk;
5133};
5134
5135MagicString.prototype.addSourcemapLocation = function addSourcemapLocation (char) {
5136 this.sourcemapLocations.add(char);
5137};
5138
5139MagicString.prototype.append = function append (content) {
5140 if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
5141
5142 this.outro += content;
5143 return this;
5144};
5145
5146MagicString.prototype.appendLeft = function appendLeft (index, content) {
5147 if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
5148
5149 this._split(index);
5150
5151 var chunk = this.byEnd[index];
5152
5153 if (chunk) {
5154 chunk.appendLeft(content);
5155 } else {
5156 this.intro += content;
5157 }
5158 return this;
5159};
5160
5161MagicString.prototype.appendRight = function appendRight (index, content) {
5162 if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
5163
5164 this._split(index);
5165
5166 var chunk = this.byStart[index];
5167
5168 if (chunk) {
5169 chunk.appendRight(content);
5170 } else {
5171 this.outro += content;
5172 }
5173 return this;
5174};
5175
5176MagicString.prototype.clone = function clone () {
5177 var cloned = new MagicString(this.original, { filename: this.filename });
5178
5179 var originalChunk = this.firstChunk;
5180 var clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
5181
5182 while (originalChunk) {
5183 cloned.byStart[clonedChunk.start] = clonedChunk;
5184 cloned.byEnd[clonedChunk.end] = clonedChunk;
5185
5186 var nextOriginalChunk = originalChunk.next;
5187 var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
5188
5189 if (nextClonedChunk) {
5190 clonedChunk.next = nextClonedChunk;
5191 nextClonedChunk.previous = clonedChunk;
5192
5193 clonedChunk = nextClonedChunk;
5194 }
5195
5196 originalChunk = nextOriginalChunk;
5197 }
5198
5199 cloned.lastChunk = clonedChunk;
5200
5201 if (this.indentExclusionRanges) {
5202 cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
5203 }
5204
5205 cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
5206
5207 cloned.intro = this.intro;
5208 cloned.outro = this.outro;
5209
5210 return cloned;
5211};
5212
5213MagicString.prototype.generateDecodedMap = function generateDecodedMap (options) {
5214 var this$1$1 = this;
5215
5216 options = options || {};
5217
5218 var sourceIndex = 0;
5219 var names = Object.keys(this.storedNames);
5220 var mappings = new Mappings(options.hires);
5221
5222 var locate = getLocator(this.original);
5223
5224 if (this.intro) {
5225 mappings.advance(this.intro);
5226 }
5227
5228 this.firstChunk.eachNext(function (chunk) {
5229 var loc = locate(chunk.start);
5230
5231 if (chunk.intro.length) { mappings.advance(chunk.intro); }
5232
5233 if (chunk.edited) {
5234 mappings.addEdit(
5235 sourceIndex,
5236 chunk.content,
5237 loc,
5238 chunk.storeName ? names.indexOf(chunk.original) : -1
5239 );
5240 } else {
5241 mappings.addUneditedChunk(sourceIndex, chunk, this$1$1.original, loc, this$1$1.sourcemapLocations);
5242 }
5243
5244 if (chunk.outro.length) { mappings.advance(chunk.outro); }
5245 });
5246
5247 return {
5248 file: options.file ? options.file.split(/[/\\]/).pop() : null,
5249 sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
5250 sourcesContent: options.includeContent ? [this.original] : [null],
5251 names: names,
5252 mappings: mappings.raw
5253 };
5254};
5255
5256MagicString.prototype.generateMap = function generateMap (options) {
5257 return new SourceMap(this.generateDecodedMap(options));
5258};
5259
5260MagicString.prototype.getIndentString = function getIndentString () {
5261 return this.indentStr === null ? '\t' : this.indentStr;
5262};
5263
5264MagicString.prototype.indent = function indent (indentStr, options) {
5265 var pattern = /^[^\r\n]/gm;
5266
5267 if (isObject$2(indentStr)) {
5268 options = indentStr;
5269 indentStr = undefined;
5270 }
5271
5272 indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
5273
5274 if (indentStr === '') { return this; } // noop
5275
5276 options = options || {};
5277
5278 // Process exclusion ranges
5279 var isExcluded = {};
5280
5281 if (options.exclude) {
5282 var exclusions =
5283 typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
5284 exclusions.forEach(function (exclusion) {
5285 for (var i = exclusion[0]; i < exclusion[1]; i += 1) {
5286 isExcluded[i] = true;
5287 }
5288 });
5289 }
5290
5291 var shouldIndentNextCharacter = options.indentStart !== false;
5292 var replacer = function (match) {
5293 if (shouldIndentNextCharacter) { return ("" + indentStr + match); }
5294 shouldIndentNextCharacter = true;
5295 return match;
5296 };
5297
5298 this.intro = this.intro.replace(pattern, replacer);
5299
5300 var charIndex = 0;
5301 var chunk = this.firstChunk;
5302
5303 while (chunk) {
5304 var end = chunk.end;
5305
5306 if (chunk.edited) {
5307 if (!isExcluded[charIndex]) {
5308 chunk.content = chunk.content.replace(pattern, replacer);
5309
5310 if (chunk.content.length) {
5311 shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
5312 }
5313 }
5314 } else {
5315 charIndex = chunk.start;
5316
5317 while (charIndex < end) {
5318 if (!isExcluded[charIndex]) {
5319 var char = this.original[charIndex];
5320
5321 if (char === '\n') {
5322 shouldIndentNextCharacter = true;
5323 } else if (char !== '\r' && shouldIndentNextCharacter) {
5324 shouldIndentNextCharacter = false;
5325
5326 if (charIndex === chunk.start) {
5327 chunk.prependRight(indentStr);
5328 } else {
5329 this._splitChunk(chunk, charIndex);
5330 chunk = chunk.next;
5331 chunk.prependRight(indentStr);
5332 }
5333 }
5334 }
5335
5336 charIndex += 1;
5337 }
5338 }
5339
5340 charIndex = chunk.end;
5341 chunk = chunk.next;
5342 }
5343
5344 this.outro = this.outro.replace(pattern, replacer);
5345
5346 return this;
5347};
5348
5349MagicString.prototype.insert = function insert () {
5350 throw new Error('magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)');
5351};
5352
5353MagicString.prototype.insertLeft = function insertLeft (index, content) {
5354 if (!warned$1.insertLeft) {
5355 console.warn('magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'); // eslint-disable-line no-console
5356 warned$1.insertLeft = true;
5357 }
5358
5359 return this.appendLeft(index, content);
5360};
5361
5362MagicString.prototype.insertRight = function insertRight (index, content) {
5363 if (!warned$1.insertRight) {
5364 console.warn('magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'); // eslint-disable-line no-console
5365 warned$1.insertRight = true;
5366 }
5367
5368 return this.prependRight(index, content);
5369};
5370
5371MagicString.prototype.move = function move (start, end, index) {
5372 if (index >= start && index <= end) { throw new Error('Cannot move a selection inside itself'); }
5373
5374 this._split(start);
5375 this._split(end);
5376 this._split(index);
5377
5378 var first = this.byStart[start];
5379 var last = this.byEnd[end];
5380
5381 var oldLeft = first.previous;
5382 var oldRight = last.next;
5383
5384 var newRight = this.byStart[index];
5385 if (!newRight && last === this.lastChunk) { return this; }
5386 var newLeft = newRight ? newRight.previous : this.lastChunk;
5387
5388 if (oldLeft) { oldLeft.next = oldRight; }
5389 if (oldRight) { oldRight.previous = oldLeft; }
5390
5391 if (newLeft) { newLeft.next = first; }
5392 if (newRight) { newRight.previous = last; }
5393
5394 if (!first.previous) { this.firstChunk = last.next; }
5395 if (!last.next) {
5396 this.lastChunk = first.previous;
5397 this.lastChunk.next = null;
5398 }
5399
5400 first.previous = newLeft;
5401 last.next = newRight || null;
5402
5403 if (!newLeft) { this.firstChunk = first; }
5404 if (!newRight) { this.lastChunk = last; }
5405 return this;
5406};
5407
5408MagicString.prototype.overwrite = function overwrite (start, end, content, options) {
5409 if (typeof content !== 'string') { throw new TypeError('replacement content must be a string'); }
5410
5411 while (start < 0) { start += this.original.length; }
5412 while (end < 0) { end += this.original.length; }
5413
5414 if (end > this.original.length) { throw new Error('end is out of bounds'); }
5415 if (start === end)
5416 { throw new Error('Cannot overwrite a zero-length range – use appendLeft or prependRight instead'); }
5417
5418 this._split(start);
5419 this._split(end);
5420
5421 if (options === true) {
5422 if (!warned$1.storeName) {
5423 console.warn('The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'); // eslint-disable-line no-console
5424 warned$1.storeName = true;
5425 }
5426
5427 options = { storeName: true };
5428 }
5429 var storeName = options !== undefined ? options.storeName : false;
5430 var contentOnly = options !== undefined ? options.contentOnly : false;
5431
5432 if (storeName) {
5433 var original = this.original.slice(start, end);
5434 this.storedNames[original] = true;
5435 }
5436
5437 var first = this.byStart[start];
5438 var last = this.byEnd[end];
5439
5440 if (first) {
5441 if (end > first.end && first.next !== this.byStart[first.end]) {
5442 throw new Error('Cannot overwrite across a split point');
5443 }
5444
5445 first.edit(content, storeName, contentOnly);
5446
5447 if (first !== last) {
5448 var chunk = first.next;
5449 while (chunk !== last) {
5450 chunk.edit('', false);
5451 chunk = chunk.next;
5452 }
5453
5454 chunk.edit('', false);
5455 }
5456 } else {
5457 // must be inserting at the end
5458 var newChunk = new Chunk(start, end, '').edit(content, storeName);
5459
5460 // TODO last chunk in the array may not be the last chunk, if it's moved...
5461 last.next = newChunk;
5462 newChunk.previous = last;
5463 }
5464 return this;
5465};
5466
5467MagicString.prototype.prepend = function prepend (content) {
5468 if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
5469
5470 this.intro = content + this.intro;
5471 return this;
5472};
5473
5474MagicString.prototype.prependLeft = function prependLeft (index, content) {
5475 if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
5476
5477 this._split(index);
5478
5479 var chunk = this.byEnd[index];
5480
5481 if (chunk) {
5482 chunk.prependLeft(content);
5483 } else {
5484 this.intro = content + this.intro;
5485 }
5486 return this;
5487};
5488
5489MagicString.prototype.prependRight = function prependRight (index, content) {
5490 if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
5491
5492 this._split(index);
5493
5494 var chunk = this.byStart[index];
5495
5496 if (chunk) {
5497 chunk.prependRight(content);
5498 } else {
5499 this.outro = content + this.outro;
5500 }
5501 return this;
5502};
5503
5504MagicString.prototype.remove = function remove (start, end) {
5505 while (start < 0) { start += this.original.length; }
5506 while (end < 0) { end += this.original.length; }
5507
5508 if (start === end) { return this; }
5509
5510 if (start < 0 || end > this.original.length) { throw new Error('Character is out of bounds'); }
5511 if (start > end) { throw new Error('end must be greater than start'); }
5512
5513 this._split(start);
5514 this._split(end);
5515
5516 var chunk = this.byStart[start];
5517
5518 while (chunk) {
5519 chunk.intro = '';
5520 chunk.outro = '';
5521 chunk.edit('');
5522
5523 chunk = end > chunk.end ? this.byStart[chunk.end] : null;
5524 }
5525 return this;
5526};
5527
5528MagicString.prototype.lastChar = function lastChar () {
5529 if (this.outro.length)
5530 { return this.outro[this.outro.length - 1]; }
5531 var chunk = this.lastChunk;
5532 do {
5533 if (chunk.outro.length)
5534 { return chunk.outro[chunk.outro.length - 1]; }
5535 if (chunk.content.length)
5536 { return chunk.content[chunk.content.length - 1]; }
5537 if (chunk.intro.length)
5538 { return chunk.intro[chunk.intro.length - 1]; }
5539 } while (chunk = chunk.previous);
5540 if (this.intro.length)
5541 { return this.intro[this.intro.length - 1]; }
5542 return '';
5543};
5544
5545MagicString.prototype.lastLine = function lastLine () {
5546 var lineIndex = this.outro.lastIndexOf(n);
5547 if (lineIndex !== -1)
5548 { return this.outro.substr(lineIndex + 1); }
5549 var lineStr = this.outro;
5550 var chunk = this.lastChunk;
5551 do {
5552 if (chunk.outro.length > 0) {
5553 lineIndex = chunk.outro.lastIndexOf(n);
5554 if (lineIndex !== -1)
5555 { return chunk.outro.substr(lineIndex + 1) + lineStr; }
5556 lineStr = chunk.outro + lineStr;
5557 }
5558
5559 if (chunk.content.length > 0) {
5560 lineIndex = chunk.content.lastIndexOf(n);
5561 if (lineIndex !== -1)
5562 { return chunk.content.substr(lineIndex + 1) + lineStr; }
5563 lineStr = chunk.content + lineStr;
5564 }
5565
5566 if (chunk.intro.length > 0) {
5567 lineIndex = chunk.intro.lastIndexOf(n);
5568 if (lineIndex !== -1)
5569 { return chunk.intro.substr(lineIndex + 1) + lineStr; }
5570 lineStr = chunk.intro + lineStr;
5571 }
5572 } while (chunk = chunk.previous);
5573 lineIndex = this.intro.lastIndexOf(n);
5574 if (lineIndex !== -1)
5575 { return this.intro.substr(lineIndex + 1) + lineStr; }
5576 return this.intro + lineStr;
5577};
5578
5579MagicString.prototype.slice = function slice (start, end) {
5580 if ( start === void 0 ) start = 0;
5581 if ( end === void 0 ) end = this.original.length;
5582
5583 while (start < 0) { start += this.original.length; }
5584 while (end < 0) { end += this.original.length; }
5585
5586 var result = '';
5587
5588 // find start chunk
5589 var chunk = this.firstChunk;
5590 while (chunk && (chunk.start > start || chunk.end <= start)) {
5591 // found end chunk before start
5592 if (chunk.start < end && chunk.end >= end) {
5593 return result;
5594 }
5595
5596 chunk = chunk.next;
5597 }
5598
5599 if (chunk && chunk.edited && chunk.start !== start)
5600 { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); }
5601
5602 var startChunk = chunk;
5603 while (chunk) {
5604 if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
5605 result += chunk.intro;
5606 }
5607
5608 var containsEnd = chunk.start < end && chunk.end >= end;
5609 if (containsEnd && chunk.edited && chunk.end !== end)
5610 { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); }
5611
5612 var sliceStart = startChunk === chunk ? start - chunk.start : 0;
5613 var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
5614
5615 result += chunk.content.slice(sliceStart, sliceEnd);
5616
5617 if (chunk.outro && (!containsEnd || chunk.end === end)) {
5618 result += chunk.outro;
5619 }
5620
5621 if (containsEnd) {
5622 break;
5623 }
5624
5625 chunk = chunk.next;
5626 }
5627
5628 return result;
5629};
5630
5631// TODO deprecate this? not really very useful
5632MagicString.prototype.snip = function snip (start, end) {
5633 var clone = this.clone();
5634 clone.remove(0, start);
5635 clone.remove(end, clone.original.length);
5636
5637 return clone;
5638};
5639
5640MagicString.prototype._split = function _split (index) {
5641 if (this.byStart[index] || this.byEnd[index]) { return; }
5642
5643 var chunk = this.lastSearchedChunk;
5644 var searchForward = index > chunk.end;
5645
5646 while (chunk) {
5647 if (chunk.contains(index)) { return this._splitChunk(chunk, index); }
5648
5649 chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
5650 }
5651};
5652
5653MagicString.prototype._splitChunk = function _splitChunk (chunk, index) {
5654 if (chunk.edited && chunk.content.length) {
5655 // zero-length edited chunks are a special case (overlapping replacements)
5656 var loc = getLocator(this.original)(index);
5657 throw new Error(
5658 ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")")
5659 );
5660 }
5661
5662 var newChunk = chunk.split(index);
5663
5664 this.byEnd[index] = chunk;
5665 this.byStart[index] = newChunk;
5666 this.byEnd[newChunk.end] = newChunk;
5667
5668 if (chunk === this.lastChunk) { this.lastChunk = newChunk; }
5669
5670 this.lastSearchedChunk = chunk;
5671 return true;
5672};
5673
5674MagicString.prototype.toString = function toString () {
5675 var str = this.intro;
5676
5677 var chunk = this.firstChunk;
5678 while (chunk) {
5679 str += chunk.toString();
5680 chunk = chunk.next;
5681 }
5682
5683 return str + this.outro;
5684};
5685
5686MagicString.prototype.isEmpty = function isEmpty () {
5687 var chunk = this.firstChunk;
5688 do {
5689 if (chunk.intro.length && chunk.intro.trim() ||
5690 chunk.content.length && chunk.content.trim() ||
5691 chunk.outro.length && chunk.outro.trim())
5692 { return false; }
5693 } while (chunk = chunk.next);
5694 return true;
5695};
5696
5697MagicString.prototype.length = function length () {
5698 var chunk = this.firstChunk;
5699 var length = 0;
5700 do {
5701 length += chunk.intro.length + chunk.content.length + chunk.outro.length;
5702 } while (chunk = chunk.next);
5703 return length;
5704};
5705
5706MagicString.prototype.trimLines = function trimLines () {
5707 return this.trim('[\\r\\n]');
5708};
5709
5710MagicString.prototype.trim = function trim (charType) {
5711 return this.trimStart(charType).trimEnd(charType);
5712};
5713
5714MagicString.prototype.trimEndAborted = function trimEndAborted (charType) {
5715 var rx = new RegExp((charType || '\\s') + '+$');
5716
5717 this.outro = this.outro.replace(rx, '');
5718 if (this.outro.length) { return true; }
5719
5720 var chunk = this.lastChunk;
5721
5722 do {
5723 var end = chunk.end;
5724 var aborted = chunk.trimEnd(rx);
5725
5726 // if chunk was trimmed, we have a new lastChunk
5727 if (chunk.end !== end) {
5728 if (this.lastChunk === chunk) {
5729 this.lastChunk = chunk.next;
5730 }
5731
5732 this.byEnd[chunk.end] = chunk;
5733 this.byStart[chunk.next.start] = chunk.next;
5734 this.byEnd[chunk.next.end] = chunk.next;
5735 }
5736
5737 if (aborted) { return true; }
5738 chunk = chunk.previous;
5739 } while (chunk);
5740
5741 return false;
5742};
5743
5744MagicString.prototype.trimEnd = function trimEnd (charType) {
5745 this.trimEndAborted(charType);
5746 return this;
5747};
5748MagicString.prototype.trimStartAborted = function trimStartAborted (charType) {
5749 var rx = new RegExp('^' + (charType || '\\s') + '+');
5750
5751 this.intro = this.intro.replace(rx, '');
5752 if (this.intro.length) { return true; }
5753
5754 var chunk = this.firstChunk;
5755
5756 do {
5757 var end = chunk.end;
5758 var aborted = chunk.trimStart(rx);
5759
5760 if (chunk.end !== end) {
5761 // special case...
5762 if (chunk === this.lastChunk) { this.lastChunk = chunk.next; }
5763
5764 this.byEnd[chunk.end] = chunk;
5765 this.byStart[chunk.next.start] = chunk.next;
5766 this.byEnd[chunk.next.end] = chunk.next;
5767 }
5768
5769 if (aborted) { return true; }
5770 chunk = chunk.next;
5771 } while (chunk);
5772
5773 return false;
5774};
5775
5776MagicString.prototype.trimStart = function trimStart (charType) {
5777 this.trimStartAborted(charType);
5778 return this;
5779};
5780
5781/**
5782 * @param typeMap [Object] Map of MIME type -> Array[extensions]
5783 * @param ...
5784 */
5785function Mime$3() {
5786 this._types = Object.create(null);
5787 this._extensions = Object.create(null);
5788
5789 for (let i = 0; i < arguments.length; i++) {
5790 this.define(arguments[i]);
5791 }
5792
5793 this.define = this.define.bind(this);
5794 this.getType = this.getType.bind(this);
5795 this.getExtension = this.getExtension.bind(this);
5796}
5797
5798/**
5799 * Define mimetype -> extension mappings. Each key is a mime-type that maps
5800 * to an array of extensions associated with the type. The first extension is
5801 * used as the default extension for the type.
5802 *
5803 * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']});
5804 *
5805 * If a type declares an extension that has already been defined, an error will
5806 * be thrown. To suppress this error and force the extension to be associated
5807 * with the new type, pass `force`=true. Alternatively, you may prefix the
5808 * extension with "*" to map the type to extension, without mapping the
5809 * extension to the type.
5810 *
5811 * e.g. mime.define({'audio/wav', ['wav']}, {'audio/x-wav', ['*wav']});
5812 *
5813 *
5814 * @param map (Object) type definitions
5815 * @param force (Boolean) if true, force overriding of existing definitions
5816 */
5817Mime$3.prototype.define = function(typeMap, force) {
5818 for (let type in typeMap) {
5819 let extensions = typeMap[type].map(function(t) {
5820 return t.toLowerCase();
5821 });
5822 type = type.toLowerCase();
5823
5824 for (let i = 0; i < extensions.length; i++) {
5825 const ext = extensions[i];
5826
5827 // '*' prefix = not the preferred type for this extension. So fixup the
5828 // extension, and skip it.
5829 if (ext[0] === '*') {
5830 continue;
5831 }
5832
5833 if (!force && (ext in this._types)) {
5834 throw new Error(
5835 'Attempt to change mapping for "' + ext +
5836 '" extension from "' + this._types[ext] + '" to "' + type +
5837 '". Pass `force=true` to allow this, otherwise remove "' + ext +
5838 '" from the list of extensions for "' + type + '".'
5839 );
5840 }
5841
5842 this._types[ext] = type;
5843 }
5844
5845 // Use first extension as default
5846 if (force || !this._extensions[type]) {
5847 const ext = extensions[0];
5848 this._extensions[type] = (ext[0] !== '*') ? ext : ext.substr(1);
5849 }
5850 }
5851};
5852
5853/**
5854 * Lookup a mime type based on extension
5855 */
5856Mime$3.prototype.getType = function(path) {
5857 path = String(path);
5858 let last = path.replace(/^.*[/\\]/, '').toLowerCase();
5859 let ext = last.replace(/^.*\./, '').toLowerCase();
5860
5861 let hasPath = last.length < path.length;
5862 let hasDot = ext.length < last.length - 1;
5863
5864 return (hasDot || !hasPath) && this._types[ext] || null;
5865};
5866
5867/**
5868 * Return file extension associated with a mime type
5869 */
5870Mime$3.prototype.getExtension = function(type) {
5871 type = /^\s*([^;\s]*)/.test(type) && RegExp.$1;
5872 return type && this._extensions[type.toLowerCase()] || null;
5873};
5874
5875var Mime_1$1 = Mime$3;
5876
5877var standard$1 = {"application/andrew-inset":["ez"],"application/applixware":["aw"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cu-seeme":["cu"],"application/dash+xml":["mpd"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["ecma","es"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["js","mjs"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["mp4s","m4p"],"application/mrb-consumer+xml":["*xdf"],"application/mrb-publish+xml":["*xdf"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["*xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-signature":["asc","sig"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-error+xml":["xer"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avif":["avif"],"image/bmp":["bmp"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/stl":["stl"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["markdown","md"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]};
5878
5879let Mime$2 = Mime_1$1;
5880var lite$1 = new Mime$2(standard$1);
5881
5882const assetUrlRE = /__VITE_ASSET__([a-z\d]{8})__(?:\$_(.*?)__)?/g;
5883// urls in JS must be quoted as strings, so when replacing them we need
5884// a different regex
5885const assetUrlQuotedRE = /"__VITE_ASSET__([a-z\d]{8})__(?:\$_(.*?)__)?"/g;
5886const rawRE = /(\?|&)raw(?:&|$)/;
5887const urlRE = /(\?|&)url(?:&|$)/;
5888const chunkToEmittedAssetsMap = new WeakMap();
5889const assetCache = new WeakMap();
5890const assetHashToFilenameMap = new WeakMap();
5891// save hashes of the files that has been emitted in build watch
5892const emittedHashMap = new WeakMap();
5893/**
5894 * Also supports loading plain strings with import text from './foo.txt?raw'
5895 */
5896function assetPlugin(config) {
5897 // assetHashToFilenameMap initialization in buildStart causes getAssetFilename to return undefined
5898 assetHashToFilenameMap.set(config, new Map());
5899 return {
5900 name: 'vite:asset',
5901 buildStart() {
5902 assetCache.set(config, new Map());
5903 emittedHashMap.set(config, new Set());
5904 },
5905 resolveId(id) {
5906 if (!config.assetsInclude(cleanUrl(id))) {
5907 return;
5908 }
5909 // imports to absolute urls pointing to files in /public
5910 // will fail to resolve in the main resolver. handle them here.
5911 const publicFile = checkPublicFile(id, config);
5912 if (publicFile) {
5913 return id;
5914 }
5915 },
5916 async load(id) {
5917 if (id.startsWith('\0')) {
5918 // Rollup convention, this id should be handled by the
5919 // plugin that marked it with \0
5920 return;
5921 }
5922 // raw requests, read from disk
5923 if (rawRE.test(id)) {
5924 const file = checkPublicFile(id, config) || cleanUrl(id);
5925 // raw query, read file and return as string
5926 return `export default ${JSON.stringify(await fs$w.promises.readFile(file, 'utf-8'))}`;
5927 }
5928 if (!config.assetsInclude(cleanUrl(id)) && !urlRE.test(id)) {
5929 return;
5930 }
5931 id = id.replace(urlRE, '$1').replace(/[\?&]$/, '');
5932 const url = await fileToUrl(id, config, this);
5933 return `export default ${JSON.stringify(url)}`;
5934 },
5935 renderChunk(code, chunk) {
5936 let match;
5937 let s;
5938 while ((match = assetUrlQuotedRE.exec(code))) {
5939 s = s || (s = new MagicString(code));
5940 const [full, hash, postfix = ''] = match;
5941 // some internal plugins may still need to emit chunks (e.g. worker) so
5942 // fallback to this.getFileName for that.
5943 const file = getAssetFilename(hash, config) || this.getFileName(hash);
5944 registerAssetToChunk(chunk, file);
5945 const outputFilepath = config.base + file + postfix;
5946 s.overwrite(match.index, match.index + full.length, JSON.stringify(outputFilepath));
5947 }
5948 if (s) {
5949 return {
5950 code: s.toString(),
5951 map: config.build.sourcemap ? s.generateMap({ hires: true }) : null
5952 };
5953 }
5954 else {
5955 return null;
5956 }
5957 },
5958 generateBundle(_, bundle) {
5959 // do not emit assets for SSR build
5960 if (config.command === 'build' && config.build.ssr) {
5961 for (const file in bundle) {
5962 if (bundle[file].type === 'asset' &&
5963 !file.includes('ssr-manifest.json')) {
5964 delete bundle[file];
5965 }
5966 }
5967 }
5968 }
5969 };
5970}
5971function registerAssetToChunk(chunk, file) {
5972 let emitted = chunkToEmittedAssetsMap.get(chunk);
5973 if (!emitted) {
5974 emitted = new Set();
5975 chunkToEmittedAssetsMap.set(chunk, emitted);
5976 }
5977 emitted.add(cleanUrl(file));
5978}
5979function checkPublicFile(url, { publicDir }) {
5980 // note if the file is in /public, the resolver would have returned it
5981 // as-is so it's not going to be a fully resolved path.
5982 if (!publicDir || !url.startsWith('/')) {
5983 return;
5984 }
5985 const publicFile = path__default.join(publicDir, cleanUrl(url));
5986 if (fs__default.existsSync(publicFile)) {
5987 return publicFile;
5988 }
5989 else {
5990 return;
5991 }
5992}
5993function fileToUrl(id, config, ctx) {
5994 if (config.command === 'serve') {
5995 return fileToDevUrl(id, config);
5996 }
5997 else {
5998 return fileToBuiltUrl(id, config, ctx);
5999 }
6000}
6001function fileToDevUrl(id, config) {
6002 let rtn;
6003 if (checkPublicFile(id, config)) {
6004 // in public dir, keep the url as-is
6005 rtn = id;
6006 }
6007 else if (id.startsWith(config.root)) {
6008 // in project root, infer short public path
6009 rtn = '/' + path__default.posix.relative(config.root, id);
6010 }
6011 else {
6012 // outside of project root, use absolute fs path
6013 // (this is special handled by the serve static middleware
6014 rtn = path__default.posix.join(FS_PREFIX + id);
6015 }
6016 return config.base + rtn.replace(/^\//, '');
6017}
6018function getAssetFilename(hash, config) {
6019 var _a;
6020 return (_a = assetHashToFilenameMap.get(config)) === null || _a === void 0 ? void 0 : _a.get(hash);
6021}
6022/**
6023 * Register an asset to be emitted as part of the bundle (if necessary)
6024 * and returns the resolved public URL
6025 */
6026async function fileToBuiltUrl(id, config, pluginContext, skipPublicCheck = false) {
6027 if (!skipPublicCheck && checkPublicFile(id, config)) {
6028 return config.base + id.slice(1);
6029 }
6030 const cache = assetCache.get(config);
6031 const cached = cache.get(id);
6032 if (cached) {
6033 return cached;
6034 }
6035 const file = cleanUrl(id);
6036 const content = await fs$w.promises.readFile(file);
6037 let url;
6038 if (config.build.lib ||
6039 (!file.endsWith('.svg') &&
6040 content.length < Number(config.build.assetsInlineLimit))) {
6041 // base64 inlined as a string
6042 url = `data:${lite$1.getType(file)};base64,${content.toString('base64')}`;
6043 }
6044 else {
6045 // emit as asset
6046 // rollup supports `import.meta.ROLLUP_FILE_URL_*`, but it generates code
6047 // that uses runtime url sniffing and it can be verbose when targeting
6048 // non-module format. It also fails to cascade the asset content change
6049 // into the chunk's hash, so we have to do our own content hashing here.
6050 // https://bundlers.tooling.report/hashing/asset-cascade/
6051 // https://github.com/rollup/rollup/issues/3415
6052 const map = assetHashToFilenameMap.get(config);
6053 const contentHash = getAssetHash(content);
6054 const { search, hash } = require$$0$b.parse(id);
6055 const postfix = (search || '') + (hash || '');
6056 const basename = path__default.basename(file);
6057 const ext = path__default.extname(basename);
6058 const fileName = path__default.posix.join(config.build.assetsDir, `${basename.slice(0, -ext.length)}.${contentHash}${ext}`);
6059 if (!map.has(contentHash)) {
6060 map.set(contentHash, fileName);
6061 }
6062 const emittedSet = emittedHashMap.get(config);
6063 if (!emittedSet.has(contentHash)) {
6064 pluginContext.emitFile({
6065 fileName,
6066 type: 'asset',
6067 source: content
6068 });
6069 emittedSet.add(contentHash);
6070 }
6071 url = `__VITE_ASSET__${contentHash}__${postfix ? `$_${postfix}__` : ``}`;
6072 }
6073 cache.set(id, url);
6074 return url;
6075}
6076function getAssetHash(content) {
6077 return require$$1$2.createHash('sha256').update(content).digest('hex').slice(0, 8);
6078}
6079async function urlToBuiltUrl(url, importer, config, pluginContext) {
6080 if (checkPublicFile(url, config)) {
6081 return config.base + url.slice(1);
6082 }
6083 const file = url.startsWith('/')
6084 ? path__default.join(config.root, url)
6085 : path__default.join(path__default.dirname(importer), url);
6086 return fileToBuiltUrl(file, config, pluginContext,
6087 // skip public check since we just did it above
6088 true);
6089}
6090
6091var tasks$1 = {};
6092
6093var utils$t = {};
6094
6095var array$3 = {};
6096
6097Object.defineProperty(array$3, "__esModule", { value: true });
6098array$3.splitWhen = array$3.flatten = void 0;
6099function flatten$2(items) {
6100 return items.reduce((collection, item) => [].concat(collection, item), []);
6101}
6102array$3.flatten = flatten$2;
6103function splitWhen$1(items, predicate) {
6104 const result = [[]];
6105 let groupIndex = 0;
6106 for (const item of items) {
6107 if (predicate(item)) {
6108 groupIndex++;
6109 result[groupIndex] = [];
6110 }
6111 else {
6112 result[groupIndex].push(item);
6113 }
6114 }
6115 return result;
6116}
6117array$3.splitWhen = splitWhen$1;
6118
6119var errno$3 = {};
6120
6121Object.defineProperty(errno$3, "__esModule", { value: true });
6122errno$3.isEnoentCodeError = void 0;
6123function isEnoentCodeError$1(error) {
6124 return error.code === 'ENOENT';
6125}
6126errno$3.isEnoentCodeError = isEnoentCodeError$1;
6127
6128var fs$v = {};
6129
6130Object.defineProperty(fs$v, "__esModule", { value: true });
6131fs$v.createDirentFromStats = void 0;
6132class DirentFromStats$2 {
6133 constructor(name, stats) {
6134 this.name = name;
6135 this.isBlockDevice = stats.isBlockDevice.bind(stats);
6136 this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
6137 this.isDirectory = stats.isDirectory.bind(stats);
6138 this.isFIFO = stats.isFIFO.bind(stats);
6139 this.isFile = stats.isFile.bind(stats);
6140 this.isSocket = stats.isSocket.bind(stats);
6141 this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
6142 }
6143}
6144function createDirentFromStats$2(name, stats) {
6145 return new DirentFromStats$2(name, stats);
6146}
6147fs$v.createDirentFromStats = createDirentFromStats$2;
6148
6149var path$z = {};
6150
6151Object.defineProperty(path$z, "__esModule", { value: true });
6152path$z.removeLeadingDotSegment = path$z.escape = path$z.makeAbsolute = path$z.unixify = void 0;
6153const path$y = path__default;
6154const LEADING_DOT_SEGMENT_CHARACTERS_COUNT$1 = 2; // ./ or .\\
6155const UNESCAPED_GLOB_SYMBOLS_RE$1 = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\())/g;
6156/**
6157 * Designed to work only with simple paths: `dir\\file`.
6158 */
6159function unixify$1(filepath) {
6160 return filepath.replace(/\\/g, '/');
6161}
6162path$z.unixify = unixify$1;
6163function makeAbsolute$1(cwd, filepath) {
6164 return path$y.resolve(cwd, filepath);
6165}
6166path$z.makeAbsolute = makeAbsolute$1;
6167function escape$2(pattern) {
6168 return pattern.replace(UNESCAPED_GLOB_SYMBOLS_RE$1, '\\$2');
6169}
6170path$z.escape = escape$2;
6171function removeLeadingDotSegment$1(entry) {
6172 // We do not use `startsWith` because this is 10x slower than current implementation for some cases.
6173 // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with
6174 if (entry.charAt(0) === '.') {
6175 const secondCharactery = entry.charAt(1);
6176 if (secondCharactery === '/' || secondCharactery === '\\') {
6177 return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT$1);
6178 }
6179 }
6180 return entry;
6181}
6182path$z.removeLeadingDotSegment = removeLeadingDotSegment$1;
6183
6184var pattern$3 = {};
6185
6186/*!
6187 * is-extglob <https://github.com/jonschlinkert/is-extglob>
6188 *
6189 * Copyright (c) 2014-2016, Jon Schlinkert.
6190 * Licensed under the MIT License.
6191 */
6192
6193var isExtglob$1 = function isExtglob(str) {
6194 if (typeof str !== 'string' || str === '') {
6195 return false;
6196 }
6197
6198 var match;
6199 while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) {
6200 if (match[2]) return true;
6201 str = str.slice(match.index + match[0].length);
6202 }
6203
6204 return false;
6205};
6206
6207/*!
6208 * is-glob <https://github.com/jonschlinkert/is-glob>
6209 *
6210 * Copyright (c) 2014-2017, Jon Schlinkert.
6211 * Released under the MIT License.
6212 */
6213
6214var isExtglob = isExtglob$1;
6215var chars = { '{': '}', '(': ')', '[': ']'};
6216var strictRegex = /\\(.)|(^!|\*|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/;
6217var relaxedRegex = /\\(.)|(^!|[*?{}()[\]]|\(\?)/;
6218
6219var isGlob$2 = function isGlob(str, options) {
6220 if (typeof str !== 'string' || str === '') {
6221 return false;
6222 }
6223
6224 if (isExtglob(str)) {
6225 return true;
6226 }
6227
6228 var regex = strictRegex;
6229 var match;
6230
6231 // optionally relax regex
6232 if (options && options.strict === false) {
6233 regex = relaxedRegex;
6234 }
6235
6236 while ((match = regex.exec(str))) {
6237 if (match[2]) return true;
6238 var idx = match.index + match[0].length;
6239
6240 // if an open bracket/brace/paren is escaped,
6241 // set the index to the next closing character
6242 var open = match[1];
6243 var close = open ? chars[open] : null;
6244 if (open && close) {
6245 var n = str.indexOf(close, idx);
6246 if (n !== -1) {
6247 idx = n + 1;
6248 }
6249 }
6250
6251 str = str.slice(idx);
6252 }
6253 return false;
6254};
6255
6256var isGlob$1 = isGlob$2;
6257var pathPosixDirname = path__default.posix.dirname;
6258var isWin32 = require$$0__default$1.platform() === 'win32';
6259
6260var slash$2 = '/';
6261var backslash = /\\/g;
6262var enclosure = /[\{\[].*[\}\]]$/;
6263var globby$2 = /(^|[^\\])([\{\[]|\([^\)]+$)/;
6264var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
6265
6266/**
6267 * @param {string} str
6268 * @param {Object} opts
6269 * @param {boolean} [opts.flipBackslashes=true]
6270 * @returns {string}
6271 */
6272var globParent$3 = function globParent(str, opts) {
6273 var options = Object.assign({ flipBackslashes: true }, opts);
6274
6275 // flip windows path separators
6276 if (options.flipBackslashes && isWin32 && str.indexOf(slash$2) < 0) {
6277 str = str.replace(backslash, slash$2);
6278 }
6279
6280 // special case for strings ending in enclosure containing path separator
6281 if (enclosure.test(str)) {
6282 str += slash$2;
6283 }
6284
6285 // preserves full path in case of trailing path separator
6286 str += 'a';
6287
6288 // remove path parts that are globby
6289 do {
6290 str = pathPosixDirname(str);
6291 } while (isGlob$1(str) || globby$2.test(str));
6292
6293 // remove escape chars and return result
6294 return str.replace(escaped, '$1');
6295};
6296
6297var utils$s = {};
6298
6299(function (exports) {
6300
6301exports.isInteger = num => {
6302 if (typeof num === 'number') {
6303 return Number.isInteger(num);
6304 }
6305 if (typeof num === 'string' && num.trim() !== '') {
6306 return Number.isInteger(Number(num));
6307 }
6308 return false;
6309};
6310
6311/**
6312 * Find a node of the given type
6313 */
6314
6315exports.find = (node, type) => node.nodes.find(node => node.type === type);
6316
6317/**
6318 * Find a node of the given type
6319 */
6320
6321exports.exceedsLimit = (min, max, step = 1, limit) => {
6322 if (limit === false) return false;
6323 if (!exports.isInteger(min) || !exports.isInteger(max)) return false;
6324 return ((Number(max) - Number(min)) / Number(step)) >= limit;
6325};
6326
6327/**
6328 * Escape the given node with '\\' before node.value
6329 */
6330
6331exports.escapeNode = (block, n = 0, type) => {
6332 let node = block.nodes[n];
6333 if (!node) return;
6334
6335 if ((type && node.type === type) || node.type === 'open' || node.type === 'close') {
6336 if (node.escaped !== true) {
6337 node.value = '\\' + node.value;
6338 node.escaped = true;
6339 }
6340 }
6341};
6342
6343/**
6344 * Returns true if the given brace node should be enclosed in literal braces
6345 */
6346
6347exports.encloseBrace = node => {
6348 if (node.type !== 'brace') return false;
6349 if ((node.commas >> 0 + node.ranges >> 0) === 0) {
6350 node.invalid = true;
6351 return true;
6352 }
6353 return false;
6354};
6355
6356/**
6357 * Returns true if a brace node is invalid.
6358 */
6359
6360exports.isInvalidBrace = block => {
6361 if (block.type !== 'brace') return false;
6362 if (block.invalid === true || block.dollar) return true;
6363 if ((block.commas >> 0 + block.ranges >> 0) === 0) {
6364 block.invalid = true;
6365 return true;
6366 }
6367 if (block.open !== true || block.close !== true) {
6368 block.invalid = true;
6369 return true;
6370 }
6371 return false;
6372};
6373
6374/**
6375 * Returns true if a node is an open or close node
6376 */
6377
6378exports.isOpenOrClose = node => {
6379 if (node.type === 'open' || node.type === 'close') {
6380 return true;
6381 }
6382 return node.open === true || node.close === true;
6383};
6384
6385/**
6386 * Reduce an array of text nodes.
6387 */
6388
6389exports.reduce = nodes => nodes.reduce((acc, node) => {
6390 if (node.type === 'text') acc.push(node.value);
6391 if (node.type === 'range') node.type = 'text';
6392 return acc;
6393}, []);
6394
6395/**
6396 * Flatten an array
6397 */
6398
6399exports.flatten = (...args) => {
6400 const result = [];
6401 const flat = arr => {
6402 for (let i = 0; i < arr.length; i++) {
6403 let ele = arr[i];
6404 Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele);
6405 }
6406 return result;
6407 };
6408 flat(args);
6409 return result;
6410};
6411}(utils$s));
6412
6413const utils$r = utils$s;
6414
6415var stringify$7 = (ast, options = {}) => {
6416 let stringify = (node, parent = {}) => {
6417 let invalidBlock = options.escapeInvalid && utils$r.isInvalidBrace(parent);
6418 let invalidNode = node.invalid === true && options.escapeInvalid === true;
6419 let output = '';
6420
6421 if (node.value) {
6422 if ((invalidBlock || invalidNode) && utils$r.isOpenOrClose(node)) {
6423 return '\\' + node.value;
6424 }
6425 return node.value;
6426 }
6427
6428 if (node.value) {
6429 return node.value;
6430 }
6431
6432 if (node.nodes) {
6433 for (let child of node.nodes) {
6434 output += stringify(child);
6435 }
6436 }
6437 return output;
6438 };
6439
6440 return stringify(ast);
6441};
6442
6443/*!
6444 * is-number <https://github.com/jonschlinkert/is-number>
6445 *
6446 * Copyright (c) 2014-present, Jon Schlinkert.
6447 * Released under the MIT License.
6448 */
6449
6450var isNumber$2 = function(num) {
6451 if (typeof num === 'number') {
6452 return num - num === 0;
6453 }
6454 if (typeof num === 'string' && num.trim() !== '') {
6455 return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
6456 }
6457 return false;
6458};
6459
6460/*!
6461 * to-regex-range <https://github.com/micromatch/to-regex-range>
6462 *
6463 * Copyright (c) 2015-present, Jon Schlinkert.
6464 * Released under the MIT License.
6465 */
6466
6467const isNumber$1 = isNumber$2;
6468
6469const toRegexRange$1 = (min, max, options) => {
6470 if (isNumber$1(min) === false) {
6471 throw new TypeError('toRegexRange: expected the first argument to be a number');
6472 }
6473
6474 if (max === void 0 || min === max) {
6475 return String(min);
6476 }
6477
6478 if (isNumber$1(max) === false) {
6479 throw new TypeError('toRegexRange: expected the second argument to be a number.');
6480 }
6481
6482 let opts = { relaxZeros: true, ...options };
6483 if (typeof opts.strictZeros === 'boolean') {
6484 opts.relaxZeros = opts.strictZeros === false;
6485 }
6486
6487 let relax = String(opts.relaxZeros);
6488 let shorthand = String(opts.shorthand);
6489 let capture = String(opts.capture);
6490 let wrap = String(opts.wrap);
6491 let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;
6492
6493 if (toRegexRange$1.cache.hasOwnProperty(cacheKey)) {
6494 return toRegexRange$1.cache[cacheKey].result;
6495 }
6496
6497 let a = Math.min(min, max);
6498 let b = Math.max(min, max);
6499
6500 if (Math.abs(a - b) === 1) {
6501 let result = min + '|' + max;
6502 if (opts.capture) {
6503 return `(${result})`;
6504 }
6505 if (opts.wrap === false) {
6506 return result;
6507 }
6508 return `(?:${result})`;
6509 }
6510
6511 let isPadded = hasPadding(min) || hasPadding(max);
6512 let state = { min, max, a, b };
6513 let positives = [];
6514 let negatives = [];
6515
6516 if (isPadded) {
6517 state.isPadded = isPadded;
6518 state.maxLen = String(state.max).length;
6519 }
6520
6521 if (a < 0) {
6522 let newMin = b < 0 ? Math.abs(b) : 1;
6523 negatives = splitToPatterns(newMin, Math.abs(a), state, opts);
6524 a = state.a = 0;
6525 }
6526
6527 if (b >= 0) {
6528 positives = splitToPatterns(a, b, state, opts);
6529 }
6530
6531 state.negatives = negatives;
6532 state.positives = positives;
6533 state.result = collatePatterns(negatives, positives);
6534
6535 if (opts.capture === true) {
6536 state.result = `(${state.result})`;
6537 } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) {
6538 state.result = `(?:${state.result})`;
6539 }
6540
6541 toRegexRange$1.cache[cacheKey] = state;
6542 return state.result;
6543};
6544
6545function collatePatterns(neg, pos, options) {
6546 let onlyNegative = filterPatterns(neg, pos, '-', false) || [];
6547 let onlyPositive = filterPatterns(pos, neg, '', false) || [];
6548 let intersected = filterPatterns(neg, pos, '-?', true) || [];
6549 let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
6550 return subpatterns.join('|');
6551}
6552
6553function splitToRanges(min, max) {
6554 let nines = 1;
6555 let zeros = 1;
6556
6557 let stop = countNines(min, nines);
6558 let stops = new Set([max]);
6559
6560 while (min <= stop && stop <= max) {
6561 stops.add(stop);
6562 nines += 1;
6563 stop = countNines(min, nines);
6564 }
6565
6566 stop = countZeros(max + 1, zeros) - 1;
6567
6568 while (min < stop && stop <= max) {
6569 stops.add(stop);
6570 zeros += 1;
6571 stop = countZeros(max + 1, zeros) - 1;
6572 }
6573
6574 stops = [...stops];
6575 stops.sort(compare);
6576 return stops;
6577}
6578
6579/**
6580 * Convert a range to a regex pattern
6581 * @param {Number} `start`
6582 * @param {Number} `stop`
6583 * @return {String}
6584 */
6585
6586function rangeToPattern(start, stop, options) {
6587 if (start === stop) {
6588 return { pattern: start, count: [], digits: 0 };
6589 }
6590
6591 let zipped = zip(start, stop);
6592 let digits = zipped.length;
6593 let pattern = '';
6594 let count = 0;
6595
6596 for (let i = 0; i < digits; i++) {
6597 let [startDigit, stopDigit] = zipped[i];
6598
6599 if (startDigit === stopDigit) {
6600 pattern += startDigit;
6601
6602 } else if (startDigit !== '0' || stopDigit !== '9') {
6603 pattern += toCharacterClass(startDigit, stopDigit);
6604
6605 } else {
6606 count++;
6607 }
6608 }
6609
6610 if (count) {
6611 pattern += options.shorthand === true ? '\\d' : '[0-9]';
6612 }
6613
6614 return { pattern, count: [count], digits };
6615}
6616
6617function splitToPatterns(min, max, tok, options) {
6618 let ranges = splitToRanges(min, max);
6619 let tokens = [];
6620 let start = min;
6621 let prev;
6622
6623 for (let i = 0; i < ranges.length; i++) {
6624 let max = ranges[i];
6625 let obj = rangeToPattern(String(start), String(max), options);
6626 let zeros = '';
6627
6628 if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
6629 if (prev.count.length > 1) {
6630 prev.count.pop();
6631 }
6632
6633 prev.count.push(obj.count[0]);
6634 prev.string = prev.pattern + toQuantifier(prev.count);
6635 start = max + 1;
6636 continue;
6637 }
6638
6639 if (tok.isPadded) {
6640 zeros = padZeros(max, tok, options);
6641 }
6642
6643 obj.string = zeros + obj.pattern + toQuantifier(obj.count);
6644 tokens.push(obj);
6645 start = max + 1;
6646 prev = obj;
6647 }
6648
6649 return tokens;
6650}
6651
6652function filterPatterns(arr, comparison, prefix, intersection, options) {
6653 let result = [];
6654
6655 for (let ele of arr) {
6656 let { string } = ele;
6657
6658 // only push if _both_ are negative...
6659 if (!intersection && !contains(comparison, 'string', string)) {
6660 result.push(prefix + string);
6661 }
6662
6663 // or _both_ are positive
6664 if (intersection && contains(comparison, 'string', string)) {
6665 result.push(prefix + string);
6666 }
6667 }
6668 return result;
6669}
6670
6671/**
6672 * Zip strings
6673 */
6674
6675function zip(a, b) {
6676 let arr = [];
6677 for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);
6678 return arr;
6679}
6680
6681function compare(a, b) {
6682 return a > b ? 1 : b > a ? -1 : 0;
6683}
6684
6685function contains(arr, key, val) {
6686 return arr.some(ele => ele[key] === val);
6687}
6688
6689function countNines(min, len) {
6690 return Number(String(min).slice(0, -len) + '9'.repeat(len));
6691}
6692
6693function countZeros(integer, zeros) {
6694 return integer - (integer % Math.pow(10, zeros));
6695}
6696
6697function toQuantifier(digits) {
6698 let [start = 0, stop = ''] = digits;
6699 if (stop || start > 1) {
6700 return `{${start + (stop ? ',' + stop : '')}}`;
6701 }
6702 return '';
6703}
6704
6705function toCharacterClass(a, b, options) {
6706 return `[${a}${(b - a === 1) ? '' : '-'}${b}]`;
6707}
6708
6709function hasPadding(str) {
6710 return /^-?(0+)\d/.test(str);
6711}
6712
6713function padZeros(value, tok, options) {
6714 if (!tok.isPadded) {
6715 return value;
6716 }
6717
6718 let diff = Math.abs(tok.maxLen - String(value).length);
6719 let relax = options.relaxZeros !== false;
6720
6721 switch (diff) {
6722 case 0:
6723 return '';
6724 case 1:
6725 return relax ? '0?' : '0';
6726 case 2:
6727 return relax ? '0{0,2}' : '00';
6728 default: {
6729 return relax ? `0{0,${diff}}` : `0{${diff}}`;
6730 }
6731 }
6732}
6733
6734/**
6735 * Cache
6736 */
6737
6738toRegexRange$1.cache = {};
6739toRegexRange$1.clearCache = () => (toRegexRange$1.cache = {});
6740
6741/**
6742 * Expose `toRegexRange`
6743 */
6744
6745var toRegexRange_1 = toRegexRange$1;
6746
6747/*!
6748 * fill-range <https://github.com/jonschlinkert/fill-range>
6749 *
6750 * Copyright (c) 2014-present, Jon Schlinkert.
6751 * Licensed under the MIT License.
6752 */
6753
6754const util$9 = require$$0__default$3;
6755const toRegexRange = toRegexRange_1;
6756
6757const isObject$1 = val => val !== null && typeof val === 'object' && !Array.isArray(val);
6758
6759const transform = toNumber => {
6760 return value => toNumber === true ? Number(value) : String(value);
6761};
6762
6763const isValidValue = value => {
6764 return typeof value === 'number' || (typeof value === 'string' && value !== '');
6765};
6766
6767const isNumber = num => Number.isInteger(+num);
6768
6769const zeros = input => {
6770 let value = `${input}`;
6771 let index = -1;
6772 if (value[0] === '-') value = value.slice(1);
6773 if (value === '0') return false;
6774 while (value[++index] === '0');
6775 return index > 0;
6776};
6777
6778const stringify$6 = (start, end, options) => {
6779 if (typeof start === 'string' || typeof end === 'string') {
6780 return true;
6781 }
6782 return options.stringify === true;
6783};
6784
6785const pad = (input, maxLength, toNumber) => {
6786 if (maxLength > 0) {
6787 let dash = input[0] === '-' ? '-' : '';
6788 if (dash) input = input.slice(1);
6789 input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0'));
6790 }
6791 if (toNumber === false) {
6792 return String(input);
6793 }
6794 return input;
6795};
6796
6797const toMaxLen = (input, maxLength) => {
6798 let negative = input[0] === '-' ? '-' : '';
6799 if (negative) {
6800 input = input.slice(1);
6801 maxLength--;
6802 }
6803 while (input.length < maxLength) input = '0' + input;
6804 return negative ? ('-' + input) : input;
6805};
6806
6807const toSequence = (parts, options) => {
6808 parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
6809 parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
6810
6811 let prefix = options.capture ? '' : '?:';
6812 let positives = '';
6813 let negatives = '';
6814 let result;
6815
6816 if (parts.positives.length) {
6817 positives = parts.positives.join('|');
6818 }
6819
6820 if (parts.negatives.length) {
6821 negatives = `-(${prefix}${parts.negatives.join('|')})`;
6822 }
6823
6824 if (positives && negatives) {
6825 result = `${positives}|${negatives}`;
6826 } else {
6827 result = positives || negatives;
6828 }
6829
6830 if (options.wrap) {
6831 return `(${prefix}${result})`;
6832 }
6833
6834 return result;
6835};
6836
6837const toRange = (a, b, isNumbers, options) => {
6838 if (isNumbers) {
6839 return toRegexRange(a, b, { wrap: false, ...options });
6840 }
6841
6842 let start = String.fromCharCode(a);
6843 if (a === b) return start;
6844
6845 let stop = String.fromCharCode(b);
6846 return `[${start}-${stop}]`;
6847};
6848
6849const toRegex = (start, end, options) => {
6850 if (Array.isArray(start)) {
6851 let wrap = options.wrap === true;
6852 let prefix = options.capture ? '' : '?:';
6853 return wrap ? `(${prefix}${start.join('|')})` : start.join('|');
6854 }
6855 return toRegexRange(start, end, options);
6856};
6857
6858const rangeError = (...args) => {
6859 return new RangeError('Invalid range arguments: ' + util$9.inspect(...args));
6860};
6861
6862const invalidRange = (start, end, options) => {
6863 if (options.strictRanges === true) throw rangeError([start, end]);
6864 return [];
6865};
6866
6867const invalidStep = (step, options) => {
6868 if (options.strictRanges === true) {
6869 throw new TypeError(`Expected step "${step}" to be a number`);
6870 }
6871 return [];
6872};
6873
6874const fillNumbers = (start, end, step = 1, options = {}) => {
6875 let a = Number(start);
6876 let b = Number(end);
6877
6878 if (!Number.isInteger(a) || !Number.isInteger(b)) {
6879 if (options.strictRanges === true) throw rangeError([start, end]);
6880 return [];
6881 }
6882
6883 // fix negative zero
6884 if (a === 0) a = 0;
6885 if (b === 0) b = 0;
6886
6887 let descending = a > b;
6888 let startString = String(start);
6889 let endString = String(end);
6890 let stepString = String(step);
6891 step = Math.max(Math.abs(step), 1);
6892
6893 let padded = zeros(startString) || zeros(endString) || zeros(stepString);
6894 let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
6895 let toNumber = padded === false && stringify$6(start, end, options) === false;
6896 let format = options.transform || transform(toNumber);
6897
6898 if (options.toRegex && step === 1) {
6899 return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
6900 }
6901
6902 let parts = { negatives: [], positives: [] };
6903 let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));
6904 let range = [];
6905 let index = 0;
6906
6907 while (descending ? a >= b : a <= b) {
6908 if (options.toRegex === true && step > 1) {
6909 push(a);
6910 } else {
6911 range.push(pad(format(a, index), maxLen, toNumber));
6912 }
6913 a = descending ? a - step : a + step;
6914 index++;
6915 }
6916
6917 if (options.toRegex === true) {
6918 return step > 1
6919 ? toSequence(parts, options)
6920 : toRegex(range, null, { wrap: false, ...options });
6921 }
6922
6923 return range;
6924};
6925
6926const fillLetters = (start, end, step = 1, options = {}) => {
6927 if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) {
6928 return invalidRange(start, end, options);
6929 }
6930
6931
6932 let format = options.transform || (val => String.fromCharCode(val));
6933 let a = `${start}`.charCodeAt(0);
6934 let b = `${end}`.charCodeAt(0);
6935
6936 let descending = a > b;
6937 let min = Math.min(a, b);
6938 let max = Math.max(a, b);
6939
6940 if (options.toRegex && step === 1) {
6941 return toRange(min, max, false, options);
6942 }
6943
6944 let range = [];
6945 let index = 0;
6946
6947 while (descending ? a >= b : a <= b) {
6948 range.push(format(a, index));
6949 a = descending ? a - step : a + step;
6950 index++;
6951 }
6952
6953 if (options.toRegex === true) {
6954 return toRegex(range, null, { wrap: false, options });
6955 }
6956
6957 return range;
6958};
6959
6960const fill$2 = (start, end, step, options = {}) => {
6961 if (end == null && isValidValue(start)) {
6962 return [start];
6963 }
6964
6965 if (!isValidValue(start) || !isValidValue(end)) {
6966 return invalidRange(start, end, options);
6967 }
6968
6969 if (typeof step === 'function') {
6970 return fill$2(start, end, 1, { transform: step });
6971 }
6972
6973 if (isObject$1(step)) {
6974 return fill$2(start, end, 0, step);
6975 }
6976
6977 let opts = { ...options };
6978 if (opts.capture === true) opts.wrap = true;
6979 step = step || opts.step || 1;
6980
6981 if (!isNumber(step)) {
6982 if (step != null && !isObject$1(step)) return invalidStep(step, opts);
6983 return fill$2(start, end, 1, step);
6984 }
6985
6986 if (isNumber(start) && isNumber(end)) {
6987 return fillNumbers(start, end, step, opts);
6988 }
6989
6990 return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
6991};
6992
6993var fillRange = fill$2;
6994
6995const fill$1 = fillRange;
6996const utils$q = utils$s;
6997
6998const compile$1 = (ast, options = {}) => {
6999 let walk = (node, parent = {}) => {
7000 let invalidBlock = utils$q.isInvalidBrace(parent);
7001 let invalidNode = node.invalid === true && options.escapeInvalid === true;
7002 let invalid = invalidBlock === true || invalidNode === true;
7003 let prefix = options.escapeInvalid === true ? '\\' : '';
7004 let output = '';
7005
7006 if (node.isOpen === true) {
7007 return prefix + node.value;
7008 }
7009 if (node.isClose === true) {
7010 return prefix + node.value;
7011 }
7012
7013 if (node.type === 'open') {
7014 return invalid ? (prefix + node.value) : '(';
7015 }
7016
7017 if (node.type === 'close') {
7018 return invalid ? (prefix + node.value) : ')';
7019 }
7020
7021 if (node.type === 'comma') {
7022 return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|');
7023 }
7024
7025 if (node.value) {
7026 return node.value;
7027 }
7028
7029 if (node.nodes && node.ranges > 0) {
7030 let args = utils$q.reduce(node.nodes);
7031 let range = fill$1(...args, { ...options, wrap: false, toRegex: true });
7032
7033 if (range.length !== 0) {
7034 return args.length > 1 && range.length > 1 ? `(${range})` : range;
7035 }
7036 }
7037
7038 if (node.nodes) {
7039 for (let child of node.nodes) {
7040 output += walk(child, node);
7041 }
7042 }
7043 return output;
7044 };
7045
7046 return walk(ast);
7047};
7048
7049var compile_1 = compile$1;
7050
7051const fill = fillRange;
7052const stringify$5 = stringify$7;
7053const utils$p = utils$s;
7054
7055const append$1 = (queue = '', stash = '', enclose = false) => {
7056 let result = [];
7057
7058 queue = [].concat(queue);
7059 stash = [].concat(stash);
7060
7061 if (!stash.length) return queue;
7062 if (!queue.length) {
7063 return enclose ? utils$p.flatten(stash).map(ele => `{${ele}}`) : stash;
7064 }
7065
7066 for (let item of queue) {
7067 if (Array.isArray(item)) {
7068 for (let value of item) {
7069 result.push(append$1(value, stash, enclose));
7070 }
7071 } else {
7072 for (let ele of stash) {
7073 if (enclose === true && typeof ele === 'string') ele = `{${ele}}`;
7074 result.push(Array.isArray(ele) ? append$1(item, ele, enclose) : (item + ele));
7075 }
7076 }
7077 }
7078 return utils$p.flatten(result);
7079};
7080
7081const expand$3 = (ast, options = {}) => {
7082 let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit;
7083
7084 let walk = (node, parent = {}) => {
7085 node.queue = [];
7086
7087 let p = parent;
7088 let q = parent.queue;
7089
7090 while (p.type !== 'brace' && p.type !== 'root' && p.parent) {
7091 p = p.parent;
7092 q = p.queue;
7093 }
7094
7095 if (node.invalid || node.dollar) {
7096 q.push(append$1(q.pop(), stringify$5(node, options)));
7097 return;
7098 }
7099
7100 if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {
7101 q.push(append$1(q.pop(), ['{}']));
7102 return;
7103 }
7104
7105 if (node.nodes && node.ranges > 0) {
7106 let args = utils$p.reduce(node.nodes);
7107
7108 if (utils$p.exceedsLimit(...args, options.step, rangeLimit)) {
7109 throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
7110 }
7111
7112 let range = fill(...args, options);
7113 if (range.length === 0) {
7114 range = stringify$5(node, options);
7115 }
7116
7117 q.push(append$1(q.pop(), range));
7118 node.nodes = [];
7119 return;
7120 }
7121
7122 let enclose = utils$p.encloseBrace(node);
7123 let queue = node.queue;
7124 let block = node;
7125
7126 while (block.type !== 'brace' && block.type !== 'root' && block.parent) {
7127 block = block.parent;
7128 queue = block.queue;
7129 }
7130
7131 for (let i = 0; i < node.nodes.length; i++) {
7132 let child = node.nodes[i];
7133
7134 if (child.type === 'comma' && node.type === 'brace') {
7135 if (i === 1) queue.push('');
7136 queue.push('');
7137 continue;
7138 }
7139
7140 if (child.type === 'close') {
7141 q.push(append$1(q.pop(), queue, enclose));
7142 continue;
7143 }
7144
7145 if (child.value && child.type !== 'open') {
7146 queue.push(append$1(queue.pop(), child.value));
7147 continue;
7148 }
7149
7150 if (child.nodes) {
7151 walk(child, node);
7152 }
7153 }
7154
7155 return queue;
7156 };
7157
7158 return utils$p.flatten(walk(ast));
7159};
7160
7161var expand_1 = expand$3;
7162
7163var constants$6 = {
7164 MAX_LENGTH: 1024 * 64,
7165
7166 // Digits
7167 CHAR_0: '0', /* 0 */
7168 CHAR_9: '9', /* 9 */
7169
7170 // Alphabet chars.
7171 CHAR_UPPERCASE_A: 'A', /* A */
7172 CHAR_LOWERCASE_A: 'a', /* a */
7173 CHAR_UPPERCASE_Z: 'Z', /* Z */
7174 CHAR_LOWERCASE_Z: 'z', /* z */
7175
7176 CHAR_LEFT_PARENTHESES: '(', /* ( */
7177 CHAR_RIGHT_PARENTHESES: ')', /* ) */
7178
7179 CHAR_ASTERISK: '*', /* * */
7180
7181 // Non-alphabetic chars.
7182 CHAR_AMPERSAND: '&', /* & */
7183 CHAR_AT: '@', /* @ */
7184 CHAR_BACKSLASH: '\\', /* \ */
7185 CHAR_BACKTICK: '`', /* ` */
7186 CHAR_CARRIAGE_RETURN: '\r', /* \r */
7187 CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */
7188 CHAR_COLON: ':', /* : */
7189 CHAR_COMMA: ',', /* , */
7190 CHAR_DOLLAR: '$', /* . */
7191 CHAR_DOT: '.', /* . */
7192 CHAR_DOUBLE_QUOTE: '"', /* " */
7193 CHAR_EQUAL: '=', /* = */
7194 CHAR_EXCLAMATION_MARK: '!', /* ! */
7195 CHAR_FORM_FEED: '\f', /* \f */
7196 CHAR_FORWARD_SLASH: '/', /* / */
7197 CHAR_HASH: '#', /* # */
7198 CHAR_HYPHEN_MINUS: '-', /* - */
7199 CHAR_LEFT_ANGLE_BRACKET: '<', /* < */
7200 CHAR_LEFT_CURLY_BRACE: '{', /* { */
7201 CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */
7202 CHAR_LINE_FEED: '\n', /* \n */
7203 CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */
7204 CHAR_PERCENT: '%', /* % */
7205 CHAR_PLUS: '+', /* + */
7206 CHAR_QUESTION_MARK: '?', /* ? */
7207 CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */
7208 CHAR_RIGHT_CURLY_BRACE: '}', /* } */
7209 CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */
7210 CHAR_SEMICOLON: ';', /* ; */
7211 CHAR_SINGLE_QUOTE: '\'', /* ' */
7212 CHAR_SPACE: ' ', /* */
7213 CHAR_TAB: '\t', /* \t */
7214 CHAR_UNDERSCORE: '_', /* _ */
7215 CHAR_VERTICAL_LINE: '|', /* | */
7216 CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */
7217};
7218
7219const stringify$4 = stringify$7;
7220
7221/**
7222 * Constants
7223 */
7224
7225const {
7226 MAX_LENGTH: MAX_LENGTH$1,
7227 CHAR_BACKSLASH, /* \ */
7228 CHAR_BACKTICK, /* ` */
7229 CHAR_COMMA: CHAR_COMMA$1, /* , */
7230 CHAR_DOT: CHAR_DOT$1, /* . */
7231 CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1, /* ( */
7232 CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1, /* ) */
7233 CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1, /* { */
7234 CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1, /* } */
7235 CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1, /* [ */
7236 CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1, /* ] */
7237 CHAR_DOUBLE_QUOTE, /* " */
7238 CHAR_SINGLE_QUOTE, /* ' */
7239 CHAR_NO_BREAK_SPACE,
7240 CHAR_ZERO_WIDTH_NOBREAK_SPACE
7241} = constants$6;
7242
7243/**
7244 * parse
7245 */
7246
7247const parse$l = (input, options = {}) => {
7248 if (typeof input !== 'string') {
7249 throw new TypeError('Expected a string');
7250 }
7251
7252 let opts = options || {};
7253 let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;
7254 if (input.length > max) {
7255 throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
7256 }
7257
7258 let ast = { type: 'root', input, nodes: [] };
7259 let stack = [ast];
7260 let block = ast;
7261 let prev = ast;
7262 let brackets = 0;
7263 let length = input.length;
7264 let index = 0;
7265 let depth = 0;
7266 let value;
7267
7268 /**
7269 * Helpers
7270 */
7271
7272 const advance = () => input[index++];
7273 const push = node => {
7274 if (node.type === 'text' && prev.type === 'dot') {
7275 prev.type = 'text';
7276 }
7277
7278 if (prev && prev.type === 'text' && node.type === 'text') {
7279 prev.value += node.value;
7280 return;
7281 }
7282
7283 block.nodes.push(node);
7284 node.parent = block;
7285 node.prev = prev;
7286 prev = node;
7287 return node;
7288 };
7289
7290 push({ type: 'bos' });
7291
7292 while (index < length) {
7293 block = stack[stack.length - 1];
7294 value = advance();
7295
7296 /**
7297 * Invalid chars
7298 */
7299
7300 if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {
7301 continue;
7302 }
7303
7304 /**
7305 * Escaped chars
7306 */
7307
7308 if (value === CHAR_BACKSLASH) {
7309 push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() });
7310 continue;
7311 }
7312
7313 /**
7314 * Right square bracket (literal): ']'
7315 */
7316
7317 if (value === CHAR_RIGHT_SQUARE_BRACKET$1) {
7318 push({ type: 'text', value: '\\' + value });
7319 continue;
7320 }
7321
7322 /**
7323 * Left square bracket: '['
7324 */
7325
7326 if (value === CHAR_LEFT_SQUARE_BRACKET$1) {
7327 brackets++;
7328 let next;
7329
7330 while (index < length && (next = advance())) {
7331 value += next;
7332
7333 if (next === CHAR_LEFT_SQUARE_BRACKET$1) {
7334 brackets++;
7335 continue;
7336 }
7337
7338 if (next === CHAR_BACKSLASH) {
7339 value += advance();
7340 continue;
7341 }
7342
7343 if (next === CHAR_RIGHT_SQUARE_BRACKET$1) {
7344 brackets--;
7345
7346 if (brackets === 0) {
7347 break;
7348 }
7349 }
7350 }
7351
7352 push({ type: 'text', value });
7353 continue;
7354 }
7355
7356 /**
7357 * Parentheses
7358 */
7359
7360 if (value === CHAR_LEFT_PARENTHESES$1) {
7361 block = push({ type: 'paren', nodes: [] });
7362 stack.push(block);
7363 push({ type: 'text', value });
7364 continue;
7365 }
7366
7367 if (value === CHAR_RIGHT_PARENTHESES$1) {
7368 if (block.type !== 'paren') {
7369 push({ type: 'text', value });
7370 continue;
7371 }
7372 block = stack.pop();
7373 push({ type: 'text', value });
7374 block = stack[stack.length - 1];
7375 continue;
7376 }
7377
7378 /**
7379 * Quotes: '|"|`
7380 */
7381
7382 if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
7383 let open = value;
7384 let next;
7385
7386 if (options.keepQuotes !== true) {
7387 value = '';
7388 }
7389
7390 while (index < length && (next = advance())) {
7391 if (next === CHAR_BACKSLASH) {
7392 value += next + advance();
7393 continue;
7394 }
7395
7396 if (next === open) {
7397 if (options.keepQuotes === true) value += next;
7398 break;
7399 }
7400
7401 value += next;
7402 }
7403
7404 push({ type: 'text', value });
7405 continue;
7406 }
7407
7408 /**
7409 * Left curly brace: '{'
7410 */
7411
7412 if (value === CHAR_LEFT_CURLY_BRACE$1) {
7413 depth++;
7414
7415 let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;
7416 let brace = {
7417 type: 'brace',
7418 open: true,
7419 close: false,
7420 dollar,
7421 depth,
7422 commas: 0,
7423 ranges: 0,
7424 nodes: []
7425 };
7426
7427 block = push(brace);
7428 stack.push(block);
7429 push({ type: 'open', value });
7430 continue;
7431 }
7432
7433 /**
7434 * Right curly brace: '}'
7435 */
7436
7437 if (value === CHAR_RIGHT_CURLY_BRACE$1) {
7438 if (block.type !== 'brace') {
7439 push({ type: 'text', value });
7440 continue;
7441 }
7442
7443 let type = 'close';
7444 block = stack.pop();
7445 block.close = true;
7446
7447 push({ type, value });
7448 depth--;
7449
7450 block = stack[stack.length - 1];
7451 continue;
7452 }
7453
7454 /**
7455 * Comma: ','
7456 */
7457
7458 if (value === CHAR_COMMA$1 && depth > 0) {
7459 if (block.ranges > 0) {
7460 block.ranges = 0;
7461 let open = block.nodes.shift();
7462 block.nodes = [open, { type: 'text', value: stringify$4(block) }];
7463 }
7464
7465 push({ type: 'comma', value });
7466 block.commas++;
7467 continue;
7468 }
7469
7470 /**
7471 * Dot: '.'
7472 */
7473
7474 if (value === CHAR_DOT$1 && depth > 0 && block.commas === 0) {
7475 let siblings = block.nodes;
7476
7477 if (depth === 0 || siblings.length === 0) {
7478 push({ type: 'text', value });
7479 continue;
7480 }
7481
7482 if (prev.type === 'dot') {
7483 block.range = [];
7484 prev.value += value;
7485 prev.type = 'range';
7486
7487 if (block.nodes.length !== 3 && block.nodes.length !== 5) {
7488 block.invalid = true;
7489 block.ranges = 0;
7490 prev.type = 'text';
7491 continue;
7492 }
7493
7494 block.ranges++;
7495 block.args = [];
7496 continue;
7497 }
7498
7499 if (prev.type === 'range') {
7500 siblings.pop();
7501
7502 let before = siblings[siblings.length - 1];
7503 before.value += prev.value + value;
7504 prev = before;
7505 block.ranges--;
7506 continue;
7507 }
7508
7509 push({ type: 'dot', value });
7510 continue;
7511 }
7512
7513 /**
7514 * Text
7515 */
7516
7517 push({ type: 'text', value });
7518 }
7519
7520 // Mark imbalanced braces and brackets as invalid
7521 do {
7522 block = stack.pop();
7523
7524 if (block.type !== 'root') {
7525 block.nodes.forEach(node => {
7526 if (!node.nodes) {
7527 if (node.type === 'open') node.isOpen = true;
7528 if (node.type === 'close') node.isClose = true;
7529 if (!node.nodes) node.type = 'text';
7530 node.invalid = true;
7531 }
7532 });
7533
7534 // get the location of the block on parent.nodes (block's siblings)
7535 let parent = stack[stack.length - 1];
7536 let index = parent.nodes.indexOf(block);
7537 // replace the (invalid) block with it's nodes
7538 parent.nodes.splice(index, 1, ...block.nodes);
7539 }
7540 } while (stack.length > 0);
7541
7542 push({ type: 'eos' });
7543 return ast;
7544};
7545
7546var parse_1$2 = parse$l;
7547
7548const stringify$3 = stringify$7;
7549const compile = compile_1;
7550const expand$2 = expand_1;
7551const parse$k = parse_1$2;
7552
7553/**
7554 * Expand the given pattern or create a regex-compatible string.
7555 *
7556 * ```js
7557 * const braces = require('braces');
7558 * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
7559 * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
7560 * ```
7561 * @param {String} `str`
7562 * @param {Object} `options`
7563 * @return {String}
7564 * @api public
7565 */
7566
7567const braces$2 = (input, options = {}) => {
7568 let output = [];
7569
7570 if (Array.isArray(input)) {
7571 for (let pattern of input) {
7572 let result = braces$2.create(pattern, options);
7573 if (Array.isArray(result)) {
7574 output.push(...result);
7575 } else {
7576 output.push(result);
7577 }
7578 }
7579 } else {
7580 output = [].concat(braces$2.create(input, options));
7581 }
7582
7583 if (options && options.expand === true && options.nodupes === true) {
7584 output = [...new Set(output)];
7585 }
7586 return output;
7587};
7588
7589/**
7590 * Parse the given `str` with the given `options`.
7591 *
7592 * ```js
7593 * // braces.parse(pattern, [, options]);
7594 * const ast = braces.parse('a/{b,c}/d');
7595 * console.log(ast);
7596 * ```
7597 * @param {String} pattern Brace pattern to parse
7598 * @param {Object} options
7599 * @return {Object} Returns an AST
7600 * @api public
7601 */
7602
7603braces$2.parse = (input, options = {}) => parse$k(input, options);
7604
7605/**
7606 * Creates a braces string from an AST, or an AST node.
7607 *
7608 * ```js
7609 * const braces = require('braces');
7610 * let ast = braces.parse('foo/{a,b}/bar');
7611 * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
7612 * ```
7613 * @param {String} `input` Brace pattern or AST.
7614 * @param {Object} `options`
7615 * @return {Array} Returns an array of expanded values.
7616 * @api public
7617 */
7618
7619braces$2.stringify = (input, options = {}) => {
7620 if (typeof input === 'string') {
7621 return stringify$3(braces$2.parse(input, options), options);
7622 }
7623 return stringify$3(input, options);
7624};
7625
7626/**
7627 * Compiles a brace pattern into a regex-compatible, optimized string.
7628 * This method is called by the main [braces](#braces) function by default.
7629 *
7630 * ```js
7631 * const braces = require('braces');
7632 * console.log(braces.compile('a/{b,c}/d'));
7633 * //=> ['a/(b|c)/d']
7634 * ```
7635 * @param {String} `input` Brace pattern or AST.
7636 * @param {Object} `options`
7637 * @return {Array} Returns an array of expanded values.
7638 * @api public
7639 */
7640
7641braces$2.compile = (input, options = {}) => {
7642 if (typeof input === 'string') {
7643 input = braces$2.parse(input, options);
7644 }
7645 return compile(input, options);
7646};
7647
7648/**
7649 * Expands a brace pattern into an array. This method is called by the
7650 * main [braces](#braces) function when `options.expand` is true. Before
7651 * using this method it's recommended that you read the [performance notes](#performance))
7652 * and advantages of using [.compile](#compile) instead.
7653 *
7654 * ```js
7655 * const braces = require('braces');
7656 * console.log(braces.expand('a/{b,c}/d'));
7657 * //=> ['a/b/d', 'a/c/d'];
7658 * ```
7659 * @param {String} `pattern` Brace pattern
7660 * @param {Object} `options`
7661 * @return {Array} Returns an array of expanded values.
7662 * @api public
7663 */
7664
7665braces$2.expand = (input, options = {}) => {
7666 if (typeof input === 'string') {
7667 input = braces$2.parse(input, options);
7668 }
7669
7670 let result = expand$2(input, options);
7671
7672 // filter out empty strings if specified
7673 if (options.noempty === true) {
7674 result = result.filter(Boolean);
7675 }
7676
7677 // filter out duplicates if specified
7678 if (options.nodupes === true) {
7679 result = [...new Set(result)];
7680 }
7681
7682 return result;
7683};
7684
7685/**
7686 * Processes a brace pattern and returns either an expanded array
7687 * (if `options.expand` is true), a highly optimized regex-compatible string.
7688 * This method is called by the main [braces](#braces) function.
7689 *
7690 * ```js
7691 * const braces = require('braces');
7692 * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
7693 * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
7694 * ```
7695 * @param {String} `pattern` Brace pattern
7696 * @param {Object} `options`
7697 * @return {Array} Returns an array of expanded values.
7698 * @api public
7699 */
7700
7701braces$2.create = (input, options = {}) => {
7702 if (input === '' || input.length < 3) {
7703 return [input];
7704 }
7705
7706 return options.expand !== true
7707 ? braces$2.compile(input, options)
7708 : braces$2.expand(input, options);
7709};
7710
7711/**
7712 * Expose "braces"
7713 */
7714
7715var braces_1 = braces$2;
7716
7717var utils$o = {};
7718
7719const path$x = path__default;
7720const WIN_SLASH = '\\\\/';
7721const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
7722
7723/**
7724 * Posix glob regex
7725 */
7726
7727const DOT_LITERAL = '\\.';
7728const PLUS_LITERAL = '\\+';
7729const QMARK_LITERAL = '\\?';
7730const SLASH_LITERAL = '\\/';
7731const ONE_CHAR = '(?=.)';
7732const QMARK = '[^/]';
7733const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
7734const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
7735const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
7736const NO_DOT = `(?!${DOT_LITERAL})`;
7737const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
7738const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
7739const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
7740const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
7741const STAR$1 = `${QMARK}*?`;
7742
7743const POSIX_CHARS = {
7744 DOT_LITERAL,
7745 PLUS_LITERAL,
7746 QMARK_LITERAL,
7747 SLASH_LITERAL,
7748 ONE_CHAR,
7749 QMARK,
7750 END_ANCHOR,
7751 DOTS_SLASH,
7752 NO_DOT,
7753 NO_DOTS,
7754 NO_DOT_SLASH,
7755 NO_DOTS_SLASH,
7756 QMARK_NO_DOT,
7757 STAR: STAR$1,
7758 START_ANCHOR
7759};
7760
7761/**
7762 * Windows glob regex
7763 */
7764
7765const WINDOWS_CHARS = {
7766 ...POSIX_CHARS,
7767
7768 SLASH_LITERAL: `[${WIN_SLASH}]`,
7769 QMARK: WIN_NO_SLASH,
7770 STAR: `${WIN_NO_SLASH}*?`,
7771 DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
7772 NO_DOT: `(?!${DOT_LITERAL})`,
7773 NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
7774 NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
7775 NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
7776 QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
7777 START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
7778 END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
7779};
7780
7781/**
7782 * POSIX Bracket Regex
7783 */
7784
7785const POSIX_REGEX_SOURCE$1 = {
7786 alnum: 'a-zA-Z0-9',
7787 alpha: 'a-zA-Z',
7788 ascii: '\\x00-\\x7F',
7789 blank: ' \\t',
7790 cntrl: '\\x00-\\x1F\\x7F',
7791 digit: '0-9',
7792 graph: '\\x21-\\x7E',
7793 lower: 'a-z',
7794 print: '\\x20-\\x7E ',
7795 punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
7796 space: ' \\t\\r\\n\\v\\f',
7797 upper: 'A-Z',
7798 word: 'A-Za-z0-9_',
7799 xdigit: 'A-Fa-f0-9'
7800};
7801
7802var constants$5 = {
7803 MAX_LENGTH: 1024 * 64,
7804 POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
7805
7806 // regular expressions
7807 REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
7808 REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
7809 REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
7810 REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
7811 REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
7812 REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
7813
7814 // Replace globs with equivalent patterns to reduce parsing time.
7815 REPLACEMENTS: {
7816 '***': '*',
7817 '**/**': '**',
7818 '**/**/**': '**'
7819 },
7820
7821 // Digits
7822 CHAR_0: 48, /* 0 */
7823 CHAR_9: 57, /* 9 */
7824
7825 // Alphabet chars.
7826 CHAR_UPPERCASE_A: 65, /* A */
7827 CHAR_LOWERCASE_A: 97, /* a */
7828 CHAR_UPPERCASE_Z: 90, /* Z */
7829 CHAR_LOWERCASE_Z: 122, /* z */
7830
7831 CHAR_LEFT_PARENTHESES: 40, /* ( */
7832 CHAR_RIGHT_PARENTHESES: 41, /* ) */
7833
7834 CHAR_ASTERISK: 42, /* * */
7835
7836 // Non-alphabetic chars.
7837 CHAR_AMPERSAND: 38, /* & */
7838 CHAR_AT: 64, /* @ */
7839 CHAR_BACKWARD_SLASH: 92, /* \ */
7840 CHAR_CARRIAGE_RETURN: 13, /* \r */
7841 CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
7842 CHAR_COLON: 58, /* : */
7843 CHAR_COMMA: 44, /* , */
7844 CHAR_DOT: 46, /* . */
7845 CHAR_DOUBLE_QUOTE: 34, /* " */
7846 CHAR_EQUAL: 61, /* = */
7847 CHAR_EXCLAMATION_MARK: 33, /* ! */
7848 CHAR_FORM_FEED: 12, /* \f */
7849 CHAR_FORWARD_SLASH: 47, /* / */
7850 CHAR_GRAVE_ACCENT: 96, /* ` */
7851 CHAR_HASH: 35, /* # */
7852 CHAR_HYPHEN_MINUS: 45, /* - */
7853 CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
7854 CHAR_LEFT_CURLY_BRACE: 123, /* { */
7855 CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
7856 CHAR_LINE_FEED: 10, /* \n */
7857 CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
7858 CHAR_PERCENT: 37, /* % */
7859 CHAR_PLUS: 43, /* + */
7860 CHAR_QUESTION_MARK: 63, /* ? */
7861 CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
7862 CHAR_RIGHT_CURLY_BRACE: 125, /* } */
7863 CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
7864 CHAR_SEMICOLON: 59, /* ; */
7865 CHAR_SINGLE_QUOTE: 39, /* ' */
7866 CHAR_SPACE: 32, /* */
7867 CHAR_TAB: 9, /* \t */
7868 CHAR_UNDERSCORE: 95, /* _ */
7869 CHAR_VERTICAL_LINE: 124, /* | */
7870 CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
7871
7872 SEP: path$x.sep,
7873
7874 /**
7875 * Create EXTGLOB_CHARS
7876 */
7877
7878 extglobChars(chars) {
7879 return {
7880 '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
7881 '?': { type: 'qmark', open: '(?:', close: ')?' },
7882 '+': { type: 'plus', open: '(?:', close: ')+' },
7883 '*': { type: 'star', open: '(?:', close: ')*' },
7884 '@': { type: 'at', open: '(?:', close: ')' }
7885 };
7886 },
7887
7888 /**
7889 * Create GLOB_CHARS
7890 */
7891
7892 globChars(win32) {
7893 return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
7894 }
7895};
7896
7897(function (exports) {
7898
7899const path = path__default;
7900const win32 = process.platform === 'win32';
7901const {
7902 REGEX_BACKSLASH,
7903 REGEX_REMOVE_BACKSLASH,
7904 REGEX_SPECIAL_CHARS,
7905 REGEX_SPECIAL_CHARS_GLOBAL
7906} = constants$5;
7907
7908exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
7909exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
7910exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
7911exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
7912exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
7913
7914exports.removeBackslashes = str => {
7915 return str.replace(REGEX_REMOVE_BACKSLASH, match => {
7916 return match === '\\' ? '' : match;
7917 });
7918};
7919
7920exports.supportsLookbehinds = () => {
7921 const segs = process.version.slice(1).split('.').map(Number);
7922 if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
7923 return true;
7924 }
7925 return false;
7926};
7927
7928exports.isWindows = options => {
7929 if (options && typeof options.windows === 'boolean') {
7930 return options.windows;
7931 }
7932 return win32 === true || path.sep === '\\';
7933};
7934
7935exports.escapeLast = (input, char, lastIdx) => {
7936 const idx = input.lastIndexOf(char, lastIdx);
7937 if (idx === -1) return input;
7938 if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
7939 return `${input.slice(0, idx)}\\${input.slice(idx)}`;
7940};
7941
7942exports.removePrefix = (input, state = {}) => {
7943 let output = input;
7944 if (output.startsWith('./')) {
7945 output = output.slice(2);
7946 state.prefix = './';
7947 }
7948 return output;
7949};
7950
7951exports.wrapOutput = (input, state = {}, options = {}) => {
7952 const prepend = options.contains ? '' : '^';
7953 const append = options.contains ? '' : '$';
7954
7955 let output = `${prepend}(?:${input})${append}`;
7956 if (state.negated === true) {
7957 output = `(?:^(?!${output}).*$)`;
7958 }
7959 return output;
7960};
7961}(utils$o));
7962
7963const utils$n = utils$o;
7964const {
7965 CHAR_ASTERISK, /* * */
7966 CHAR_AT, /* @ */
7967 CHAR_BACKWARD_SLASH, /* \ */
7968 CHAR_COMMA, /* , */
7969 CHAR_DOT, /* . */
7970 CHAR_EXCLAMATION_MARK, /* ! */
7971 CHAR_FORWARD_SLASH, /* / */
7972 CHAR_LEFT_CURLY_BRACE, /* { */
7973 CHAR_LEFT_PARENTHESES, /* ( */
7974 CHAR_LEFT_SQUARE_BRACKET, /* [ */
7975 CHAR_PLUS, /* + */
7976 CHAR_QUESTION_MARK, /* ? */
7977 CHAR_RIGHT_CURLY_BRACE, /* } */
7978 CHAR_RIGHT_PARENTHESES, /* ) */
7979 CHAR_RIGHT_SQUARE_BRACKET /* ] */
7980} = constants$5;
7981
7982const isPathSeparator = code => {
7983 return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
7984};
7985
7986const depth = token => {
7987 if (token.isPrefix !== true) {
7988 token.depth = token.isGlobstar ? Infinity : 1;
7989 }
7990};
7991
7992/**
7993 * Quickly scans a glob pattern and returns an object with a handful of
7994 * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
7995 * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
7996 * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
7997 *
7998 * ```js
7999 * const pm = require('picomatch');
8000 * console.log(pm.scan('foo/bar/*.js'));
8001 * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
8002 * ```
8003 * @param {String} `str`
8004 * @param {Object} `options`
8005 * @return {Object} Returns an object with tokens and regex source string.
8006 * @api public
8007 */
8008
8009const scan$1 = (input, options) => {
8010 const opts = options || {};
8011
8012 const length = input.length - 1;
8013 const scanToEnd = opts.parts === true || opts.scanToEnd === true;
8014 const slashes = [];
8015 const tokens = [];
8016 const parts = [];
8017
8018 let str = input;
8019 let index = -1;
8020 let start = 0;
8021 let lastIndex = 0;
8022 let isBrace = false;
8023 let isBracket = false;
8024 let isGlob = false;
8025 let isExtglob = false;
8026 let isGlobstar = false;
8027 let braceEscaped = false;
8028 let backslashes = false;
8029 let negated = false;
8030 let negatedExtglob = false;
8031 let finished = false;
8032 let braces = 0;
8033 let prev;
8034 let code;
8035 let token = { value: '', depth: 0, isGlob: false };
8036
8037 const eos = () => index >= length;
8038 const peek = () => str.charCodeAt(index + 1);
8039 const advance = () => {
8040 prev = code;
8041 return str.charCodeAt(++index);
8042 };
8043
8044 while (index < length) {
8045 code = advance();
8046 let next;
8047
8048 if (code === CHAR_BACKWARD_SLASH) {
8049 backslashes = token.backslashes = true;
8050 code = advance();
8051
8052 if (code === CHAR_LEFT_CURLY_BRACE) {
8053 braceEscaped = true;
8054 }
8055 continue;
8056 }
8057
8058 if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
8059 braces++;
8060
8061 while (eos() !== true && (code = advance())) {
8062 if (code === CHAR_BACKWARD_SLASH) {
8063 backslashes = token.backslashes = true;
8064 advance();
8065 continue;
8066 }
8067
8068 if (code === CHAR_LEFT_CURLY_BRACE) {
8069 braces++;
8070 continue;
8071 }
8072
8073 if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
8074 isBrace = token.isBrace = true;
8075 isGlob = token.isGlob = true;
8076 finished = true;
8077
8078 if (scanToEnd === true) {
8079 continue;
8080 }
8081
8082 break;
8083 }
8084
8085 if (braceEscaped !== true && code === CHAR_COMMA) {
8086 isBrace = token.isBrace = true;
8087 isGlob = token.isGlob = true;
8088 finished = true;
8089
8090 if (scanToEnd === true) {
8091 continue;
8092 }
8093
8094 break;
8095 }
8096
8097 if (code === CHAR_RIGHT_CURLY_BRACE) {
8098 braces--;
8099
8100 if (braces === 0) {
8101 braceEscaped = false;
8102 isBrace = token.isBrace = true;
8103 finished = true;
8104 break;
8105 }
8106 }
8107 }
8108
8109 if (scanToEnd === true) {
8110 continue;
8111 }
8112
8113 break;
8114 }
8115
8116 if (code === CHAR_FORWARD_SLASH) {
8117 slashes.push(index);
8118 tokens.push(token);
8119 token = { value: '', depth: 0, isGlob: false };
8120
8121 if (finished === true) continue;
8122 if (prev === CHAR_DOT && index === (start + 1)) {
8123 start += 2;
8124 continue;
8125 }
8126
8127 lastIndex = index + 1;
8128 continue;
8129 }
8130
8131 if (opts.noext !== true) {
8132 const isExtglobChar = code === CHAR_PLUS
8133 || code === CHAR_AT
8134 || code === CHAR_ASTERISK
8135 || code === CHAR_QUESTION_MARK
8136 || code === CHAR_EXCLAMATION_MARK;
8137
8138 if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
8139 isGlob = token.isGlob = true;
8140 isExtglob = token.isExtglob = true;
8141 finished = true;
8142 if (code === CHAR_EXCLAMATION_MARK && index === start) {
8143 negatedExtglob = true;
8144 }
8145
8146 if (scanToEnd === true) {
8147 while (eos() !== true && (code = advance())) {
8148 if (code === CHAR_BACKWARD_SLASH) {
8149 backslashes = token.backslashes = true;
8150 code = advance();
8151 continue;
8152 }
8153
8154 if (code === CHAR_RIGHT_PARENTHESES) {
8155 isGlob = token.isGlob = true;
8156 finished = true;
8157 break;
8158 }
8159 }
8160 continue;
8161 }
8162 break;
8163 }
8164 }
8165
8166 if (code === CHAR_ASTERISK) {
8167 if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
8168 isGlob = token.isGlob = true;
8169 finished = true;
8170
8171 if (scanToEnd === true) {
8172 continue;
8173 }
8174 break;
8175 }
8176
8177 if (code === CHAR_QUESTION_MARK) {
8178 isGlob = token.isGlob = true;
8179 finished = true;
8180
8181 if (scanToEnd === true) {
8182 continue;
8183 }
8184 break;
8185 }
8186
8187 if (code === CHAR_LEFT_SQUARE_BRACKET) {
8188 while (eos() !== true && (next = advance())) {
8189 if (next === CHAR_BACKWARD_SLASH) {
8190 backslashes = token.backslashes = true;
8191 advance();
8192 continue;
8193 }
8194
8195 if (next === CHAR_RIGHT_SQUARE_BRACKET) {
8196 isBracket = token.isBracket = true;
8197 isGlob = token.isGlob = true;
8198 finished = true;
8199 break;
8200 }
8201 }
8202
8203 if (scanToEnd === true) {
8204 continue;
8205 }
8206
8207 break;
8208 }
8209
8210 if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
8211 negated = token.negated = true;
8212 start++;
8213 continue;
8214 }
8215
8216 if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
8217 isGlob = token.isGlob = true;
8218
8219 if (scanToEnd === true) {
8220 while (eos() !== true && (code = advance())) {
8221 if (code === CHAR_LEFT_PARENTHESES) {
8222 backslashes = token.backslashes = true;
8223 code = advance();
8224 continue;
8225 }
8226
8227 if (code === CHAR_RIGHT_PARENTHESES) {
8228 finished = true;
8229 break;
8230 }
8231 }
8232 continue;
8233 }
8234 break;
8235 }
8236
8237 if (isGlob === true) {
8238 finished = true;
8239
8240 if (scanToEnd === true) {
8241 continue;
8242 }
8243
8244 break;
8245 }
8246 }
8247
8248 if (opts.noext === true) {
8249 isExtglob = false;
8250 isGlob = false;
8251 }
8252
8253 let base = str;
8254 let prefix = '';
8255 let glob = '';
8256
8257 if (start > 0) {
8258 prefix = str.slice(0, start);
8259 str = str.slice(start);
8260 lastIndex -= start;
8261 }
8262
8263 if (base && isGlob === true && lastIndex > 0) {
8264 base = str.slice(0, lastIndex);
8265 glob = str.slice(lastIndex);
8266 } else if (isGlob === true) {
8267 base = '';
8268 glob = str;
8269 } else {
8270 base = str;
8271 }
8272
8273 if (base && base !== '' && base !== '/' && base !== str) {
8274 if (isPathSeparator(base.charCodeAt(base.length - 1))) {
8275 base = base.slice(0, -1);
8276 }
8277 }
8278
8279 if (opts.unescape === true) {
8280 if (glob) glob = utils$n.removeBackslashes(glob);
8281
8282 if (base && backslashes === true) {
8283 base = utils$n.removeBackslashes(base);
8284 }
8285 }
8286
8287 const state = {
8288 prefix,
8289 input,
8290 start,
8291 base,
8292 glob,
8293 isBrace,
8294 isBracket,
8295 isGlob,
8296 isExtglob,
8297 isGlobstar,
8298 negated,
8299 negatedExtglob
8300 };
8301
8302 if (opts.tokens === true) {
8303 state.maxDepth = 0;
8304 if (!isPathSeparator(code)) {
8305 tokens.push(token);
8306 }
8307 state.tokens = tokens;
8308 }
8309
8310 if (opts.parts === true || opts.tokens === true) {
8311 let prevIndex;
8312
8313 for (let idx = 0; idx < slashes.length; idx++) {
8314 const n = prevIndex ? prevIndex + 1 : start;
8315 const i = slashes[idx];
8316 const value = input.slice(n, i);
8317 if (opts.tokens) {
8318 if (idx === 0 && start !== 0) {
8319 tokens[idx].isPrefix = true;
8320 tokens[idx].value = prefix;
8321 } else {
8322 tokens[idx].value = value;
8323 }
8324 depth(tokens[idx]);
8325 state.maxDepth += tokens[idx].depth;
8326 }
8327 if (idx !== 0 || value !== '') {
8328 parts.push(value);
8329 }
8330 prevIndex = i;
8331 }
8332
8333 if (prevIndex && prevIndex + 1 < input.length) {
8334 const value = input.slice(prevIndex + 1);
8335 parts.push(value);
8336
8337 if (opts.tokens) {
8338 tokens[tokens.length - 1].value = value;
8339 depth(tokens[tokens.length - 1]);
8340 state.maxDepth += tokens[tokens.length - 1].depth;
8341 }
8342 }
8343
8344 state.slashes = slashes;
8345 state.parts = parts;
8346 }
8347
8348 return state;
8349};
8350
8351var scan_1 = scan$1;
8352
8353const constants$4 = constants$5;
8354const utils$m = utils$o;
8355
8356/**
8357 * Constants
8358 */
8359
8360const {
8361 MAX_LENGTH,
8362 POSIX_REGEX_SOURCE,
8363 REGEX_NON_SPECIAL_CHARS,
8364 REGEX_SPECIAL_CHARS_BACKREF,
8365 REPLACEMENTS
8366} = constants$4;
8367
8368/**
8369 * Helpers
8370 */
8371
8372const expandRange = (args, options) => {
8373 if (typeof options.expandRange === 'function') {
8374 return options.expandRange(...args, options);
8375 }
8376
8377 args.sort();
8378 const value = `[${args.join('-')}]`;
8379
8380 return value;
8381};
8382
8383/**
8384 * Create the message for a syntax error
8385 */
8386
8387const syntaxError = (type, char) => {
8388 return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
8389};
8390
8391/**
8392 * Parse the given input string.
8393 * @param {String} input
8394 * @param {Object} options
8395 * @return {Object}
8396 */
8397
8398const parse$j = (input, options) => {
8399 if (typeof input !== 'string') {
8400 throw new TypeError('Expected a string');
8401 }
8402
8403 input = REPLACEMENTS[input] || input;
8404
8405 const opts = { ...options };
8406 const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
8407
8408 let len = input.length;
8409 if (len > max) {
8410 throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
8411 }
8412
8413 const bos = { type: 'bos', value: '', output: opts.prepend || '' };
8414 const tokens = [bos];
8415
8416 const capture = opts.capture ? '' : '?:';
8417 const win32 = utils$m.isWindows(options);
8418
8419 // create constants based on platform, for windows or posix
8420 const PLATFORM_CHARS = constants$4.globChars(win32);
8421 const EXTGLOB_CHARS = constants$4.extglobChars(PLATFORM_CHARS);
8422
8423 const {
8424 DOT_LITERAL,
8425 PLUS_LITERAL,
8426 SLASH_LITERAL,
8427 ONE_CHAR,
8428 DOTS_SLASH,
8429 NO_DOT,
8430 NO_DOT_SLASH,
8431 NO_DOTS_SLASH,
8432 QMARK,
8433 QMARK_NO_DOT,
8434 STAR,
8435 START_ANCHOR
8436 } = PLATFORM_CHARS;
8437
8438 const globstar = opts => {
8439 return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
8440 };
8441
8442 const nodot = opts.dot ? '' : NO_DOT;
8443 const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
8444 let star = opts.bash === true ? globstar(opts) : STAR;
8445
8446 if (opts.capture) {
8447 star = `(${star})`;
8448 }
8449
8450 // minimatch options support
8451 if (typeof opts.noext === 'boolean') {
8452 opts.noextglob = opts.noext;
8453 }
8454
8455 const state = {
8456 input,
8457 index: -1,
8458 start: 0,
8459 dot: opts.dot === true,
8460 consumed: '',
8461 output: '',
8462 prefix: '',
8463 backtrack: false,
8464 negated: false,
8465 brackets: 0,
8466 braces: 0,
8467 parens: 0,
8468 quotes: 0,
8469 globstar: false,
8470 tokens
8471 };
8472
8473 input = utils$m.removePrefix(input, state);
8474 len = input.length;
8475
8476 const extglobs = [];
8477 const braces = [];
8478 const stack = [];
8479 let prev = bos;
8480 let value;
8481
8482 /**
8483 * Tokenizing helpers
8484 */
8485
8486 const eos = () => state.index === len - 1;
8487 const peek = state.peek = (n = 1) => input[state.index + n];
8488 const advance = state.advance = () => input[++state.index] || '';
8489 const remaining = () => input.slice(state.index + 1);
8490 const consume = (value = '', num = 0) => {
8491 state.consumed += value;
8492 state.index += num;
8493 };
8494
8495 const append = token => {
8496 state.output += token.output != null ? token.output : token.value;
8497 consume(token.value);
8498 };
8499
8500 const negate = () => {
8501 let count = 1;
8502
8503 while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
8504 advance();
8505 state.start++;
8506 count++;
8507 }
8508
8509 if (count % 2 === 0) {
8510 return false;
8511 }
8512
8513 state.negated = true;
8514 state.start++;
8515 return true;
8516 };
8517
8518 const increment = type => {
8519 state[type]++;
8520 stack.push(type);
8521 };
8522
8523 const decrement = type => {
8524 state[type]--;
8525 stack.pop();
8526 };
8527
8528 /**
8529 * Push tokens onto the tokens array. This helper speeds up
8530 * tokenizing by 1) helping us avoid backtracking as much as possible,
8531 * and 2) helping us avoid creating extra tokens when consecutive
8532 * characters are plain text. This improves performance and simplifies
8533 * lookbehinds.
8534 */
8535
8536 const push = tok => {
8537 if (prev.type === 'globstar') {
8538 const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
8539 const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
8540
8541 if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
8542 state.output = state.output.slice(0, -prev.output.length);
8543 prev.type = 'star';
8544 prev.value = '*';
8545 prev.output = star;
8546 state.output += prev.output;
8547 }
8548 }
8549
8550 if (extglobs.length && tok.type !== 'paren') {
8551 extglobs[extglobs.length - 1].inner += tok.value;
8552 }
8553
8554 if (tok.value || tok.output) append(tok);
8555 if (prev && prev.type === 'text' && tok.type === 'text') {
8556 prev.value += tok.value;
8557 prev.output = (prev.output || '') + tok.value;
8558 return;
8559 }
8560
8561 tok.prev = prev;
8562 tokens.push(tok);
8563 prev = tok;
8564 };
8565
8566 const extglobOpen = (type, value) => {
8567 const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
8568
8569 token.prev = prev;
8570 token.parens = state.parens;
8571 token.output = state.output;
8572 const output = (opts.capture ? '(' : '') + token.open;
8573
8574 increment('parens');
8575 push({ type, value, output: state.output ? '' : ONE_CHAR });
8576 push({ type: 'paren', extglob: true, value: advance(), output });
8577 extglobs.push(token);
8578 };
8579
8580 const extglobClose = token => {
8581 let output = token.close + (opts.capture ? ')' : '');
8582 let rest;
8583
8584 if (token.type === 'negate') {
8585 let extglobStar = star;
8586
8587 if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
8588 extglobStar = globstar(opts);
8589 }
8590
8591 if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
8592 output = token.close = `)$))${extglobStar}`;
8593 }
8594
8595 if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
8596 output = token.close = `)${rest})${extglobStar})`;
8597 }
8598
8599 if (token.prev.type === 'bos') {
8600 state.negatedExtglob = true;
8601 }
8602 }
8603
8604 push({ type: 'paren', extglob: true, value, output });
8605 decrement('parens');
8606 };
8607
8608 /**
8609 * Fast paths
8610 */
8611
8612 if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
8613 let backslashes = false;
8614
8615 let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
8616 if (first === '\\') {
8617 backslashes = true;
8618 return m;
8619 }
8620
8621 if (first === '?') {
8622 if (esc) {
8623 return esc + first + (rest ? QMARK.repeat(rest.length) : '');
8624 }
8625 if (index === 0) {
8626 return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
8627 }
8628 return QMARK.repeat(chars.length);
8629 }
8630
8631 if (first === '.') {
8632 return DOT_LITERAL.repeat(chars.length);
8633 }
8634
8635 if (first === '*') {
8636 if (esc) {
8637 return esc + first + (rest ? star : '');
8638 }
8639 return star;
8640 }
8641 return esc ? m : `\\${m}`;
8642 });
8643
8644 if (backslashes === true) {
8645 if (opts.unescape === true) {
8646 output = output.replace(/\\/g, '');
8647 } else {
8648 output = output.replace(/\\+/g, m => {
8649 return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
8650 });
8651 }
8652 }
8653
8654 if (output === input && opts.contains === true) {
8655 state.output = input;
8656 return state;
8657 }
8658
8659 state.output = utils$m.wrapOutput(output, state, options);
8660 return state;
8661 }
8662
8663 /**
8664 * Tokenize input until we reach end-of-string
8665 */
8666
8667 while (!eos()) {
8668 value = advance();
8669
8670 if (value === '\u0000') {
8671 continue;
8672 }
8673
8674 /**
8675 * Escaped characters
8676 */
8677
8678 if (value === '\\') {
8679 const next = peek();
8680
8681 if (next === '/' && opts.bash !== true) {
8682 continue;
8683 }
8684
8685 if (next === '.' || next === ';') {
8686 continue;
8687 }
8688
8689 if (!next) {
8690 value += '\\';
8691 push({ type: 'text', value });
8692 continue;
8693 }
8694
8695 // collapse slashes to reduce potential for exploits
8696 const match = /^\\+/.exec(remaining());
8697 let slashes = 0;
8698
8699 if (match && match[0].length > 2) {
8700 slashes = match[0].length;
8701 state.index += slashes;
8702 if (slashes % 2 !== 0) {
8703 value += '\\';
8704 }
8705 }
8706
8707 if (opts.unescape === true) {
8708 value = advance();
8709 } else {
8710 value += advance();
8711 }
8712
8713 if (state.brackets === 0) {
8714 push({ type: 'text', value });
8715 continue;
8716 }
8717 }
8718
8719 /**
8720 * If we're inside a regex character class, continue
8721 * until we reach the closing bracket.
8722 */
8723
8724 if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
8725 if (opts.posix !== false && value === ':') {
8726 const inner = prev.value.slice(1);
8727 if (inner.includes('[')) {
8728 prev.posix = true;
8729
8730 if (inner.includes(':')) {
8731 const idx = prev.value.lastIndexOf('[');
8732 const pre = prev.value.slice(0, idx);
8733 const rest = prev.value.slice(idx + 2);
8734 const posix = POSIX_REGEX_SOURCE[rest];
8735 if (posix) {
8736 prev.value = pre + posix;
8737 state.backtrack = true;
8738 advance();
8739
8740 if (!bos.output && tokens.indexOf(prev) === 1) {
8741 bos.output = ONE_CHAR;
8742 }
8743 continue;
8744 }
8745 }
8746 }
8747 }
8748
8749 if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
8750 value = `\\${value}`;
8751 }
8752
8753 if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
8754 value = `\\${value}`;
8755 }
8756
8757 if (opts.posix === true && value === '!' && prev.value === '[') {
8758 value = '^';
8759 }
8760
8761 prev.value += value;
8762 append({ value });
8763 continue;
8764 }
8765
8766 /**
8767 * If we're inside a quoted string, continue
8768 * until we reach the closing double quote.
8769 */
8770
8771 if (state.quotes === 1 && value !== '"') {
8772 value = utils$m.escapeRegex(value);
8773 prev.value += value;
8774 append({ value });
8775 continue;
8776 }
8777
8778 /**
8779 * Double quotes
8780 */
8781
8782 if (value === '"') {
8783 state.quotes = state.quotes === 1 ? 0 : 1;
8784 if (opts.keepQuotes === true) {
8785 push({ type: 'text', value });
8786 }
8787 continue;
8788 }
8789
8790 /**
8791 * Parentheses
8792 */
8793
8794 if (value === '(') {
8795 increment('parens');
8796 push({ type: 'paren', value });
8797 continue;
8798 }
8799
8800 if (value === ')') {
8801 if (state.parens === 0 && opts.strictBrackets === true) {
8802 throw new SyntaxError(syntaxError('opening', '('));
8803 }
8804
8805 const extglob = extglobs[extglobs.length - 1];
8806 if (extglob && state.parens === extglob.parens + 1) {
8807 extglobClose(extglobs.pop());
8808 continue;
8809 }
8810
8811 push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
8812 decrement('parens');
8813 continue;
8814 }
8815
8816 /**
8817 * Square brackets
8818 */
8819
8820 if (value === '[') {
8821 if (opts.nobracket === true || !remaining().includes(']')) {
8822 if (opts.nobracket !== true && opts.strictBrackets === true) {
8823 throw new SyntaxError(syntaxError('closing', ']'));
8824 }
8825
8826 value = `\\${value}`;
8827 } else {
8828 increment('brackets');
8829 }
8830
8831 push({ type: 'bracket', value });
8832 continue;
8833 }
8834
8835 if (value === ']') {
8836 if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
8837 push({ type: 'text', value, output: `\\${value}` });
8838 continue;
8839 }
8840
8841 if (state.brackets === 0) {
8842 if (opts.strictBrackets === true) {
8843 throw new SyntaxError(syntaxError('opening', '['));
8844 }
8845
8846 push({ type: 'text', value, output: `\\${value}` });
8847 continue;
8848 }
8849
8850 decrement('brackets');
8851
8852 const prevValue = prev.value.slice(1);
8853 if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
8854 value = `/${value}`;
8855 }
8856
8857 prev.value += value;
8858 append({ value });
8859
8860 // when literal brackets are explicitly disabled
8861 // assume we should match with a regex character class
8862 if (opts.literalBrackets === false || utils$m.hasRegexChars(prevValue)) {
8863 continue;
8864 }
8865
8866 const escaped = utils$m.escapeRegex(prev.value);
8867 state.output = state.output.slice(0, -prev.value.length);
8868
8869 // when literal brackets are explicitly enabled
8870 // assume we should escape the brackets to match literal characters
8871 if (opts.literalBrackets === true) {
8872 state.output += escaped;
8873 prev.value = escaped;
8874 continue;
8875 }
8876
8877 // when the user specifies nothing, try to match both
8878 prev.value = `(${capture}${escaped}|${prev.value})`;
8879 state.output += prev.value;
8880 continue;
8881 }
8882
8883 /**
8884 * Braces
8885 */
8886
8887 if (value === '{' && opts.nobrace !== true) {
8888 increment('braces');
8889
8890 const open = {
8891 type: 'brace',
8892 value,
8893 output: '(',
8894 outputIndex: state.output.length,
8895 tokensIndex: state.tokens.length
8896 };
8897
8898 braces.push(open);
8899 push(open);
8900 continue;
8901 }
8902
8903 if (value === '}') {
8904 const brace = braces[braces.length - 1];
8905
8906 if (opts.nobrace === true || !brace) {
8907 push({ type: 'text', value, output: value });
8908 continue;
8909 }
8910
8911 let output = ')';
8912
8913 if (brace.dots === true) {
8914 const arr = tokens.slice();
8915 const range = [];
8916
8917 for (let i = arr.length - 1; i >= 0; i--) {
8918 tokens.pop();
8919 if (arr[i].type === 'brace') {
8920 break;
8921 }
8922 if (arr[i].type !== 'dots') {
8923 range.unshift(arr[i].value);
8924 }
8925 }
8926
8927 output = expandRange(range, opts);
8928 state.backtrack = true;
8929 }
8930
8931 if (brace.comma !== true && brace.dots !== true) {
8932 const out = state.output.slice(0, brace.outputIndex);
8933 const toks = state.tokens.slice(brace.tokensIndex);
8934 brace.value = brace.output = '\\{';
8935 value = output = '\\}';
8936 state.output = out;
8937 for (const t of toks) {
8938 state.output += (t.output || t.value);
8939 }
8940 }
8941
8942 push({ type: 'brace', value, output });
8943 decrement('braces');
8944 braces.pop();
8945 continue;
8946 }
8947
8948 /**
8949 * Pipes
8950 */
8951
8952 if (value === '|') {
8953 if (extglobs.length > 0) {
8954 extglobs[extglobs.length - 1].conditions++;
8955 }
8956 push({ type: 'text', value });
8957 continue;
8958 }
8959
8960 /**
8961 * Commas
8962 */
8963
8964 if (value === ',') {
8965 let output = value;
8966
8967 const brace = braces[braces.length - 1];
8968 if (brace && stack[stack.length - 1] === 'braces') {
8969 brace.comma = true;
8970 output = '|';
8971 }
8972
8973 push({ type: 'comma', value, output });
8974 continue;
8975 }
8976
8977 /**
8978 * Slashes
8979 */
8980
8981 if (value === '/') {
8982 // if the beginning of the glob is "./", advance the start
8983 // to the current index, and don't add the "./" characters
8984 // to the state. This greatly simplifies lookbehinds when
8985 // checking for BOS characters like "!" and "." (not "./")
8986 if (prev.type === 'dot' && state.index === state.start + 1) {
8987 state.start = state.index + 1;
8988 state.consumed = '';
8989 state.output = '';
8990 tokens.pop();
8991 prev = bos; // reset "prev" to the first token
8992 continue;
8993 }
8994
8995 push({ type: 'slash', value, output: SLASH_LITERAL });
8996 continue;
8997 }
8998
8999 /**
9000 * Dots
9001 */
9002
9003 if (value === '.') {
9004 if (state.braces > 0 && prev.type === 'dot') {
9005 if (prev.value === '.') prev.output = DOT_LITERAL;
9006 const brace = braces[braces.length - 1];
9007 prev.type = 'dots';
9008 prev.output += value;
9009 prev.value += value;
9010 brace.dots = true;
9011 continue;
9012 }
9013
9014 if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
9015 push({ type: 'text', value, output: DOT_LITERAL });
9016 continue;
9017 }
9018
9019 push({ type: 'dot', value, output: DOT_LITERAL });
9020 continue;
9021 }
9022
9023 /**
9024 * Question marks
9025 */
9026
9027 if (value === '?') {
9028 const isGroup = prev && prev.value === '(';
9029 if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
9030 extglobOpen('qmark', value);
9031 continue;
9032 }
9033
9034 if (prev && prev.type === 'paren') {
9035 const next = peek();
9036 let output = value;
9037
9038 if (next === '<' && !utils$m.supportsLookbehinds()) {
9039 throw new Error('Node.js v10 or higher is required for regex lookbehinds');
9040 }
9041
9042 if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
9043 output = `\\${value}`;
9044 }
9045
9046 push({ type: 'text', value, output });
9047 continue;
9048 }
9049
9050 if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
9051 push({ type: 'qmark', value, output: QMARK_NO_DOT });
9052 continue;
9053 }
9054
9055 push({ type: 'qmark', value, output: QMARK });
9056 continue;
9057 }
9058
9059 /**
9060 * Exclamation
9061 */
9062
9063 if (value === '!') {
9064 if (opts.noextglob !== true && peek() === '(') {
9065 if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
9066 extglobOpen('negate', value);
9067 continue;
9068 }
9069 }
9070
9071 if (opts.nonegate !== true && state.index === 0) {
9072 negate();
9073 continue;
9074 }
9075 }
9076
9077 /**
9078 * Plus
9079 */
9080
9081 if (value === '+') {
9082 if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
9083 extglobOpen('plus', value);
9084 continue;
9085 }
9086
9087 if ((prev && prev.value === '(') || opts.regex === false) {
9088 push({ type: 'plus', value, output: PLUS_LITERAL });
9089 continue;
9090 }
9091
9092 if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
9093 push({ type: 'plus', value });
9094 continue;
9095 }
9096
9097 push({ type: 'plus', value: PLUS_LITERAL });
9098 continue;
9099 }
9100
9101 /**
9102 * Plain text
9103 */
9104
9105 if (value === '@') {
9106 if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
9107 push({ type: 'at', extglob: true, value, output: '' });
9108 continue;
9109 }
9110
9111 push({ type: 'text', value });
9112 continue;
9113 }
9114
9115 /**
9116 * Plain text
9117 */
9118
9119 if (value !== '*') {
9120 if (value === '$' || value === '^') {
9121 value = `\\${value}`;
9122 }
9123
9124 const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
9125 if (match) {
9126 value += match[0];
9127 state.index += match[0].length;
9128 }
9129
9130 push({ type: 'text', value });
9131 continue;
9132 }
9133
9134 /**
9135 * Stars
9136 */
9137
9138 if (prev && (prev.type === 'globstar' || prev.star === true)) {
9139 prev.type = 'star';
9140 prev.star = true;
9141 prev.value += value;
9142 prev.output = star;
9143 state.backtrack = true;
9144 state.globstar = true;
9145 consume(value);
9146 continue;
9147 }
9148
9149 let rest = remaining();
9150 if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
9151 extglobOpen('star', value);
9152 continue;
9153 }
9154
9155 if (prev.type === 'star') {
9156 if (opts.noglobstar === true) {
9157 consume(value);
9158 continue;
9159 }
9160
9161 const prior = prev.prev;
9162 const before = prior.prev;
9163 const isStart = prior.type === 'slash' || prior.type === 'bos';
9164 const afterStar = before && (before.type === 'star' || before.type === 'globstar');
9165
9166 if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
9167 push({ type: 'star', value, output: '' });
9168 continue;
9169 }
9170
9171 const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
9172 const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
9173 if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
9174 push({ type: 'star', value, output: '' });
9175 continue;
9176 }
9177
9178 // strip consecutive `/**/`
9179 while (rest.slice(0, 3) === '/**') {
9180 const after = input[state.index + 4];
9181 if (after && after !== '/') {
9182 break;
9183 }
9184 rest = rest.slice(3);
9185 consume('/**', 3);
9186 }
9187
9188 if (prior.type === 'bos' && eos()) {
9189 prev.type = 'globstar';
9190 prev.value += value;
9191 prev.output = globstar(opts);
9192 state.output = prev.output;
9193 state.globstar = true;
9194 consume(value);
9195 continue;
9196 }
9197
9198 if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
9199 state.output = state.output.slice(0, -(prior.output + prev.output).length);
9200 prior.output = `(?:${prior.output}`;
9201
9202 prev.type = 'globstar';
9203 prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
9204 prev.value += value;
9205 state.globstar = true;
9206 state.output += prior.output + prev.output;
9207 consume(value);
9208 continue;
9209 }
9210
9211 if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
9212 const end = rest[1] !== void 0 ? '|$' : '';
9213
9214 state.output = state.output.slice(0, -(prior.output + prev.output).length);
9215 prior.output = `(?:${prior.output}`;
9216
9217 prev.type = 'globstar';
9218 prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
9219 prev.value += value;
9220
9221 state.output += prior.output + prev.output;
9222 state.globstar = true;
9223
9224 consume(value + advance());
9225
9226 push({ type: 'slash', value: '/', output: '' });
9227 continue;
9228 }
9229
9230 if (prior.type === 'bos' && rest[0] === '/') {
9231 prev.type = 'globstar';
9232 prev.value += value;
9233 prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
9234 state.output = prev.output;
9235 state.globstar = true;
9236 consume(value + advance());
9237 push({ type: 'slash', value: '/', output: '' });
9238 continue;
9239 }
9240
9241 // remove single star from output
9242 state.output = state.output.slice(0, -prev.output.length);
9243
9244 // reset previous token to globstar
9245 prev.type = 'globstar';
9246 prev.output = globstar(opts);
9247 prev.value += value;
9248
9249 // reset output with globstar
9250 state.output += prev.output;
9251 state.globstar = true;
9252 consume(value);
9253 continue;
9254 }
9255
9256 const token = { type: 'star', value, output: star };
9257
9258 if (opts.bash === true) {
9259 token.output = '.*?';
9260 if (prev.type === 'bos' || prev.type === 'slash') {
9261 token.output = nodot + token.output;
9262 }
9263 push(token);
9264 continue;
9265 }
9266
9267 if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
9268 token.output = value;
9269 push(token);
9270 continue;
9271 }
9272
9273 if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
9274 if (prev.type === 'dot') {
9275 state.output += NO_DOT_SLASH;
9276 prev.output += NO_DOT_SLASH;
9277
9278 } else if (opts.dot === true) {
9279 state.output += NO_DOTS_SLASH;
9280 prev.output += NO_DOTS_SLASH;
9281
9282 } else {
9283 state.output += nodot;
9284 prev.output += nodot;
9285 }
9286
9287 if (peek() !== '*') {
9288 state.output += ONE_CHAR;
9289 prev.output += ONE_CHAR;
9290 }
9291 }
9292
9293 push(token);
9294 }
9295
9296 while (state.brackets > 0) {
9297 if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
9298 state.output = utils$m.escapeLast(state.output, '[');
9299 decrement('brackets');
9300 }
9301
9302 while (state.parens > 0) {
9303 if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
9304 state.output = utils$m.escapeLast(state.output, '(');
9305 decrement('parens');
9306 }
9307
9308 while (state.braces > 0) {
9309 if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
9310 state.output = utils$m.escapeLast(state.output, '{');
9311 decrement('braces');
9312 }
9313
9314 if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
9315 push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
9316 }
9317
9318 // rebuild the output if we had to backtrack at any point
9319 if (state.backtrack === true) {
9320 state.output = '';
9321
9322 for (const token of state.tokens) {
9323 state.output += token.output != null ? token.output : token.value;
9324
9325 if (token.suffix) {
9326 state.output += token.suffix;
9327 }
9328 }
9329 }
9330
9331 return state;
9332};
9333
9334/**
9335 * Fast paths for creating regular expressions for common glob patterns.
9336 * This can significantly speed up processing and has very little downside
9337 * impact when none of the fast paths match.
9338 */
9339
9340parse$j.fastpaths = (input, options) => {
9341 const opts = { ...options };
9342 const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
9343 const len = input.length;
9344 if (len > max) {
9345 throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
9346 }
9347
9348 input = REPLACEMENTS[input] || input;
9349 const win32 = utils$m.isWindows(options);
9350
9351 // create constants based on platform, for windows or posix
9352 const {
9353 DOT_LITERAL,
9354 SLASH_LITERAL,
9355 ONE_CHAR,
9356 DOTS_SLASH,
9357 NO_DOT,
9358 NO_DOTS,
9359 NO_DOTS_SLASH,
9360 STAR,
9361 START_ANCHOR
9362 } = constants$4.globChars(win32);
9363
9364 const nodot = opts.dot ? NO_DOTS : NO_DOT;
9365 const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
9366 const capture = opts.capture ? '' : '?:';
9367 const state = { negated: false, prefix: '' };
9368 let star = opts.bash === true ? '.*?' : STAR;
9369
9370 if (opts.capture) {
9371 star = `(${star})`;
9372 }
9373
9374 const globstar = opts => {
9375 if (opts.noglobstar === true) return star;
9376 return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
9377 };
9378
9379 const create = str => {
9380 switch (str) {
9381 case '*':
9382 return `${nodot}${ONE_CHAR}${star}`;
9383
9384 case '.*':
9385 return `${DOT_LITERAL}${ONE_CHAR}${star}`;
9386
9387 case '*.*':
9388 return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
9389
9390 case '*/*':
9391 return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
9392
9393 case '**':
9394 return nodot + globstar(opts);
9395
9396 case '**/*':
9397 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
9398
9399 case '**/*.*':
9400 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
9401
9402 case '**/.*':
9403 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
9404
9405 default: {
9406 const match = /^(.*?)\.(\w+)$/.exec(str);
9407 if (!match) return;
9408
9409 const source = create(match[1]);
9410 if (!source) return;
9411
9412 return source + DOT_LITERAL + match[2];
9413 }
9414 }
9415 };
9416
9417 const output = utils$m.removePrefix(input, state);
9418 let source = create(output);
9419
9420 if (source && opts.strictSlashes !== true) {
9421 source += `${SLASH_LITERAL}?`;
9422 }
9423
9424 return source;
9425};
9426
9427var parse_1$1 = parse$j;
9428
9429const path$w = path__default;
9430const scan = scan_1;
9431const parse$i = parse_1$1;
9432const utils$l = utils$o;
9433const constants$3 = constants$5;
9434const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
9435
9436/**
9437 * Creates a matcher function from one or more glob patterns. The
9438 * returned function takes a string to match as its first argument,
9439 * and returns true if the string is a match. The returned matcher
9440 * function also takes a boolean as the second argument that, when true,
9441 * returns an object with additional information.
9442 *
9443 * ```js
9444 * const picomatch = require('picomatch');
9445 * // picomatch(glob[, options]);
9446 *
9447 * const isMatch = picomatch('*.!(*a)');
9448 * console.log(isMatch('a.a')); //=> false
9449 * console.log(isMatch('a.b')); //=> true
9450 * ```
9451 * @name picomatch
9452 * @param {String|Array} `globs` One or more glob patterns.
9453 * @param {Object=} `options`
9454 * @return {Function=} Returns a matcher function.
9455 * @api public
9456 */
9457
9458const picomatch$5 = (glob, options, returnState = false) => {
9459 if (Array.isArray(glob)) {
9460 const fns = glob.map(input => picomatch$5(input, options, returnState));
9461 const arrayMatcher = str => {
9462 for (const isMatch of fns) {
9463 const state = isMatch(str);
9464 if (state) return state;
9465 }
9466 return false;
9467 };
9468 return arrayMatcher;
9469 }
9470
9471 const isState = isObject(glob) && glob.tokens && glob.input;
9472
9473 if (glob === '' || (typeof glob !== 'string' && !isState)) {
9474 throw new TypeError('Expected pattern to be a non-empty string');
9475 }
9476
9477 const opts = options || {};
9478 const posix = utils$l.isWindows(options);
9479 const regex = isState
9480 ? picomatch$5.compileRe(glob, options)
9481 : picomatch$5.makeRe(glob, options, false, true);
9482
9483 const state = regex.state;
9484 delete regex.state;
9485
9486 let isIgnored = () => false;
9487 if (opts.ignore) {
9488 const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
9489 isIgnored = picomatch$5(opts.ignore, ignoreOpts, returnState);
9490 }
9491
9492 const matcher = (input, returnObject = false) => {
9493 const { isMatch, match, output } = picomatch$5.test(input, regex, options, { glob, posix });
9494 const result = { glob, state, regex, posix, input, output, match, isMatch };
9495
9496 if (typeof opts.onResult === 'function') {
9497 opts.onResult(result);
9498 }
9499
9500 if (isMatch === false) {
9501 result.isMatch = false;
9502 return returnObject ? result : false;
9503 }
9504
9505 if (isIgnored(input)) {
9506 if (typeof opts.onIgnore === 'function') {
9507 opts.onIgnore(result);
9508 }
9509 result.isMatch = false;
9510 return returnObject ? result : false;
9511 }
9512
9513 if (typeof opts.onMatch === 'function') {
9514 opts.onMatch(result);
9515 }
9516 return returnObject ? result : true;
9517 };
9518
9519 if (returnState) {
9520 matcher.state = state;
9521 }
9522
9523 return matcher;
9524};
9525
9526/**
9527 * Test `input` with the given `regex`. This is used by the main
9528 * `picomatch()` function to test the input string.
9529 *
9530 * ```js
9531 * const picomatch = require('picomatch');
9532 * // picomatch.test(input, regex[, options]);
9533 *
9534 * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
9535 * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
9536 * ```
9537 * @param {String} `input` String to test.
9538 * @param {RegExp} `regex`
9539 * @return {Object} Returns an object with matching info.
9540 * @api public
9541 */
9542
9543picomatch$5.test = (input, regex, options, { glob, posix } = {}) => {
9544 if (typeof input !== 'string') {
9545 throw new TypeError('Expected input to be a string');
9546 }
9547
9548 if (input === '') {
9549 return { isMatch: false, output: '' };
9550 }
9551
9552 const opts = options || {};
9553 const format = opts.format || (posix ? utils$l.toPosixSlashes : null);
9554 let match = input === glob;
9555 let output = (match && format) ? format(input) : input;
9556
9557 if (match === false) {
9558 output = format ? format(input) : input;
9559 match = output === glob;
9560 }
9561
9562 if (match === false || opts.capture === true) {
9563 if (opts.matchBase === true || opts.basename === true) {
9564 match = picomatch$5.matchBase(input, regex, options, posix);
9565 } else {
9566 match = regex.exec(output);
9567 }
9568 }
9569
9570 return { isMatch: Boolean(match), match, output };
9571};
9572
9573/**
9574 * Match the basename of a filepath.
9575 *
9576 * ```js
9577 * const picomatch = require('picomatch');
9578 * // picomatch.matchBase(input, glob[, options]);
9579 * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
9580 * ```
9581 * @param {String} `input` String to test.
9582 * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
9583 * @return {Boolean}
9584 * @api public
9585 */
9586
9587picomatch$5.matchBase = (input, glob, options, posix = utils$l.isWindows(options)) => {
9588 const regex = glob instanceof RegExp ? glob : picomatch$5.makeRe(glob, options);
9589 return regex.test(path$w.basename(input));
9590};
9591
9592/**
9593 * Returns true if **any** of the given glob `patterns` match the specified `string`.
9594 *
9595 * ```js
9596 * const picomatch = require('picomatch');
9597 * // picomatch.isMatch(string, patterns[, options]);
9598 *
9599 * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
9600 * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
9601 * ```
9602 * @param {String|Array} str The string to test.
9603 * @param {String|Array} patterns One or more glob patterns to use for matching.
9604 * @param {Object} [options] See available [options](#options).
9605 * @return {Boolean} Returns true if any patterns match `str`
9606 * @api public
9607 */
9608
9609picomatch$5.isMatch = (str, patterns, options) => picomatch$5(patterns, options)(str);
9610
9611/**
9612 * Parse a glob pattern to create the source string for a regular
9613 * expression.
9614 *
9615 * ```js
9616 * const picomatch = require('picomatch');
9617 * const result = picomatch.parse(pattern[, options]);
9618 * ```
9619 * @param {String} `pattern`
9620 * @param {Object} `options`
9621 * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
9622 * @api public
9623 */
9624
9625picomatch$5.parse = (pattern, options) => {
9626 if (Array.isArray(pattern)) return pattern.map(p => picomatch$5.parse(p, options));
9627 return parse$i(pattern, { ...options, fastpaths: false });
9628};
9629
9630/**
9631 * Scan a glob pattern to separate the pattern into segments.
9632 *
9633 * ```js
9634 * const picomatch = require('picomatch');
9635 * // picomatch.scan(input[, options]);
9636 *
9637 * const result = picomatch.scan('!./foo/*.js');
9638 * console.log(result);
9639 * { prefix: '!./',
9640 * input: '!./foo/*.js',
9641 * start: 3,
9642 * base: 'foo',
9643 * glob: '*.js',
9644 * isBrace: false,
9645 * isBracket: false,
9646 * isGlob: true,
9647 * isExtglob: false,
9648 * isGlobstar: false,
9649 * negated: true }
9650 * ```
9651 * @param {String} `input` Glob pattern to scan.
9652 * @param {Object} `options`
9653 * @return {Object} Returns an object with
9654 * @api public
9655 */
9656
9657picomatch$5.scan = (input, options) => scan(input, options);
9658
9659/**
9660 * Compile a regular expression from the `state` object returned by the
9661 * [parse()](#parse) method.
9662 *
9663 * @param {Object} `state`
9664 * @param {Object} `options`
9665 * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
9666 * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
9667 * @return {RegExp}
9668 * @api public
9669 */
9670
9671picomatch$5.compileRe = (state, options, returnOutput = false, returnState = false) => {
9672 if (returnOutput === true) {
9673 return state.output;
9674 }
9675
9676 const opts = options || {};
9677 const prepend = opts.contains ? '' : '^';
9678 const append = opts.contains ? '' : '$';
9679
9680 let source = `${prepend}(?:${state.output})${append}`;
9681 if (state && state.negated === true) {
9682 source = `^(?!${source}).*$`;
9683 }
9684
9685 const regex = picomatch$5.toRegex(source, options);
9686 if (returnState === true) {
9687 regex.state = state;
9688 }
9689
9690 return regex;
9691};
9692
9693/**
9694 * Create a regular expression from a parsed glob pattern.
9695 *
9696 * ```js
9697 * const picomatch = require('picomatch');
9698 * const state = picomatch.parse('*.js');
9699 * // picomatch.compileRe(state[, options]);
9700 *
9701 * console.log(picomatch.compileRe(state));
9702 * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
9703 * ```
9704 * @param {String} `state` The object returned from the `.parse` method.
9705 * @param {Object} `options`
9706 * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.
9707 * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
9708 * @return {RegExp} Returns a regex created from the given pattern.
9709 * @api public
9710 */
9711
9712picomatch$5.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
9713 if (!input || typeof input !== 'string') {
9714 throw new TypeError('Expected a non-empty string');
9715 }
9716
9717 let parsed = { negated: false, fastpaths: true };
9718
9719 if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
9720 parsed.output = parse$i.fastpaths(input, options);
9721 }
9722
9723 if (!parsed.output) {
9724 parsed = parse$i(input, options);
9725 }
9726
9727 return picomatch$5.compileRe(parsed, options, returnOutput, returnState);
9728};
9729
9730/**
9731 * Create a regular expression from the given regex source string.
9732 *
9733 * ```js
9734 * const picomatch = require('picomatch');
9735 * // picomatch.toRegex(source[, options]);
9736 *
9737 * const { output } = picomatch.parse('*.js');
9738 * console.log(picomatch.toRegex(output));
9739 * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
9740 * ```
9741 * @param {String} `source` Regular expression source string.
9742 * @param {Object} `options`
9743 * @return {RegExp}
9744 * @api public
9745 */
9746
9747picomatch$5.toRegex = (source, options) => {
9748 try {
9749 const opts = options || {};
9750 return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
9751 } catch (err) {
9752 if (options && options.debug === true) throw err;
9753 return /$^/;
9754 }
9755};
9756
9757/**
9758 * Picomatch constants.
9759 * @return {Object}
9760 */
9761
9762picomatch$5.constants = constants$3;
9763
9764/**
9765 * Expose "picomatch"
9766 */
9767
9768var picomatch_1 = picomatch$5;
9769
9770var picomatch$4 = picomatch_1;
9771
9772const util$8 = require$$0__default$3;
9773const braces$1 = braces_1;
9774const picomatch$3 = picomatch$4;
9775const utils$k = utils$o;
9776const isEmptyString = val => val === '' || val === './';
9777
9778/**
9779 * Returns an array of strings that match one or more glob patterns.
9780 *
9781 * ```js
9782 * const mm = require('micromatch');
9783 * // mm(list, patterns[, options]);
9784 *
9785 * console.log(mm(['a.js', 'a.txt'], ['*.js']));
9786 * //=> [ 'a.js' ]
9787 * ```
9788 * @param {String|Array<string>} `list` List of strings to match.
9789 * @param {String|Array<string>} `patterns` One or more glob patterns to use for matching.
9790 * @param {Object} `options` See available [options](#options)
9791 * @return {Array} Returns an array of matches
9792 * @summary false
9793 * @api public
9794 */
9795
9796const micromatch$2 = (list, patterns, options) => {
9797 patterns = [].concat(patterns);
9798 list = [].concat(list);
9799
9800 let omit = new Set();
9801 let keep = new Set();
9802 let items = new Set();
9803 let negatives = 0;
9804
9805 let onResult = state => {
9806 items.add(state.output);
9807 if (options && options.onResult) {
9808 options.onResult(state);
9809 }
9810 };
9811
9812 for (let i = 0; i < patterns.length; i++) {
9813 let isMatch = picomatch$3(String(patterns[i]), { ...options, onResult }, true);
9814 let negated = isMatch.state.negated || isMatch.state.negatedExtglob;
9815 if (negated) negatives++;
9816
9817 for (let item of list) {
9818 let matched = isMatch(item, true);
9819
9820 let match = negated ? !matched.isMatch : matched.isMatch;
9821 if (!match) continue;
9822
9823 if (negated) {
9824 omit.add(matched.output);
9825 } else {
9826 omit.delete(matched.output);
9827 keep.add(matched.output);
9828 }
9829 }
9830 }
9831
9832 let result = negatives === patterns.length ? [...items] : [...keep];
9833 let matches = result.filter(item => !omit.has(item));
9834
9835 if (options && matches.length === 0) {
9836 if (options.failglob === true) {
9837 throw new Error(`No matches found for "${patterns.join(', ')}"`);
9838 }
9839
9840 if (options.nonull === true || options.nullglob === true) {
9841 return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns;
9842 }
9843 }
9844
9845 return matches;
9846};
9847
9848/**
9849 * Backwards compatibility
9850 */
9851
9852micromatch$2.match = micromatch$2;
9853
9854/**
9855 * Returns a matcher function from the given glob `pattern` and `options`.
9856 * The returned function takes a string to match as its only argument and returns
9857 * true if the string is a match.
9858 *
9859 * ```js
9860 * const mm = require('micromatch');
9861 * // mm.matcher(pattern[, options]);
9862 *
9863 * const isMatch = mm.matcher('*.!(*a)');
9864 * console.log(isMatch('a.a')); //=> false
9865 * console.log(isMatch('a.b')); //=> true
9866 * ```
9867 * @param {String} `pattern` Glob pattern
9868 * @param {Object} `options`
9869 * @return {Function} Returns a matcher function.
9870 * @api public
9871 */
9872
9873micromatch$2.matcher = (pattern, options) => picomatch$3(pattern, options);
9874
9875/**
9876 * Returns true if **any** of the given glob `patterns` match the specified `string`.
9877 *
9878 * ```js
9879 * const mm = require('micromatch');
9880 * // mm.isMatch(string, patterns[, options]);
9881 *
9882 * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true
9883 * console.log(mm.isMatch('a.a', 'b.*')); //=> false
9884 * ```
9885 * @param {String} `str` The string to test.
9886 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
9887 * @param {Object} `[options]` See available [options](#options).
9888 * @return {Boolean} Returns true if any patterns match `str`
9889 * @api public
9890 */
9891
9892micromatch$2.isMatch = (str, patterns, options) => picomatch$3(patterns, options)(str);
9893
9894/**
9895 * Backwards compatibility
9896 */
9897
9898micromatch$2.any = micromatch$2.isMatch;
9899
9900/**
9901 * Returns a list of strings that _**do not match any**_ of the given `patterns`.
9902 *
9903 * ```js
9904 * const mm = require('micromatch');
9905 * // mm.not(list, patterns[, options]);
9906 *
9907 * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));
9908 * //=> ['b.b', 'c.c']
9909 * ```
9910 * @param {Array} `list` Array of strings to match.
9911 * @param {String|Array} `patterns` One or more glob pattern to use for matching.
9912 * @param {Object} `options` See available [options](#options) for changing how matches are performed
9913 * @return {Array} Returns an array of strings that **do not match** the given patterns.
9914 * @api public
9915 */
9916
9917micromatch$2.not = (list, patterns, options = {}) => {
9918 patterns = [].concat(patterns).map(String);
9919 let result = new Set();
9920 let items = [];
9921
9922 let onResult = state => {
9923 if (options.onResult) options.onResult(state);
9924 items.push(state.output);
9925 };
9926
9927 let matches = micromatch$2(list, patterns, { ...options, onResult });
9928
9929 for (let item of items) {
9930 if (!matches.includes(item)) {
9931 result.add(item);
9932 }
9933 }
9934 return [...result];
9935};
9936
9937/**
9938 * Returns true if the given `string` contains the given pattern. Similar
9939 * to [.isMatch](#isMatch) but the pattern can match any part of the string.
9940 *
9941 * ```js
9942 * var mm = require('micromatch');
9943 * // mm.contains(string, pattern[, options]);
9944 *
9945 * console.log(mm.contains('aa/bb/cc', '*b'));
9946 * //=> true
9947 * console.log(mm.contains('aa/bb/cc', '*d'));
9948 * //=> false
9949 * ```
9950 * @param {String} `str` The string to match.
9951 * @param {String|Array} `patterns` Glob pattern to use for matching.
9952 * @param {Object} `options` See available [options](#options) for changing how matches are performed
9953 * @return {Boolean} Returns true if any of the patterns matches any part of `str`.
9954 * @api public
9955 */
9956
9957micromatch$2.contains = (str, pattern, options) => {
9958 if (typeof str !== 'string') {
9959 throw new TypeError(`Expected a string: "${util$8.inspect(str)}"`);
9960 }
9961
9962 if (Array.isArray(pattern)) {
9963 return pattern.some(p => micromatch$2.contains(str, p, options));
9964 }
9965
9966 if (typeof pattern === 'string') {
9967 if (isEmptyString(str) || isEmptyString(pattern)) {
9968 return false;
9969 }
9970
9971 if (str.includes(pattern) || (str.startsWith('./') && str.slice(2).includes(pattern))) {
9972 return true;
9973 }
9974 }
9975
9976 return micromatch$2.isMatch(str, pattern, { ...options, contains: true });
9977};
9978
9979/**
9980 * Filter the keys of the given object with the given `glob` pattern
9981 * and `options`. Does not attempt to match nested keys. If you need this feature,
9982 * use [glob-object][] instead.
9983 *
9984 * ```js
9985 * const mm = require('micromatch');
9986 * // mm.matchKeys(object, patterns[, options]);
9987 *
9988 * const obj = { aa: 'a', ab: 'b', ac: 'c' };
9989 * console.log(mm.matchKeys(obj, '*b'));
9990 * //=> { ab: 'b' }
9991 * ```
9992 * @param {Object} `object` The object with keys to filter.
9993 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
9994 * @param {Object} `options` See available [options](#options) for changing how matches are performed
9995 * @return {Object} Returns an object with only keys that match the given patterns.
9996 * @api public
9997 */
9998
9999micromatch$2.matchKeys = (obj, patterns, options) => {
10000 if (!utils$k.isObject(obj)) {
10001 throw new TypeError('Expected the first argument to be an object');
10002 }
10003 let keys = micromatch$2(Object.keys(obj), patterns, options);
10004 let res = {};
10005 for (let key of keys) res[key] = obj[key];
10006 return res;
10007};
10008
10009/**
10010 * Returns true if some of the strings in the given `list` match any of the given glob `patterns`.
10011 *
10012 * ```js
10013 * const mm = require('micromatch');
10014 * // mm.some(list, patterns[, options]);
10015 *
10016 * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
10017 * // true
10018 * console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));
10019 * // false
10020 * ```
10021 * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.
10022 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
10023 * @param {Object} `options` See available [options](#options) for changing how matches are performed
10024 * @return {Boolean} Returns true if any `patterns` matches any of the strings in `list`
10025 * @api public
10026 */
10027
10028micromatch$2.some = (list, patterns, options) => {
10029 let items = [].concat(list);
10030
10031 for (let pattern of [].concat(patterns)) {
10032 let isMatch = picomatch$3(String(pattern), options);
10033 if (items.some(item => isMatch(item))) {
10034 return true;
10035 }
10036 }
10037 return false;
10038};
10039
10040/**
10041 * Returns true if every string in the given `list` matches
10042 * any of the given glob `patterns`.
10043 *
10044 * ```js
10045 * const mm = require('micromatch');
10046 * // mm.every(list, patterns[, options]);
10047 *
10048 * console.log(mm.every('foo.js', ['foo.js']));
10049 * // true
10050 * console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));
10051 * // true
10052 * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
10053 * // false
10054 * console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));
10055 * // false
10056 * ```
10057 * @param {String|Array} `list` The string or array of strings to test.
10058 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
10059 * @param {Object} `options` See available [options](#options) for changing how matches are performed
10060 * @return {Boolean} Returns true if all `patterns` matches all of the strings in `list`
10061 * @api public
10062 */
10063
10064micromatch$2.every = (list, patterns, options) => {
10065 let items = [].concat(list);
10066
10067 for (let pattern of [].concat(patterns)) {
10068 let isMatch = picomatch$3(String(pattern), options);
10069 if (!items.every(item => isMatch(item))) {
10070 return false;
10071 }
10072 }
10073 return true;
10074};
10075
10076/**
10077 * Returns true if **all** of the given `patterns` match
10078 * the specified string.
10079 *
10080 * ```js
10081 * const mm = require('micromatch');
10082 * // mm.all(string, patterns[, options]);
10083 *
10084 * console.log(mm.all('foo.js', ['foo.js']));
10085 * // true
10086 *
10087 * console.log(mm.all('foo.js', ['*.js', '!foo.js']));
10088 * // false
10089 *
10090 * console.log(mm.all('foo.js', ['*.js', 'foo.js']));
10091 * // true
10092 *
10093 * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
10094 * // true
10095 * ```
10096 * @param {String|Array} `str` The string to test.
10097 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
10098 * @param {Object} `options` See available [options](#options) for changing how matches are performed
10099 * @return {Boolean} Returns true if any patterns match `str`
10100 * @api public
10101 */
10102
10103micromatch$2.all = (str, patterns, options) => {
10104 if (typeof str !== 'string') {
10105 throw new TypeError(`Expected a string: "${util$8.inspect(str)}"`);
10106 }
10107
10108 return [].concat(patterns).every(p => picomatch$3(p, options)(str));
10109};
10110
10111/**
10112 * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match.
10113 *
10114 * ```js
10115 * const mm = require('micromatch');
10116 * // mm.capture(pattern, string[, options]);
10117 *
10118 * console.log(mm.capture('test/*.js', 'test/foo.js'));
10119 * //=> ['foo']
10120 * console.log(mm.capture('test/*.js', 'foo/bar.css'));
10121 * //=> null
10122 * ```
10123 * @param {String} `glob` Glob pattern to use for matching.
10124 * @param {String} `input` String to match
10125 * @param {Object} `options` See available [options](#options) for changing how matches are performed
10126 * @return {Array|null} Returns an array of captures if the input matches the glob pattern, otherwise `null`.
10127 * @api public
10128 */
10129
10130micromatch$2.capture = (glob, input, options) => {
10131 let posix = utils$k.isWindows(options);
10132 let regex = picomatch$3.makeRe(String(glob), { ...options, capture: true });
10133 let match = regex.exec(posix ? utils$k.toPosixSlashes(input) : input);
10134
10135 if (match) {
10136 return match.slice(1).map(v => v === void 0 ? '' : v);
10137 }
10138};
10139
10140/**
10141 * Create a regular expression from the given glob `pattern`.
10142 *
10143 * ```js
10144 * const mm = require('micromatch');
10145 * // mm.makeRe(pattern[, options]);
10146 *
10147 * console.log(mm.makeRe('*.js'));
10148 * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
10149 * ```
10150 * @param {String} `pattern` A glob pattern to convert to regex.
10151 * @param {Object} `options`
10152 * @return {RegExp} Returns a regex created from the given pattern.
10153 * @api public
10154 */
10155
10156micromatch$2.makeRe = (...args) => picomatch$3.makeRe(...args);
10157
10158/**
10159 * Scan a glob pattern to separate the pattern into segments. Used
10160 * by the [split](#split) method.
10161 *
10162 * ```js
10163 * const mm = require('micromatch');
10164 * const state = mm.scan(pattern[, options]);
10165 * ```
10166 * @param {String} `pattern`
10167 * @param {Object} `options`
10168 * @return {Object} Returns an object with
10169 * @api public
10170 */
10171
10172micromatch$2.scan = (...args) => picomatch$3.scan(...args);
10173
10174/**
10175 * Parse a glob pattern to create the source string for a regular
10176 * expression.
10177 *
10178 * ```js
10179 * const mm = require('micromatch');
10180 * const state = mm(pattern[, options]);
10181 * ```
10182 * @param {String} `glob`
10183 * @param {Object} `options`
10184 * @return {Object} Returns an object with useful properties and output to be used as regex source string.
10185 * @api public
10186 */
10187
10188micromatch$2.parse = (patterns, options) => {
10189 let res = [];
10190 for (let pattern of [].concat(patterns || [])) {
10191 for (let str of braces$1(String(pattern), options)) {
10192 res.push(picomatch$3.parse(str, options));
10193 }
10194 }
10195 return res;
10196};
10197
10198/**
10199 * Process the given brace `pattern`.
10200 *
10201 * ```js
10202 * const { braces } = require('micromatch');
10203 * console.log(braces('foo/{a,b,c}/bar'));
10204 * //=> [ 'foo/(a|b|c)/bar' ]
10205 *
10206 * console.log(braces('foo/{a,b,c}/bar', { expand: true }));
10207 * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ]
10208 * ```
10209 * @param {String} `pattern` String with brace pattern to process.
10210 * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options.
10211 * @return {Array}
10212 * @api public
10213 */
10214
10215micromatch$2.braces = (pattern, options) => {
10216 if (typeof pattern !== 'string') throw new TypeError('Expected a string');
10217 if ((options && options.nobrace === true) || !/\{.*\}/.test(pattern)) {
10218 return [pattern];
10219 }
10220 return braces$1(pattern, options);
10221};
10222
10223/**
10224 * Expand braces
10225 */
10226
10227micromatch$2.braceExpand = (pattern, options) => {
10228 if (typeof pattern !== 'string') throw new TypeError('Expected a string');
10229 return micromatch$2.braces(pattern, { ...options, expand: true });
10230};
10231
10232/**
10233 * Expose micromatch
10234 */
10235
10236var micromatch_1 = micromatch$2;
10237
10238Object.defineProperty(pattern$3, "__esModule", { value: true });
10239pattern$3.matchAny = pattern$3.convertPatternsToRe = pattern$3.makeRe = pattern$3.getPatternParts = pattern$3.expandBraceExpansion = pattern$3.expandPatternsWithBraceExpansion = pattern$3.isAffectDepthOfReadingPattern = pattern$3.endsWithSlashGlobStar = pattern$3.hasGlobStar = pattern$3.getBaseDirectory = pattern$3.isPatternRelatedToParentDirectory = pattern$3.getPatternsOutsideCurrentDirectory = pattern$3.getPatternsInsideCurrentDirectory = pattern$3.getPositivePatterns = pattern$3.getNegativePatterns = pattern$3.isPositivePattern = pattern$3.isNegativePattern = pattern$3.convertToNegativePattern = pattern$3.convertToPositivePattern = pattern$3.isDynamicPattern = pattern$3.isStaticPattern = void 0;
10240const path$v = path__default;
10241const globParent$2 = globParent$3;
10242const micromatch$1 = micromatch_1;
10243const GLOBSTAR$3 = '**';
10244const ESCAPE_SYMBOL$1 = '\\';
10245const COMMON_GLOB_SYMBOLS_RE$1 = /[*?]|^!/;
10246const REGEX_CHARACTER_CLASS_SYMBOLS_RE$1 = /\[.*]/;
10247const REGEX_GROUP_SYMBOLS_RE$1 = /(?:^|[^!*+?@])\(.*\|.*\)/;
10248const GLOB_EXTENSION_SYMBOLS_RE$1 = /[!*+?@]\(.*\)/;
10249const BRACE_EXPANSIONS_SYMBOLS_RE$1 = /{.*(?:,|\.\.).*}/;
10250function isStaticPattern$1(pattern, options = {}) {
10251 return !isDynamicPattern$1(pattern, options);
10252}
10253pattern$3.isStaticPattern = isStaticPattern$1;
10254function isDynamicPattern$1(pattern, options = {}) {
10255 /**
10256 * A special case with an empty string is necessary for matching patterns that start with a forward slash.
10257 * An empty string cannot be a dynamic pattern.
10258 * For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'.
10259 */
10260 if (pattern === '') {
10261 return false;
10262 }
10263 /**
10264 * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check
10265 * filepath directly (without read directory).
10266 */
10267 if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL$1)) {
10268 return true;
10269 }
10270 if (COMMON_GLOB_SYMBOLS_RE$1.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE$1.test(pattern) || REGEX_GROUP_SYMBOLS_RE$1.test(pattern)) {
10271 return true;
10272 }
10273 if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE$1.test(pattern)) {
10274 return true;
10275 }
10276 if (options.braceExpansion !== false && BRACE_EXPANSIONS_SYMBOLS_RE$1.test(pattern)) {
10277 return true;
10278 }
10279 return false;
10280}
10281pattern$3.isDynamicPattern = isDynamicPattern$1;
10282function convertToPositivePattern$1(pattern) {
10283 return isNegativePattern$1(pattern) ? pattern.slice(1) : pattern;
10284}
10285pattern$3.convertToPositivePattern = convertToPositivePattern$1;
10286function convertToNegativePattern$1(pattern) {
10287 return '!' + pattern;
10288}
10289pattern$3.convertToNegativePattern = convertToNegativePattern$1;
10290function isNegativePattern$1(pattern) {
10291 return pattern.startsWith('!') && pattern[1] !== '(';
10292}
10293pattern$3.isNegativePattern = isNegativePattern$1;
10294function isPositivePattern$1(pattern) {
10295 return !isNegativePattern$1(pattern);
10296}
10297pattern$3.isPositivePattern = isPositivePattern$1;
10298function getNegativePatterns$1(patterns) {
10299 return patterns.filter(isNegativePattern$1);
10300}
10301pattern$3.getNegativePatterns = getNegativePatterns$1;
10302function getPositivePatterns$3(patterns) {
10303 return patterns.filter(isPositivePattern$1);
10304}
10305pattern$3.getPositivePatterns = getPositivePatterns$3;
10306/**
10307 * Returns patterns that can be applied inside the current directory.
10308 *
10309 * @example
10310 * // ['./*', '*', 'a/*']
10311 * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*'])
10312 */
10313function getPatternsInsideCurrentDirectory(patterns) {
10314 return patterns.filter((pattern) => !isPatternRelatedToParentDirectory(pattern));
10315}
10316pattern$3.getPatternsInsideCurrentDirectory = getPatternsInsideCurrentDirectory;
10317/**
10318 * Returns patterns to be expanded relative to (outside) the current directory.
10319 *
10320 * @example
10321 * // ['../*', './../*']
10322 * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*'])
10323 */
10324function getPatternsOutsideCurrentDirectory(patterns) {
10325 return patterns.filter(isPatternRelatedToParentDirectory);
10326}
10327pattern$3.getPatternsOutsideCurrentDirectory = getPatternsOutsideCurrentDirectory;
10328function isPatternRelatedToParentDirectory(pattern) {
10329 return pattern.startsWith('..') || pattern.startsWith('./..');
10330}
10331pattern$3.isPatternRelatedToParentDirectory = isPatternRelatedToParentDirectory;
10332function getBaseDirectory$1(pattern) {
10333 return globParent$2(pattern, { flipBackslashes: false });
10334}
10335pattern$3.getBaseDirectory = getBaseDirectory$1;
10336function hasGlobStar$1(pattern) {
10337 return pattern.includes(GLOBSTAR$3);
10338}
10339pattern$3.hasGlobStar = hasGlobStar$1;
10340function endsWithSlashGlobStar$1(pattern) {
10341 return pattern.endsWith('/' + GLOBSTAR$3);
10342}
10343pattern$3.endsWithSlashGlobStar = endsWithSlashGlobStar$1;
10344function isAffectDepthOfReadingPattern$1(pattern) {
10345 const basename = path$v.basename(pattern);
10346 return endsWithSlashGlobStar$1(pattern) || isStaticPattern$1(basename);
10347}
10348pattern$3.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern$1;
10349function expandPatternsWithBraceExpansion$1(patterns) {
10350 return patterns.reduce((collection, pattern) => {
10351 return collection.concat(expandBraceExpansion$1(pattern));
10352 }, []);
10353}
10354pattern$3.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion$1;
10355function expandBraceExpansion$1(pattern) {
10356 return micromatch$1.braces(pattern, {
10357 expand: true,
10358 nodupes: true
10359 });
10360}
10361pattern$3.expandBraceExpansion = expandBraceExpansion$1;
10362function getPatternParts$1(pattern, options) {
10363 let { parts } = micromatch$1.scan(pattern, Object.assign(Object.assign({}, options), { parts: true }));
10364 /**
10365 * The scan method returns an empty array in some cases.
10366 * See micromatch/picomatch#58 for more details.
10367 */
10368 if (parts.length === 0) {
10369 parts = [pattern];
10370 }
10371 /**
10372 * The scan method does not return an empty part for the pattern with a forward slash.
10373 * This is another part of micromatch/picomatch#58.
10374 */
10375 if (parts[0].startsWith('/')) {
10376 parts[0] = parts[0].slice(1);
10377 parts.unshift('');
10378 }
10379 return parts;
10380}
10381pattern$3.getPatternParts = getPatternParts$1;
10382function makeRe$2(pattern, options) {
10383 return micromatch$1.makeRe(pattern, options);
10384}
10385pattern$3.makeRe = makeRe$2;
10386function convertPatternsToRe$1(patterns, options) {
10387 return patterns.map((pattern) => makeRe$2(pattern, options));
10388}
10389pattern$3.convertPatternsToRe = convertPatternsToRe$1;
10390function matchAny$1(entry, patternsRe) {
10391 return patternsRe.some((patternRe) => patternRe.test(entry));
10392}
10393pattern$3.matchAny = matchAny$1;
10394
10395var stream$b = {};
10396
10397/*
10398 * merge2
10399 * https://github.com/teambition/merge2
10400 *
10401 * Copyright (c) 2014-2020 Teambition
10402 * Licensed under the MIT license.
10403 */
10404const Stream = require$$0__default$2;
10405const PassThrough$1 = Stream.PassThrough;
10406const slice$1 = Array.prototype.slice;
10407
10408var merge2_1 = merge2$3;
10409
10410function merge2$3 () {
10411 const streamsQueue = [];
10412 const args = slice$1.call(arguments);
10413 let merging = false;
10414 let options = args[args.length - 1];
10415
10416 if (options && !Array.isArray(options) && options.pipe == null) {
10417 args.pop();
10418 } else {
10419 options = {};
10420 }
10421
10422 const doEnd = options.end !== false;
10423 const doPipeError = options.pipeError === true;
10424 if (options.objectMode == null) {
10425 options.objectMode = true;
10426 }
10427 if (options.highWaterMark == null) {
10428 options.highWaterMark = 64 * 1024;
10429 }
10430 const mergedStream = PassThrough$1(options);
10431
10432 function addStream () {
10433 for (let i = 0, len = arguments.length; i < len; i++) {
10434 streamsQueue.push(pauseStreams(arguments[i], options));
10435 }
10436 mergeStream();
10437 return this
10438 }
10439
10440 function mergeStream () {
10441 if (merging) {
10442 return
10443 }
10444 merging = true;
10445
10446 let streams = streamsQueue.shift();
10447 if (!streams) {
10448 process.nextTick(endStream);
10449 return
10450 }
10451 if (!Array.isArray(streams)) {
10452 streams = [streams];
10453 }
10454
10455 let pipesCount = streams.length + 1;
10456
10457 function next () {
10458 if (--pipesCount > 0) {
10459 return
10460 }
10461 merging = false;
10462 mergeStream();
10463 }
10464
10465 function pipe (stream) {
10466 function onend () {
10467 stream.removeListener('merge2UnpipeEnd', onend);
10468 stream.removeListener('end', onend);
10469 if (doPipeError) {
10470 stream.removeListener('error', onerror);
10471 }
10472 next();
10473 }
10474 function onerror (err) {
10475 mergedStream.emit('error', err);
10476 }
10477 // skip ended stream
10478 if (stream._readableState.endEmitted) {
10479 return next()
10480 }
10481
10482 stream.on('merge2UnpipeEnd', onend);
10483 stream.on('end', onend);
10484
10485 if (doPipeError) {
10486 stream.on('error', onerror);
10487 }
10488
10489 stream.pipe(mergedStream, { end: false });
10490 // compatible for old stream
10491 stream.resume();
10492 }
10493
10494 for (let i = 0; i < streams.length; i++) {
10495 pipe(streams[i]);
10496 }
10497
10498 next();
10499 }
10500
10501 function endStream () {
10502 merging = false;
10503 // emit 'queueDrain' when all streams merged.
10504 mergedStream.emit('queueDrain');
10505 if (doEnd) {
10506 mergedStream.end();
10507 }
10508 }
10509
10510 mergedStream.setMaxListeners(0);
10511 mergedStream.add = addStream;
10512 mergedStream.on('unpipe', function (stream) {
10513 stream.emit('merge2UnpipeEnd');
10514 });
10515
10516 if (args.length) {
10517 addStream.apply(null, args);
10518 }
10519 return mergedStream
10520}
10521
10522// check and pause streams for pipe.
10523function pauseStreams (streams, options) {
10524 if (!Array.isArray(streams)) {
10525 // Backwards-compat with old-style streams
10526 if (!streams._readableState && streams.pipe) {
10527 streams = streams.pipe(PassThrough$1(options));
10528 }
10529 if (!streams._readableState || !streams.pause || !streams.pipe) {
10530 throw new Error('Only readable stream can be merged.')
10531 }
10532 streams.pause();
10533 } else {
10534 for (let i = 0, len = streams.length; i < len; i++) {
10535 streams[i] = pauseStreams(streams[i], options);
10536 }
10537 }
10538 return streams
10539}
10540
10541Object.defineProperty(stream$b, "__esModule", { value: true });
10542stream$b.merge = void 0;
10543const merge2$2 = merge2_1;
10544function merge$3(streams) {
10545 const mergedStream = merge2$2(streams);
10546 streams.forEach((stream) => {
10547 stream.once('error', (error) => mergedStream.emit('error', error));
10548 });
10549 mergedStream.once('close', () => propagateCloseEventToSources$1(streams));
10550 mergedStream.once('end', () => propagateCloseEventToSources$1(streams));
10551 return mergedStream;
10552}
10553stream$b.merge = merge$3;
10554function propagateCloseEventToSources$1(streams) {
10555 streams.forEach((stream) => stream.emit('close'));
10556}
10557
10558var string$4 = {};
10559
10560Object.defineProperty(string$4, "__esModule", { value: true });
10561string$4.isEmpty = string$4.isString = void 0;
10562function isString$2(input) {
10563 return typeof input === 'string';
10564}
10565string$4.isString = isString$2;
10566function isEmpty$1(input) {
10567 return input === '';
10568}
10569string$4.isEmpty = isEmpty$1;
10570
10571Object.defineProperty(utils$t, "__esModule", { value: true });
10572utils$t.string = utils$t.stream = utils$t.pattern = utils$t.path = utils$t.fs = utils$t.errno = utils$t.array = void 0;
10573const array$2 = array$3;
10574utils$t.array = array$2;
10575const errno$2 = errno$3;
10576utils$t.errno = errno$2;
10577const fs$u = fs$v;
10578utils$t.fs = fs$u;
10579const path$u = path$z;
10580utils$t.path = path$u;
10581const pattern$2 = pattern$3;
10582utils$t.pattern = pattern$2;
10583const stream$a = stream$b;
10584utils$t.stream = stream$a;
10585const string$3 = string$4;
10586utils$t.string = string$3;
10587
10588Object.defineProperty(tasks$1, "__esModule", { value: true });
10589tasks$1.convertPatternGroupToTask = tasks$1.convertPatternGroupsToTasks = tasks$1.groupPatternsByBaseDirectory = tasks$1.getNegativePatternsAsPositive = tasks$1.getPositivePatterns = tasks$1.convertPatternsToTasks = tasks$1.generate = void 0;
10590const utils$j = utils$t;
10591function generate$1(patterns, settings) {
10592 const positivePatterns = getPositivePatterns$2(patterns);
10593 const negativePatterns = getNegativePatternsAsPositive$1(patterns, settings.ignore);
10594 const staticPatterns = positivePatterns.filter((pattern) => utils$j.pattern.isStaticPattern(pattern, settings));
10595 const dynamicPatterns = positivePatterns.filter((pattern) => utils$j.pattern.isDynamicPattern(pattern, settings));
10596 const staticTasks = convertPatternsToTasks$1(staticPatterns, negativePatterns, /* dynamic */ false);
10597 const dynamicTasks = convertPatternsToTasks$1(dynamicPatterns, negativePatterns, /* dynamic */ true);
10598 return staticTasks.concat(dynamicTasks);
10599}
10600tasks$1.generate = generate$1;
10601/**
10602 * Returns tasks grouped by basic pattern directories.
10603 *
10604 * Patterns that can be found inside (`./`) and outside (`../`) the current directory are handled separately.
10605 * This is necessary because directory traversal starts at the base directory and goes deeper.
10606 */
10607function convertPatternsToTasks$1(positive, negative, dynamic) {
10608 const tasks = [];
10609 const patternsOutsideCurrentDirectory = utils$j.pattern.getPatternsOutsideCurrentDirectory(positive);
10610 const patternsInsideCurrentDirectory = utils$j.pattern.getPatternsInsideCurrentDirectory(positive);
10611 const outsideCurrentDirectoryGroup = groupPatternsByBaseDirectory$1(patternsOutsideCurrentDirectory);
10612 const insideCurrentDirectoryGroup = groupPatternsByBaseDirectory$1(patternsInsideCurrentDirectory);
10613 tasks.push(...convertPatternGroupsToTasks$1(outsideCurrentDirectoryGroup, [], dynamic));
10614 /*
10615 * For the sake of reducing future accesses to the file system, we merge all tasks within the current directory
10616 * into a global task, if at least one pattern refers to the root (`.`). In this case, the global task covers the rest.
10617 */
10618 if ('.' in insideCurrentDirectoryGroup) {
10619 tasks.push(convertPatternGroupToTask$1('.', patternsInsideCurrentDirectory, negative, dynamic));
10620 }
10621 else {
10622 tasks.push(...convertPatternGroupsToTasks$1(insideCurrentDirectoryGroup, negative, dynamic));
10623 }
10624 return tasks;
10625}
10626tasks$1.convertPatternsToTasks = convertPatternsToTasks$1;
10627function getPositivePatterns$2(patterns) {
10628 return utils$j.pattern.getPositivePatterns(patterns);
10629}
10630tasks$1.getPositivePatterns = getPositivePatterns$2;
10631function getNegativePatternsAsPositive$1(patterns, ignore) {
10632 const negative = utils$j.pattern.getNegativePatterns(patterns).concat(ignore);
10633 const positive = negative.map(utils$j.pattern.convertToPositivePattern);
10634 return positive;
10635}
10636tasks$1.getNegativePatternsAsPositive = getNegativePatternsAsPositive$1;
10637function groupPatternsByBaseDirectory$1(patterns) {
10638 const group = {};
10639 return patterns.reduce((collection, pattern) => {
10640 const base = utils$j.pattern.getBaseDirectory(pattern);
10641 if (base in collection) {
10642 collection[base].push(pattern);
10643 }
10644 else {
10645 collection[base] = [pattern];
10646 }
10647 return collection;
10648 }, group);
10649}
10650tasks$1.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory$1;
10651function convertPatternGroupsToTasks$1(positive, negative, dynamic) {
10652 return Object.keys(positive).map((base) => {
10653 return convertPatternGroupToTask$1(base, positive[base], negative, dynamic);
10654 });
10655}
10656tasks$1.convertPatternGroupsToTasks = convertPatternGroupsToTasks$1;
10657function convertPatternGroupToTask$1(base, positive, negative, dynamic) {
10658 return {
10659 dynamic,
10660 positive,
10661 negative,
10662 base,
10663 patterns: [].concat(positive, negative.map(utils$j.pattern.convertToNegativePattern))
10664 };
10665}
10666tasks$1.convertPatternGroupToTask = convertPatternGroupToTask$1;
10667
10668var async$7 = {};
10669
10670var stream$9 = {};
10671
10672var out$4 = {};
10673
10674var async$6 = {};
10675
10676Object.defineProperty(async$6, "__esModule", { value: true });
10677async$6.read = void 0;
10678function read$4(path, settings, callback) {
10679 settings.fs.lstat(path, (lstatError, lstat) => {
10680 if (lstatError !== null) {
10681 callFailureCallback$2(callback, lstatError);
10682 return;
10683 }
10684 if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
10685 callSuccessCallback$2(callback, lstat);
10686 return;
10687 }
10688 settings.fs.stat(path, (statError, stat) => {
10689 if (statError !== null) {
10690 if (settings.throwErrorOnBrokenSymbolicLink) {
10691 callFailureCallback$2(callback, statError);
10692 return;
10693 }
10694 callSuccessCallback$2(callback, lstat);
10695 return;
10696 }
10697 if (settings.markSymbolicLink) {
10698 stat.isSymbolicLink = () => true;
10699 }
10700 callSuccessCallback$2(callback, stat);
10701 });
10702 });
10703}
10704async$6.read = read$4;
10705function callFailureCallback$2(callback, error) {
10706 callback(error);
10707}
10708function callSuccessCallback$2(callback, result) {
10709 callback(null, result);
10710}
10711
10712var sync$d = {};
10713
10714Object.defineProperty(sync$d, "__esModule", { value: true });
10715sync$d.read = void 0;
10716function read$3(path, settings) {
10717 const lstat = settings.fs.lstatSync(path);
10718 if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
10719 return lstat;
10720 }
10721 try {
10722 const stat = settings.fs.statSync(path);
10723 if (settings.markSymbolicLink) {
10724 stat.isSymbolicLink = () => true;
10725 }
10726 return stat;
10727 }
10728 catch (error) {
10729 if (!settings.throwErrorOnBrokenSymbolicLink) {
10730 return lstat;
10731 }
10732 throw error;
10733 }
10734}
10735sync$d.read = read$3;
10736
10737var settings$4 = {};
10738
10739var fs$t = {};
10740
10741(function (exports) {
10742Object.defineProperty(exports, "__esModule", { value: true });
10743exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0;
10744const fs = fs__default;
10745exports.FILE_SYSTEM_ADAPTER = {
10746 lstat: fs.lstat,
10747 stat: fs.stat,
10748 lstatSync: fs.lstatSync,
10749 statSync: fs.statSync
10750};
10751function createFileSystemAdapter(fsMethods) {
10752 if (fsMethods === undefined) {
10753 return exports.FILE_SYSTEM_ADAPTER;
10754 }
10755 return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods);
10756}
10757exports.createFileSystemAdapter = createFileSystemAdapter;
10758}(fs$t));
10759
10760Object.defineProperty(settings$4, "__esModule", { value: true });
10761const fs$s = fs$t;
10762class Settings$2 {
10763 constructor(_options = {}) {
10764 this._options = _options;
10765 this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true);
10766 this.fs = fs$s.createFileSystemAdapter(this._options.fs);
10767 this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false);
10768 this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
10769 }
10770 _getValue(option, value) {
10771 return option !== null && option !== void 0 ? option : value;
10772 }
10773}
10774settings$4.default = Settings$2;
10775
10776Object.defineProperty(out$4, "__esModule", { value: true });
10777out$4.statSync = out$4.stat = out$4.Settings = void 0;
10778const async$5 = async$6;
10779const sync$c = sync$d;
10780const settings_1$4 = settings$4;
10781out$4.Settings = settings_1$4.default;
10782function stat$4(path, optionsOrSettingsOrCallback, callback) {
10783 if (typeof optionsOrSettingsOrCallback === 'function') {
10784 async$5.read(path, getSettings$2(), optionsOrSettingsOrCallback);
10785 return;
10786 }
10787 async$5.read(path, getSettings$2(optionsOrSettingsOrCallback), callback);
10788}
10789out$4.stat = stat$4;
10790function statSync(path, optionsOrSettings) {
10791 const settings = getSettings$2(optionsOrSettings);
10792 return sync$c.read(path, settings);
10793}
10794out$4.statSync = statSync;
10795function getSettings$2(settingsOrOptions = {}) {
10796 if (settingsOrOptions instanceof settings_1$4.default) {
10797 return settingsOrOptions;
10798 }
10799 return new settings_1$4.default(settingsOrOptions);
10800}
10801
10802var out$3 = {};
10803
10804var async$4 = {};
10805
10806var async$3 = {};
10807
10808var out$2 = {};
10809
10810var async$2 = {};
10811
10812/*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
10813
10814let promise$1;
10815
10816var queueMicrotask_1 = typeof queueMicrotask === 'function'
10817 ? queueMicrotask.bind(typeof window !== 'undefined' ? window : commonjsGlobal)
10818 // reuse resolved promise, and allocate it lazily
10819 : cb => (promise$1 || (promise$1 = Promise.resolve()))
10820 .then(cb)
10821 .catch(err => setTimeout(() => { throw err }, 0));
10822
10823/*! run-parallel. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
10824
10825var runParallel_1 = runParallel;
10826
10827const queueMicrotask$1 = queueMicrotask_1;
10828
10829function runParallel (tasks, cb) {
10830 let results, pending, keys;
10831 let isSync = true;
10832
10833 if (Array.isArray(tasks)) {
10834 results = [];
10835 pending = tasks.length;
10836 } else {
10837 keys = Object.keys(tasks);
10838 results = {};
10839 pending = keys.length;
10840 }
10841
10842 function done (err) {
10843 function end () {
10844 if (cb) cb(err, results);
10845 cb = null;
10846 }
10847 if (isSync) queueMicrotask$1(end);
10848 else end();
10849 }
10850
10851 function each (i, err, result) {
10852 results[i] = result;
10853 if (--pending === 0 || err) {
10854 done(err);
10855 }
10856 }
10857
10858 if (!pending) {
10859 // empty
10860 done(null);
10861 } else if (keys) {
10862 // object
10863 keys.forEach(function (key) {
10864 tasks[key](function (err, result) { each(key, err, result); });
10865 });
10866 } else {
10867 // array
10868 tasks.forEach(function (task, i) {
10869 task(function (err, result) { each(i, err, result); });
10870 });
10871 }
10872
10873 isSync = false;
10874}
10875
10876var constants$2 = {};
10877
10878Object.defineProperty(constants$2, "__esModule", { value: true });
10879constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES = void 0;
10880const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.');
10881if (NODE_PROCESS_VERSION_PARTS[0] === undefined || NODE_PROCESS_VERSION_PARTS[1] === undefined) {
10882 throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`);
10883}
10884const MAJOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[0], 10);
10885const MINOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[1], 10);
10886const SUPPORTED_MAJOR_VERSION = 10;
10887const SUPPORTED_MINOR_VERSION = 10;
10888const IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION;
10889const IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION;
10890/**
10891 * IS `true` for Node.js 10.10 and greater.
10892 */
10893constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR;
10894
10895var utils$i = {};
10896
10897var fs$r = {};
10898
10899Object.defineProperty(fs$r, "__esModule", { value: true });
10900fs$r.createDirentFromStats = void 0;
10901class DirentFromStats$1 {
10902 constructor(name, stats) {
10903 this.name = name;
10904 this.isBlockDevice = stats.isBlockDevice.bind(stats);
10905 this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
10906 this.isDirectory = stats.isDirectory.bind(stats);
10907 this.isFIFO = stats.isFIFO.bind(stats);
10908 this.isFile = stats.isFile.bind(stats);
10909 this.isSocket = stats.isSocket.bind(stats);
10910 this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
10911 }
10912}
10913function createDirentFromStats$1(name, stats) {
10914 return new DirentFromStats$1(name, stats);
10915}
10916fs$r.createDirentFromStats = createDirentFromStats$1;
10917
10918Object.defineProperty(utils$i, "__esModule", { value: true });
10919utils$i.fs = void 0;
10920const fs$q = fs$r;
10921utils$i.fs = fs$q;
10922
10923var common$e = {};
10924
10925Object.defineProperty(common$e, "__esModule", { value: true });
10926common$e.joinPathSegments = void 0;
10927function joinPathSegments$1(a, b, separator) {
10928 /**
10929 * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`).
10930 */
10931 if (a.endsWith(separator)) {
10932 return a + b;
10933 }
10934 return a + separator + b;
10935}
10936common$e.joinPathSegments = joinPathSegments$1;
10937
10938Object.defineProperty(async$2, "__esModule", { value: true });
10939async$2.readdir = async$2.readdirWithFileTypes = async$2.read = void 0;
10940const fsStat$8 = out$4;
10941const rpl = runParallel_1;
10942const constants_1$1 = constants$2;
10943const utils$h = utils$i;
10944const common$d = common$e;
10945function read$2(directory, settings, callback) {
10946 if (!settings.stats && constants_1$1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
10947 readdirWithFileTypes$1(directory, settings, callback);
10948 return;
10949 }
10950 readdir$3(directory, settings, callback);
10951}
10952async$2.read = read$2;
10953function readdirWithFileTypes$1(directory, settings, callback) {
10954 settings.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => {
10955 if (readdirError !== null) {
10956 callFailureCallback$1(callback, readdirError);
10957 return;
10958 }
10959 const entries = dirents.map((dirent) => ({
10960 dirent,
10961 name: dirent.name,
10962 path: common$d.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator)
10963 }));
10964 if (!settings.followSymbolicLinks) {
10965 callSuccessCallback$1(callback, entries);
10966 return;
10967 }
10968 const tasks = entries.map((entry) => makeRplTaskEntry(entry, settings));
10969 rpl(tasks, (rplError, rplEntries) => {
10970 if (rplError !== null) {
10971 callFailureCallback$1(callback, rplError);
10972 return;
10973 }
10974 callSuccessCallback$1(callback, rplEntries);
10975 });
10976 });
10977}
10978async$2.readdirWithFileTypes = readdirWithFileTypes$1;
10979function makeRplTaskEntry(entry, settings) {
10980 return (done) => {
10981 if (!entry.dirent.isSymbolicLink()) {
10982 done(null, entry);
10983 return;
10984 }
10985 settings.fs.stat(entry.path, (statError, stats) => {
10986 if (statError !== null) {
10987 if (settings.throwErrorOnBrokenSymbolicLink) {
10988 done(statError);
10989 return;
10990 }
10991 done(null, entry);
10992 return;
10993 }
10994 entry.dirent = utils$h.fs.createDirentFromStats(entry.name, stats);
10995 done(null, entry);
10996 });
10997 };
10998}
10999function readdir$3(directory, settings, callback) {
11000 settings.fs.readdir(directory, (readdirError, names) => {
11001 if (readdirError !== null) {
11002 callFailureCallback$1(callback, readdirError);
11003 return;
11004 }
11005 const tasks = names.map((name) => {
11006 const path = common$d.joinPathSegments(directory, name, settings.pathSegmentSeparator);
11007 return (done) => {
11008 fsStat$8.stat(path, settings.fsStatSettings, (error, stats) => {
11009 if (error !== null) {
11010 done(error);
11011 return;
11012 }
11013 const entry = {
11014 name,
11015 path,
11016 dirent: utils$h.fs.createDirentFromStats(name, stats)
11017 };
11018 if (settings.stats) {
11019 entry.stats = stats;
11020 }
11021 done(null, entry);
11022 });
11023 };
11024 });
11025 rpl(tasks, (rplError, entries) => {
11026 if (rplError !== null) {
11027 callFailureCallback$1(callback, rplError);
11028 return;
11029 }
11030 callSuccessCallback$1(callback, entries);
11031 });
11032 });
11033}
11034async$2.readdir = readdir$3;
11035function callFailureCallback$1(callback, error) {
11036 callback(error);
11037}
11038function callSuccessCallback$1(callback, result) {
11039 callback(null, result);
11040}
11041
11042var sync$b = {};
11043
11044Object.defineProperty(sync$b, "__esModule", { value: true });
11045sync$b.readdir = sync$b.readdirWithFileTypes = sync$b.read = void 0;
11046const fsStat$7 = out$4;
11047const constants_1 = constants$2;
11048const utils$g = utils$i;
11049const common$c = common$e;
11050function read$1(directory, settings) {
11051 if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
11052 return readdirWithFileTypes(directory, settings);
11053 }
11054 return readdir$2(directory, settings);
11055}
11056sync$b.read = read$1;
11057function readdirWithFileTypes(directory, settings) {
11058 const dirents = settings.fs.readdirSync(directory, { withFileTypes: true });
11059 return dirents.map((dirent) => {
11060 const entry = {
11061 dirent,
11062 name: dirent.name,
11063 path: common$c.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator)
11064 };
11065 if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) {
11066 try {
11067 const stats = settings.fs.statSync(entry.path);
11068 entry.dirent = utils$g.fs.createDirentFromStats(entry.name, stats);
11069 }
11070 catch (error) {
11071 if (settings.throwErrorOnBrokenSymbolicLink) {
11072 throw error;
11073 }
11074 }
11075 }
11076 return entry;
11077 });
11078}
11079sync$b.readdirWithFileTypes = readdirWithFileTypes;
11080function readdir$2(directory, settings) {
11081 const names = settings.fs.readdirSync(directory);
11082 return names.map((name) => {
11083 const entryPath = common$c.joinPathSegments(directory, name, settings.pathSegmentSeparator);
11084 const stats = fsStat$7.statSync(entryPath, settings.fsStatSettings);
11085 const entry = {
11086 name,
11087 path: entryPath,
11088 dirent: utils$g.fs.createDirentFromStats(name, stats)
11089 };
11090 if (settings.stats) {
11091 entry.stats = stats;
11092 }
11093 return entry;
11094 });
11095}
11096sync$b.readdir = readdir$2;
11097
11098var settings$3 = {};
11099
11100var fs$p = {};
11101
11102(function (exports) {
11103Object.defineProperty(exports, "__esModule", { value: true });
11104exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0;
11105const fs = fs__default;
11106exports.FILE_SYSTEM_ADAPTER = {
11107 lstat: fs.lstat,
11108 stat: fs.stat,
11109 lstatSync: fs.lstatSync,
11110 statSync: fs.statSync,
11111 readdir: fs.readdir,
11112 readdirSync: fs.readdirSync
11113};
11114function createFileSystemAdapter(fsMethods) {
11115 if (fsMethods === undefined) {
11116 return exports.FILE_SYSTEM_ADAPTER;
11117 }
11118 return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods);
11119}
11120exports.createFileSystemAdapter = createFileSystemAdapter;
11121}(fs$p));
11122
11123Object.defineProperty(settings$3, "__esModule", { value: true });
11124const path$t = path__default;
11125const fsStat$6 = out$4;
11126const fs$o = fs$p;
11127class Settings$1 {
11128 constructor(_options = {}) {
11129 this._options = _options;
11130 this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false);
11131 this.fs = fs$o.createFileSystemAdapter(this._options.fs);
11132 this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$t.sep);
11133 this.stats = this._getValue(this._options.stats, false);
11134 this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
11135 this.fsStatSettings = new fsStat$6.Settings({
11136 followSymbolicLink: this.followSymbolicLinks,
11137 fs: this.fs,
11138 throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink
11139 });
11140 }
11141 _getValue(option, value) {
11142 return option !== null && option !== void 0 ? option : value;
11143 }
11144}
11145settings$3.default = Settings$1;
11146
11147Object.defineProperty(out$2, "__esModule", { value: true });
11148out$2.Settings = out$2.scandirSync = out$2.scandir = void 0;
11149const async$1 = async$2;
11150const sync$a = sync$b;
11151const settings_1$3 = settings$3;
11152out$2.Settings = settings_1$3.default;
11153function scandir(path, optionsOrSettingsOrCallback, callback) {
11154 if (typeof optionsOrSettingsOrCallback === 'function') {
11155 async$1.read(path, getSettings$1(), optionsOrSettingsOrCallback);
11156 return;
11157 }
11158 async$1.read(path, getSettings$1(optionsOrSettingsOrCallback), callback);
11159}
11160out$2.scandir = scandir;
11161function scandirSync(path, optionsOrSettings) {
11162 const settings = getSettings$1(optionsOrSettings);
11163 return sync$a.read(path, settings);
11164}
11165out$2.scandirSync = scandirSync;
11166function getSettings$1(settingsOrOptions = {}) {
11167 if (settingsOrOptions instanceof settings_1$3.default) {
11168 return settingsOrOptions;
11169 }
11170 return new settings_1$3.default(settingsOrOptions);
11171}
11172
11173var queue = {exports: {}};
11174
11175function reusify$1 (Constructor) {
11176 var head = new Constructor();
11177 var tail = head;
11178
11179 function get () {
11180 var current = head;
11181
11182 if (current.next) {
11183 head = current.next;
11184 } else {
11185 head = new Constructor();
11186 tail = head;
11187 }
11188
11189 current.next = null;
11190
11191 return current
11192 }
11193
11194 function release (obj) {
11195 tail.next = obj;
11196 tail = obj;
11197 }
11198
11199 return {
11200 get: get,
11201 release: release
11202 }
11203}
11204
11205var reusify_1 = reusify$1;
11206
11207var reusify = reusify_1;
11208
11209function fastqueue (context, worker, concurrency) {
11210 if (typeof context === 'function') {
11211 concurrency = worker;
11212 worker = context;
11213 context = null;
11214 }
11215
11216 if (concurrency < 1) {
11217 throw new Error('fastqueue concurrency must be greater than 1')
11218 }
11219
11220 var cache = reusify(Task);
11221 var queueHead = null;
11222 var queueTail = null;
11223 var _running = 0;
11224 var errorHandler = null;
11225
11226 var self = {
11227 push: push,
11228 drain: noop$3,
11229 saturated: noop$3,
11230 pause: pause,
11231 paused: false,
11232 concurrency: concurrency,
11233 running: running,
11234 resume: resume,
11235 idle: idle,
11236 length: length,
11237 getQueue: getQueue,
11238 unshift: unshift,
11239 empty: noop$3,
11240 kill: kill,
11241 killAndDrain: killAndDrain,
11242 error: error
11243 };
11244
11245 return self
11246
11247 function running () {
11248 return _running
11249 }
11250
11251 function pause () {
11252 self.paused = true;
11253 }
11254
11255 function length () {
11256 var current = queueHead;
11257 var counter = 0;
11258
11259 while (current) {
11260 current = current.next;
11261 counter++;
11262 }
11263
11264 return counter
11265 }
11266
11267 function getQueue () {
11268 var current = queueHead;
11269 var tasks = [];
11270
11271 while (current) {
11272 tasks.push(current.value);
11273 current = current.next;
11274 }
11275
11276 return tasks
11277 }
11278
11279 function resume () {
11280 if (!self.paused) return
11281 self.paused = false;
11282 for (var i = 0; i < self.concurrency; i++) {
11283 _running++;
11284 release();
11285 }
11286 }
11287
11288 function idle () {
11289 return _running === 0 && self.length() === 0
11290 }
11291
11292 function push (value, done) {
11293 var current = cache.get();
11294
11295 current.context = context;
11296 current.release = release;
11297 current.value = value;
11298 current.callback = done || noop$3;
11299 current.errorHandler = errorHandler;
11300
11301 if (_running === self.concurrency || self.paused) {
11302 if (queueTail) {
11303 queueTail.next = current;
11304 queueTail = current;
11305 } else {
11306 queueHead = current;
11307 queueTail = current;
11308 self.saturated();
11309 }
11310 } else {
11311 _running++;
11312 worker.call(context, current.value, current.worked);
11313 }
11314 }
11315
11316 function unshift (value, done) {
11317 var current = cache.get();
11318
11319 current.context = context;
11320 current.release = release;
11321 current.value = value;
11322 current.callback = done || noop$3;
11323
11324 if (_running === self.concurrency || self.paused) {
11325 if (queueHead) {
11326 current.next = queueHead;
11327 queueHead = current;
11328 } else {
11329 queueHead = current;
11330 queueTail = current;
11331 self.saturated();
11332 }
11333 } else {
11334 _running++;
11335 worker.call(context, current.value, current.worked);
11336 }
11337 }
11338
11339 function release (holder) {
11340 if (holder) {
11341 cache.release(holder);
11342 }
11343 var next = queueHead;
11344 if (next) {
11345 if (!self.paused) {
11346 if (queueTail === queueHead) {
11347 queueTail = null;
11348 }
11349 queueHead = next.next;
11350 next.next = null;
11351 worker.call(context, next.value, next.worked);
11352 if (queueTail === null) {
11353 self.empty();
11354 }
11355 } else {
11356 _running--;
11357 }
11358 } else if (--_running === 0) {
11359 self.drain();
11360 }
11361 }
11362
11363 function kill () {
11364 queueHead = null;
11365 queueTail = null;
11366 self.drain = noop$3;
11367 }
11368
11369 function killAndDrain () {
11370 queueHead = null;
11371 queueTail = null;
11372 self.drain();
11373 self.drain = noop$3;
11374 }
11375
11376 function error (handler) {
11377 errorHandler = handler;
11378 }
11379}
11380
11381function noop$3 () {}
11382
11383function Task () {
11384 this.value = null;
11385 this.callback = noop$3;
11386 this.next = null;
11387 this.release = noop$3;
11388 this.context = null;
11389 this.errorHandler = null;
11390
11391 var self = this;
11392
11393 this.worked = function worked (err, result) {
11394 var callback = self.callback;
11395 var errorHandler = self.errorHandler;
11396 var val = self.value;
11397 self.value = null;
11398 self.callback = noop$3;
11399 if (self.errorHandler) {
11400 errorHandler(err, val);
11401 }
11402 callback.call(self.context, err, result);
11403 self.release(self);
11404 };
11405}
11406
11407function queueAsPromised (context, worker, concurrency) {
11408 if (typeof context === 'function') {
11409 concurrency = worker;
11410 worker = context;
11411 context = null;
11412 }
11413
11414 function asyncWrapper (arg, cb) {
11415 worker.call(this, arg)
11416 .then(function (res) {
11417 cb(null, res);
11418 }, cb);
11419 }
11420
11421 var queue = fastqueue(context, asyncWrapper, concurrency);
11422
11423 var pushCb = queue.push;
11424 var unshiftCb = queue.unshift;
11425
11426 queue.push = push;
11427 queue.unshift = unshift;
11428
11429 return queue
11430
11431 function push (value) {
11432 return new Promise(function (resolve, reject) {
11433 pushCb(value, function (err, result) {
11434 if (err) {
11435 reject(err);
11436 return
11437 }
11438 resolve(result);
11439 });
11440 })
11441 }
11442
11443 function unshift (value) {
11444 return new Promise(function (resolve, reject) {
11445 unshiftCb(value, function (err, result) {
11446 if (err) {
11447 reject(err);
11448 return
11449 }
11450 resolve(result);
11451 });
11452 })
11453 }
11454}
11455
11456queue.exports = fastqueue;
11457queue.exports.promise = queueAsPromised;
11458
11459var common$b = {};
11460
11461Object.defineProperty(common$b, "__esModule", { value: true });
11462common$b.joinPathSegments = common$b.replacePathSegmentSeparator = common$b.isAppliedFilter = common$b.isFatalError = void 0;
11463function isFatalError(settings, error) {
11464 if (settings.errorFilter === null) {
11465 return true;
11466 }
11467 return !settings.errorFilter(error);
11468}
11469common$b.isFatalError = isFatalError;
11470function isAppliedFilter(filter, value) {
11471 return filter === null || filter(value);
11472}
11473common$b.isAppliedFilter = isAppliedFilter;
11474function replacePathSegmentSeparator(filepath, separator) {
11475 return filepath.split(/[/\\]/).join(separator);
11476}
11477common$b.replacePathSegmentSeparator = replacePathSegmentSeparator;
11478function joinPathSegments(a, b, separator) {
11479 if (a === '') {
11480 return b;
11481 }
11482 /**
11483 * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`).
11484 */
11485 if (a.endsWith(separator)) {
11486 return a + b;
11487 }
11488 return a + separator + b;
11489}
11490common$b.joinPathSegments = joinPathSegments;
11491
11492var reader$2 = {};
11493
11494Object.defineProperty(reader$2, "__esModule", { value: true });
11495const common$a = common$b;
11496class Reader$2 {
11497 constructor(_root, _settings) {
11498 this._root = _root;
11499 this._settings = _settings;
11500 this._root = common$a.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator);
11501 }
11502}
11503reader$2.default = Reader$2;
11504
11505Object.defineProperty(async$3, "__esModule", { value: true });
11506const events_1 = require$$0__default$6;
11507const fsScandir$2 = out$2;
11508const fastq = queue.exports;
11509const common$9 = common$b;
11510const reader_1$5 = reader$2;
11511class AsyncReader extends reader_1$5.default {
11512 constructor(_root, _settings) {
11513 super(_root, _settings);
11514 this._settings = _settings;
11515 this._scandir = fsScandir$2.scandir;
11516 this._emitter = new events_1.EventEmitter();
11517 this._queue = fastq(this._worker.bind(this), this._settings.concurrency);
11518 this._isFatalError = false;
11519 this._isDestroyed = false;
11520 this._queue.drain = () => {
11521 if (!this._isFatalError) {
11522 this._emitter.emit('end');
11523 }
11524 };
11525 }
11526 read() {
11527 this._isFatalError = false;
11528 this._isDestroyed = false;
11529 setImmediate(() => {
11530 this._pushToQueue(this._root, this._settings.basePath);
11531 });
11532 return this._emitter;
11533 }
11534 get isDestroyed() {
11535 return this._isDestroyed;
11536 }
11537 destroy() {
11538 if (this._isDestroyed) {
11539 throw new Error('The reader is already destroyed');
11540 }
11541 this._isDestroyed = true;
11542 this._queue.killAndDrain();
11543 }
11544 onEntry(callback) {
11545 this._emitter.on('entry', callback);
11546 }
11547 onError(callback) {
11548 this._emitter.once('error', callback);
11549 }
11550 onEnd(callback) {
11551 this._emitter.once('end', callback);
11552 }
11553 _pushToQueue(directory, base) {
11554 const queueItem = { directory, base };
11555 this._queue.push(queueItem, (error) => {
11556 if (error !== null) {
11557 this._handleError(error);
11558 }
11559 });
11560 }
11561 _worker(item, done) {
11562 this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => {
11563 if (error !== null) {
11564 done(error, undefined);
11565 return;
11566 }
11567 for (const entry of entries) {
11568 this._handleEntry(entry, item.base);
11569 }
11570 done(null, undefined);
11571 });
11572 }
11573 _handleError(error) {
11574 if (this._isDestroyed || !common$9.isFatalError(this._settings, error)) {
11575 return;
11576 }
11577 this._isFatalError = true;
11578 this._isDestroyed = true;
11579 this._emitter.emit('error', error);
11580 }
11581 _handleEntry(entry, base) {
11582 if (this._isDestroyed || this._isFatalError) {
11583 return;
11584 }
11585 const fullpath = entry.path;
11586 if (base !== undefined) {
11587 entry.path = common$9.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
11588 }
11589 if (common$9.isAppliedFilter(this._settings.entryFilter, entry)) {
11590 this._emitEntry(entry);
11591 }
11592 if (entry.dirent.isDirectory() && common$9.isAppliedFilter(this._settings.deepFilter, entry)) {
11593 this._pushToQueue(fullpath, entry.path);
11594 }
11595 }
11596 _emitEntry(entry) {
11597 this._emitter.emit('entry', entry);
11598 }
11599}
11600async$3.default = AsyncReader;
11601
11602Object.defineProperty(async$4, "__esModule", { value: true });
11603const async_1$4 = async$3;
11604class AsyncProvider {
11605 constructor(_root, _settings) {
11606 this._root = _root;
11607 this._settings = _settings;
11608 this._reader = new async_1$4.default(this._root, this._settings);
11609 this._storage = new Set();
11610 }
11611 read(callback) {
11612 this._reader.onError((error) => {
11613 callFailureCallback(callback, error);
11614 });
11615 this._reader.onEntry((entry) => {
11616 this._storage.add(entry);
11617 });
11618 this._reader.onEnd(() => {
11619 callSuccessCallback(callback, [...this._storage]);
11620 });
11621 this._reader.read();
11622 }
11623}
11624async$4.default = AsyncProvider;
11625function callFailureCallback(callback, error) {
11626 callback(error);
11627}
11628function callSuccessCallback(callback, entries) {
11629 callback(null, entries);
11630}
11631
11632var stream$8 = {};
11633
11634Object.defineProperty(stream$8, "__esModule", { value: true });
11635const stream_1$9 = require$$0__default$2;
11636const async_1$3 = async$3;
11637class StreamProvider {
11638 constructor(_root, _settings) {
11639 this._root = _root;
11640 this._settings = _settings;
11641 this._reader = new async_1$3.default(this._root, this._settings);
11642 this._stream = new stream_1$9.Readable({
11643 objectMode: true,
11644 read: () => { },
11645 destroy: () => {
11646 if (!this._reader.isDestroyed) {
11647 this._reader.destroy();
11648 }
11649 }
11650 });
11651 }
11652 read() {
11653 this._reader.onError((error) => {
11654 this._stream.emit('error', error);
11655 });
11656 this._reader.onEntry((entry) => {
11657 this._stream.push(entry);
11658 });
11659 this._reader.onEnd(() => {
11660 this._stream.push(null);
11661 });
11662 this._reader.read();
11663 return this._stream;
11664 }
11665}
11666stream$8.default = StreamProvider;
11667
11668var sync$9 = {};
11669
11670var sync$8 = {};
11671
11672Object.defineProperty(sync$8, "__esModule", { value: true });
11673const fsScandir$1 = out$2;
11674const common$8 = common$b;
11675const reader_1$4 = reader$2;
11676class SyncReader extends reader_1$4.default {
11677 constructor() {
11678 super(...arguments);
11679 this._scandir = fsScandir$1.scandirSync;
11680 this._storage = new Set();
11681 this._queue = new Set();
11682 }
11683 read() {
11684 this._pushToQueue(this._root, this._settings.basePath);
11685 this._handleQueue();
11686 return [...this._storage];
11687 }
11688 _pushToQueue(directory, base) {
11689 this._queue.add({ directory, base });
11690 }
11691 _handleQueue() {
11692 for (const item of this._queue.values()) {
11693 this._handleDirectory(item.directory, item.base);
11694 }
11695 }
11696 _handleDirectory(directory, base) {
11697 try {
11698 const entries = this._scandir(directory, this._settings.fsScandirSettings);
11699 for (const entry of entries) {
11700 this._handleEntry(entry, base);
11701 }
11702 }
11703 catch (error) {
11704 this._handleError(error);
11705 }
11706 }
11707 _handleError(error) {
11708 if (!common$8.isFatalError(this._settings, error)) {
11709 return;
11710 }
11711 throw error;
11712 }
11713 _handleEntry(entry, base) {
11714 const fullpath = entry.path;
11715 if (base !== undefined) {
11716 entry.path = common$8.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
11717 }
11718 if (common$8.isAppliedFilter(this._settings.entryFilter, entry)) {
11719 this._pushToStorage(entry);
11720 }
11721 if (entry.dirent.isDirectory() && common$8.isAppliedFilter(this._settings.deepFilter, entry)) {
11722 this._pushToQueue(fullpath, entry.path);
11723 }
11724 }
11725 _pushToStorage(entry) {
11726 this._storage.add(entry);
11727 }
11728}
11729sync$8.default = SyncReader;
11730
11731Object.defineProperty(sync$9, "__esModule", { value: true });
11732const sync_1$5 = sync$8;
11733class SyncProvider {
11734 constructor(_root, _settings) {
11735 this._root = _root;
11736 this._settings = _settings;
11737 this._reader = new sync_1$5.default(this._root, this._settings);
11738 }
11739 read() {
11740 return this._reader.read();
11741 }
11742}
11743sync$9.default = SyncProvider;
11744
11745var settings$2 = {};
11746
11747Object.defineProperty(settings$2, "__esModule", { value: true });
11748const path$s = path__default;
11749const fsScandir = out$2;
11750class Settings {
11751 constructor(_options = {}) {
11752 this._options = _options;
11753 this.basePath = this._getValue(this._options.basePath, undefined);
11754 this.concurrency = this._getValue(this._options.concurrency, Number.POSITIVE_INFINITY);
11755 this.deepFilter = this._getValue(this._options.deepFilter, null);
11756 this.entryFilter = this._getValue(this._options.entryFilter, null);
11757 this.errorFilter = this._getValue(this._options.errorFilter, null);
11758 this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$s.sep);
11759 this.fsScandirSettings = new fsScandir.Settings({
11760 followSymbolicLinks: this._options.followSymbolicLinks,
11761 fs: this._options.fs,
11762 pathSegmentSeparator: this._options.pathSegmentSeparator,
11763 stats: this._options.stats,
11764 throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink
11765 });
11766 }
11767 _getValue(option, value) {
11768 return option !== null && option !== void 0 ? option : value;
11769 }
11770}
11771settings$2.default = Settings;
11772
11773Object.defineProperty(out$3, "__esModule", { value: true });
11774out$3.Settings = out$3.walkStream = out$3.walkSync = out$3.walk = void 0;
11775const async_1$2 = async$4;
11776const stream_1$8 = stream$8;
11777const sync_1$4 = sync$9;
11778const settings_1$2 = settings$2;
11779out$3.Settings = settings_1$2.default;
11780function walk$3(directory, optionsOrSettingsOrCallback, callback) {
11781 if (typeof optionsOrSettingsOrCallback === 'function') {
11782 new async_1$2.default(directory, getSettings()).read(optionsOrSettingsOrCallback);
11783 return;
11784 }
11785 new async_1$2.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback);
11786}
11787out$3.walk = walk$3;
11788function walkSync(directory, optionsOrSettings) {
11789 const settings = getSettings(optionsOrSettings);
11790 const provider = new sync_1$4.default(directory, settings);
11791 return provider.read();
11792}
11793out$3.walkSync = walkSync;
11794function walkStream(directory, optionsOrSettings) {
11795 const settings = getSettings(optionsOrSettings);
11796 const provider = new stream_1$8.default(directory, settings);
11797 return provider.read();
11798}
11799out$3.walkStream = walkStream;
11800function getSettings(settingsOrOptions = {}) {
11801 if (settingsOrOptions instanceof settings_1$2.default) {
11802 return settingsOrOptions;
11803 }
11804 return new settings_1$2.default(settingsOrOptions);
11805}
11806
11807var reader$1 = {};
11808
11809Object.defineProperty(reader$1, "__esModule", { value: true });
11810const path$r = path__default;
11811const fsStat$5 = out$4;
11812const utils$f = utils$t;
11813class Reader$1 {
11814 constructor(_settings) {
11815 this._settings = _settings;
11816 this._fsStatSettings = new fsStat$5.Settings({
11817 followSymbolicLink: this._settings.followSymbolicLinks,
11818 fs: this._settings.fs,
11819 throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks
11820 });
11821 }
11822 _getFullEntryPath(filepath) {
11823 return path$r.resolve(this._settings.cwd, filepath);
11824 }
11825 _makeEntry(stats, pattern) {
11826 const entry = {
11827 name: pattern,
11828 path: pattern,
11829 dirent: utils$f.fs.createDirentFromStats(pattern, stats)
11830 };
11831 if (this._settings.stats) {
11832 entry.stats = stats;
11833 }
11834 return entry;
11835 }
11836 _isFatalError(error) {
11837 return !utils$f.errno.isEnoentCodeError(error) && !this._settings.suppressErrors;
11838 }
11839}
11840reader$1.default = Reader$1;
11841
11842Object.defineProperty(stream$9, "__esModule", { value: true });
11843const stream_1$7 = require$$0__default$2;
11844const fsStat$4 = out$4;
11845const fsWalk$3 = out$3;
11846const reader_1$3 = reader$1;
11847class ReaderStream$1 extends reader_1$3.default {
11848 constructor() {
11849 super(...arguments);
11850 this._walkStream = fsWalk$3.walkStream;
11851 this._stat = fsStat$4.stat;
11852 }
11853 dynamic(root, options) {
11854 return this._walkStream(root, options);
11855 }
11856 static(patterns, options) {
11857 const filepaths = patterns.map(this._getFullEntryPath, this);
11858 const stream = new stream_1$7.PassThrough({ objectMode: true });
11859 stream._write = (index, _enc, done) => {
11860 return this._getEntry(filepaths[index], patterns[index], options)
11861 .then((entry) => {
11862 if (entry !== null && options.entryFilter(entry)) {
11863 stream.push(entry);
11864 }
11865 if (index === filepaths.length - 1) {
11866 stream.end();
11867 }
11868 done();
11869 })
11870 .catch(done);
11871 };
11872 for (let i = 0; i < filepaths.length; i++) {
11873 stream.write(i);
11874 }
11875 return stream;
11876 }
11877 _getEntry(filepath, pattern, options) {
11878 return this._getStat(filepath)
11879 .then((stats) => this._makeEntry(stats, pattern))
11880 .catch((error) => {
11881 if (options.errorFilter(error)) {
11882 return null;
11883 }
11884 throw error;
11885 });
11886 }
11887 _getStat(filepath) {
11888 return new Promise((resolve, reject) => {
11889 this._stat(filepath, this._fsStatSettings, (error, stats) => {
11890 return error === null ? resolve(stats) : reject(error);
11891 });
11892 });
11893 }
11894}
11895stream$9.default = ReaderStream$1;
11896
11897var provider$1 = {};
11898
11899var deep$1 = {};
11900
11901var partial$1 = {};
11902
11903var matcher$1 = {};
11904
11905Object.defineProperty(matcher$1, "__esModule", { value: true });
11906const utils$e = utils$t;
11907class Matcher$1 {
11908 constructor(_patterns, _settings, _micromatchOptions) {
11909 this._patterns = _patterns;
11910 this._settings = _settings;
11911 this._micromatchOptions = _micromatchOptions;
11912 this._storage = [];
11913 this._fillStorage();
11914 }
11915 _fillStorage() {
11916 /**
11917 * The original pattern may include `{,*,**,a/*}`, which will lead to problems with matching (unresolved level).
11918 * So, before expand patterns with brace expansion into separated patterns.
11919 */
11920 const patterns = utils$e.pattern.expandPatternsWithBraceExpansion(this._patterns);
11921 for (const pattern of patterns) {
11922 const segments = this._getPatternSegments(pattern);
11923 const sections = this._splitSegmentsIntoSections(segments);
11924 this._storage.push({
11925 complete: sections.length <= 1,
11926 pattern,
11927 segments,
11928 sections
11929 });
11930 }
11931 }
11932 _getPatternSegments(pattern) {
11933 const parts = utils$e.pattern.getPatternParts(pattern, this._micromatchOptions);
11934 return parts.map((part) => {
11935 const dynamic = utils$e.pattern.isDynamicPattern(part, this._settings);
11936 if (!dynamic) {
11937 return {
11938 dynamic: false,
11939 pattern: part
11940 };
11941 }
11942 return {
11943 dynamic: true,
11944 pattern: part,
11945 patternRe: utils$e.pattern.makeRe(part, this._micromatchOptions)
11946 };
11947 });
11948 }
11949 _splitSegmentsIntoSections(segments) {
11950 return utils$e.array.splitWhen(segments, (segment) => segment.dynamic && utils$e.pattern.hasGlobStar(segment.pattern));
11951 }
11952}
11953matcher$1.default = Matcher$1;
11954
11955Object.defineProperty(partial$1, "__esModule", { value: true });
11956const matcher_1$1 = matcher$1;
11957class PartialMatcher$1 extends matcher_1$1.default {
11958 match(filepath) {
11959 const parts = filepath.split('/');
11960 const levels = parts.length;
11961 const patterns = this._storage.filter((info) => !info.complete || info.segments.length > levels);
11962 for (const pattern of patterns) {
11963 const section = pattern.sections[0];
11964 /**
11965 * In this case, the pattern has a globstar and we must read all directories unconditionally,
11966 * but only if the level has reached the end of the first group.
11967 *
11968 * fixtures/{a,b}/**
11969 * ^ true/false ^ always true
11970 */
11971 if (!pattern.complete && levels > section.length) {
11972 return true;
11973 }
11974 const match = parts.every((part, index) => {
11975 const segment = pattern.segments[index];
11976 if (segment.dynamic && segment.patternRe.test(part)) {
11977 return true;
11978 }
11979 if (!segment.dynamic && segment.pattern === part) {
11980 return true;
11981 }
11982 return false;
11983 });
11984 if (match) {
11985 return true;
11986 }
11987 }
11988 return false;
11989 }
11990}
11991partial$1.default = PartialMatcher$1;
11992
11993Object.defineProperty(deep$1, "__esModule", { value: true });
11994const utils$d = utils$t;
11995const partial_1$1 = partial$1;
11996class DeepFilter$1 {
11997 constructor(_settings, _micromatchOptions) {
11998 this._settings = _settings;
11999 this._micromatchOptions = _micromatchOptions;
12000 }
12001 getFilter(basePath, positive, negative) {
12002 const matcher = this._getMatcher(positive);
12003 const negativeRe = this._getNegativePatternsRe(negative);
12004 return (entry) => this._filter(basePath, entry, matcher, negativeRe);
12005 }
12006 _getMatcher(patterns) {
12007 return new partial_1$1.default(patterns, this._settings, this._micromatchOptions);
12008 }
12009 _getNegativePatternsRe(patterns) {
12010 const affectDepthOfReadingPatterns = patterns.filter(utils$d.pattern.isAffectDepthOfReadingPattern);
12011 return utils$d.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions);
12012 }
12013 _filter(basePath, entry, matcher, negativeRe) {
12014 if (this._isSkippedByDeep(basePath, entry.path)) {
12015 return false;
12016 }
12017 if (this._isSkippedSymbolicLink(entry)) {
12018 return false;
12019 }
12020 const filepath = utils$d.path.removeLeadingDotSegment(entry.path);
12021 if (this._isSkippedByPositivePatterns(filepath, matcher)) {
12022 return false;
12023 }
12024 return this._isSkippedByNegativePatterns(filepath, negativeRe);
12025 }
12026 _isSkippedByDeep(basePath, entryPath) {
12027 /**
12028 * Avoid unnecessary depth calculations when it doesn't matter.
12029 */
12030 if (this._settings.deep === Infinity) {
12031 return false;
12032 }
12033 return this._getEntryLevel(basePath, entryPath) >= this._settings.deep;
12034 }
12035 _getEntryLevel(basePath, entryPath) {
12036 const entryPathDepth = entryPath.split('/').length;
12037 if (basePath === '') {
12038 return entryPathDepth;
12039 }
12040 const basePathDepth = basePath.split('/').length;
12041 return entryPathDepth - basePathDepth;
12042 }
12043 _isSkippedSymbolicLink(entry) {
12044 return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink();
12045 }
12046 _isSkippedByPositivePatterns(entryPath, matcher) {
12047 return !this._settings.baseNameMatch && !matcher.match(entryPath);
12048 }
12049 _isSkippedByNegativePatterns(entryPath, patternsRe) {
12050 return !utils$d.pattern.matchAny(entryPath, patternsRe);
12051 }
12052}
12053deep$1.default = DeepFilter$1;
12054
12055var entry$3 = {};
12056
12057Object.defineProperty(entry$3, "__esModule", { value: true });
12058const utils$c = utils$t;
12059class EntryFilter$1 {
12060 constructor(_settings, _micromatchOptions) {
12061 this._settings = _settings;
12062 this._micromatchOptions = _micromatchOptions;
12063 this.index = new Map();
12064 }
12065 getFilter(positive, negative) {
12066 const positiveRe = utils$c.pattern.convertPatternsToRe(positive, this._micromatchOptions);
12067 const negativeRe = utils$c.pattern.convertPatternsToRe(negative, this._micromatchOptions);
12068 return (entry) => this._filter(entry, positiveRe, negativeRe);
12069 }
12070 _filter(entry, positiveRe, negativeRe) {
12071 if (this._settings.unique && this._isDuplicateEntry(entry)) {
12072 return false;
12073 }
12074 if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) {
12075 return false;
12076 }
12077 if (this._isSkippedByAbsoluteNegativePatterns(entry.path, negativeRe)) {
12078 return false;
12079 }
12080 const filepath = this._settings.baseNameMatch ? entry.name : entry.path;
12081 const isMatched = this._isMatchToPatterns(filepath, positiveRe) && !this._isMatchToPatterns(entry.path, negativeRe);
12082 if (this._settings.unique && isMatched) {
12083 this._createIndexRecord(entry);
12084 }
12085 return isMatched;
12086 }
12087 _isDuplicateEntry(entry) {
12088 return this.index.has(entry.path);
12089 }
12090 _createIndexRecord(entry) {
12091 this.index.set(entry.path, undefined);
12092 }
12093 _onlyFileFilter(entry) {
12094 return this._settings.onlyFiles && !entry.dirent.isFile();
12095 }
12096 _onlyDirectoryFilter(entry) {
12097 return this._settings.onlyDirectories && !entry.dirent.isDirectory();
12098 }
12099 _isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) {
12100 if (!this._settings.absolute) {
12101 return false;
12102 }
12103 const fullpath = utils$c.path.makeAbsolute(this._settings.cwd, entryPath);
12104 return utils$c.pattern.matchAny(fullpath, patternsRe);
12105 }
12106 _isMatchToPatterns(entryPath, patternsRe) {
12107 const filepath = utils$c.path.removeLeadingDotSegment(entryPath);
12108 return utils$c.pattern.matchAny(filepath, patternsRe);
12109 }
12110}
12111entry$3.default = EntryFilter$1;
12112
12113var error$5 = {};
12114
12115Object.defineProperty(error$5, "__esModule", { value: true });
12116const utils$b = utils$t;
12117class ErrorFilter$1 {
12118 constructor(_settings) {
12119 this._settings = _settings;
12120 }
12121 getFilter() {
12122 return (error) => this._isNonFatalError(error);
12123 }
12124 _isNonFatalError(error) {
12125 return utils$b.errno.isEnoentCodeError(error) || this._settings.suppressErrors;
12126 }
12127}
12128error$5.default = ErrorFilter$1;
12129
12130var entry$2 = {};
12131
12132Object.defineProperty(entry$2, "__esModule", { value: true });
12133const utils$a = utils$t;
12134class EntryTransformer$1 {
12135 constructor(_settings) {
12136 this._settings = _settings;
12137 }
12138 getTransformer() {
12139 return (entry) => this._transform(entry);
12140 }
12141 _transform(entry) {
12142 let filepath = entry.path;
12143 if (this._settings.absolute) {
12144 filepath = utils$a.path.makeAbsolute(this._settings.cwd, filepath);
12145 filepath = utils$a.path.unixify(filepath);
12146 }
12147 if (this._settings.markDirectories && entry.dirent.isDirectory()) {
12148 filepath += '/';
12149 }
12150 if (!this._settings.objectMode) {
12151 return filepath;
12152 }
12153 return Object.assign(Object.assign({}, entry), { path: filepath });
12154 }
12155}
12156entry$2.default = EntryTransformer$1;
12157
12158Object.defineProperty(provider$1, "__esModule", { value: true });
12159const path$q = path__default;
12160const deep_1$1 = deep$1;
12161const entry_1$1 = entry$3;
12162const error_1$1 = error$5;
12163const entry_2$1 = entry$2;
12164class Provider$1 {
12165 constructor(_settings) {
12166 this._settings = _settings;
12167 this.errorFilter = new error_1$1.default(this._settings);
12168 this.entryFilter = new entry_1$1.default(this._settings, this._getMicromatchOptions());
12169 this.deepFilter = new deep_1$1.default(this._settings, this._getMicromatchOptions());
12170 this.entryTransformer = new entry_2$1.default(this._settings);
12171 }
12172 _getRootDirectory(task) {
12173 return path$q.resolve(this._settings.cwd, task.base);
12174 }
12175 _getReaderOptions(task) {
12176 const basePath = task.base === '.' ? '' : task.base;
12177 return {
12178 basePath,
12179 pathSegmentSeparator: '/',
12180 concurrency: this._settings.concurrency,
12181 deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative),
12182 entryFilter: this.entryFilter.getFilter(task.positive, task.negative),
12183 errorFilter: this.errorFilter.getFilter(),
12184 followSymbolicLinks: this._settings.followSymbolicLinks,
12185 fs: this._settings.fs,
12186 stats: this._settings.stats,
12187 throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink,
12188 transform: this.entryTransformer.getTransformer()
12189 };
12190 }
12191 _getMicromatchOptions() {
12192 return {
12193 dot: this._settings.dot,
12194 matchBase: this._settings.baseNameMatch,
12195 nobrace: !this._settings.braceExpansion,
12196 nocase: !this._settings.caseSensitiveMatch,
12197 noext: !this._settings.extglob,
12198 noglobstar: !this._settings.globstar,
12199 posix: true,
12200 strictSlashes: false
12201 };
12202 }
12203}
12204provider$1.default = Provider$1;
12205
12206Object.defineProperty(async$7, "__esModule", { value: true });
12207const stream_1$6 = stream$9;
12208const provider_1$5 = provider$1;
12209class ProviderAsync$1 extends provider_1$5.default {
12210 constructor() {
12211 super(...arguments);
12212 this._reader = new stream_1$6.default(this._settings);
12213 }
12214 read(task) {
12215 const root = this._getRootDirectory(task);
12216 const options = this._getReaderOptions(task);
12217 const entries = [];
12218 return new Promise((resolve, reject) => {
12219 const stream = this.api(root, task, options);
12220 stream.once('error', reject);
12221 stream.on('data', (entry) => entries.push(options.transform(entry)));
12222 stream.once('end', () => resolve(entries));
12223 });
12224 }
12225 api(root, task, options) {
12226 if (task.dynamic) {
12227 return this._reader.dynamic(root, options);
12228 }
12229 return this._reader.static(task.patterns, options);
12230 }
12231}
12232async$7.default = ProviderAsync$1;
12233
12234var stream$7 = {};
12235
12236Object.defineProperty(stream$7, "__esModule", { value: true });
12237const stream_1$5 = require$$0__default$2;
12238const stream_2$1 = stream$9;
12239const provider_1$4 = provider$1;
12240class ProviderStream$1 extends provider_1$4.default {
12241 constructor() {
12242 super(...arguments);
12243 this._reader = new stream_2$1.default(this._settings);
12244 }
12245 read(task) {
12246 const root = this._getRootDirectory(task);
12247 const options = this._getReaderOptions(task);
12248 const source = this.api(root, task, options);
12249 const destination = new stream_1$5.Readable({ objectMode: true, read: () => { } });
12250 source
12251 .once('error', (error) => destination.emit('error', error))
12252 .on('data', (entry) => destination.emit('data', options.transform(entry)))
12253 .once('end', () => destination.emit('end'));
12254 destination
12255 .once('close', () => source.destroy());
12256 return destination;
12257 }
12258 api(root, task, options) {
12259 if (task.dynamic) {
12260 return this._reader.dynamic(root, options);
12261 }
12262 return this._reader.static(task.patterns, options);
12263 }
12264}
12265stream$7.default = ProviderStream$1;
12266
12267var sync$7 = {};
12268
12269var sync$6 = {};
12270
12271Object.defineProperty(sync$6, "__esModule", { value: true });
12272const fsStat$3 = out$4;
12273const fsWalk$2 = out$3;
12274const reader_1$2 = reader$1;
12275class ReaderSync$1 extends reader_1$2.default {
12276 constructor() {
12277 super(...arguments);
12278 this._walkSync = fsWalk$2.walkSync;
12279 this._statSync = fsStat$3.statSync;
12280 }
12281 dynamic(root, options) {
12282 return this._walkSync(root, options);
12283 }
12284 static(patterns, options) {
12285 const entries = [];
12286 for (const pattern of patterns) {
12287 const filepath = this._getFullEntryPath(pattern);
12288 const entry = this._getEntry(filepath, pattern, options);
12289 if (entry === null || !options.entryFilter(entry)) {
12290 continue;
12291 }
12292 entries.push(entry);
12293 }
12294 return entries;
12295 }
12296 _getEntry(filepath, pattern, options) {
12297 try {
12298 const stats = this._getStat(filepath);
12299 return this._makeEntry(stats, pattern);
12300 }
12301 catch (error) {
12302 if (options.errorFilter(error)) {
12303 return null;
12304 }
12305 throw error;
12306 }
12307 }
12308 _getStat(filepath) {
12309 return this._statSync(filepath, this._fsStatSettings);
12310 }
12311}
12312sync$6.default = ReaderSync$1;
12313
12314Object.defineProperty(sync$7, "__esModule", { value: true });
12315const sync_1$3 = sync$6;
12316const provider_1$3 = provider$1;
12317class ProviderSync$1 extends provider_1$3.default {
12318 constructor() {
12319 super(...arguments);
12320 this._reader = new sync_1$3.default(this._settings);
12321 }
12322 read(task) {
12323 const root = this._getRootDirectory(task);
12324 const options = this._getReaderOptions(task);
12325 const entries = this.api(root, task, options);
12326 return entries.map(options.transform);
12327 }
12328 api(root, task, options) {
12329 if (task.dynamic) {
12330 return this._reader.dynamic(root, options);
12331 }
12332 return this._reader.static(task.patterns, options);
12333 }
12334}
12335sync$7.default = ProviderSync$1;
12336
12337var settings$1 = {};
12338
12339(function (exports) {
12340Object.defineProperty(exports, "__esModule", { value: true });
12341exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0;
12342const fs = fs__default;
12343const os = require$$0__default$1;
12344/**
12345 * The `os.cpus` method can return zero. We expect the number of cores to be greater than zero.
12346 * https://github.com/nodejs/node/blob/7faeddf23a98c53896f8b574a6e66589e8fb1eb8/lib/os.js#L106-L107
12347 */
12348const CPU_COUNT = Math.max(os.cpus().length, 1);
12349exports.DEFAULT_FILE_SYSTEM_ADAPTER = {
12350 lstat: fs.lstat,
12351 lstatSync: fs.lstatSync,
12352 stat: fs.stat,
12353 statSync: fs.statSync,
12354 readdir: fs.readdir,
12355 readdirSync: fs.readdirSync
12356};
12357class Settings {
12358 constructor(_options = {}) {
12359 this._options = _options;
12360 this.absolute = this._getValue(this._options.absolute, false);
12361 this.baseNameMatch = this._getValue(this._options.baseNameMatch, false);
12362 this.braceExpansion = this._getValue(this._options.braceExpansion, true);
12363 this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true);
12364 this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT);
12365 this.cwd = this._getValue(this._options.cwd, process.cwd());
12366 this.deep = this._getValue(this._options.deep, Infinity);
12367 this.dot = this._getValue(this._options.dot, false);
12368 this.extglob = this._getValue(this._options.extglob, true);
12369 this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true);
12370 this.fs = this._getFileSystemMethods(this._options.fs);
12371 this.globstar = this._getValue(this._options.globstar, true);
12372 this.ignore = this._getValue(this._options.ignore, []);
12373 this.markDirectories = this._getValue(this._options.markDirectories, false);
12374 this.objectMode = this._getValue(this._options.objectMode, false);
12375 this.onlyDirectories = this._getValue(this._options.onlyDirectories, false);
12376 this.onlyFiles = this._getValue(this._options.onlyFiles, true);
12377 this.stats = this._getValue(this._options.stats, false);
12378 this.suppressErrors = this._getValue(this._options.suppressErrors, false);
12379 this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false);
12380 this.unique = this._getValue(this._options.unique, true);
12381 if (this.onlyDirectories) {
12382 this.onlyFiles = false;
12383 }
12384 if (this.stats) {
12385 this.objectMode = true;
12386 }
12387 }
12388 _getValue(option, value) {
12389 return option === undefined ? value : option;
12390 }
12391 _getFileSystemMethods(methods = {}) {
12392 return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods);
12393 }
12394}
12395exports.default = Settings;
12396}(settings$1));
12397
12398const taskManager$1 = tasks$1;
12399const async_1$1 = async$7;
12400const stream_1$4 = stream$7;
12401const sync_1$2 = sync$7;
12402const settings_1$1 = settings$1;
12403const utils$9 = utils$t;
12404async function FastGlob$1(source, options) {
12405 assertPatternsInput$2(source);
12406 const works = getWorks$1(source, async_1$1.default, options);
12407 const result = await Promise.all(works);
12408 return utils$9.array.flatten(result);
12409}
12410// https://github.com/typescript-eslint/typescript-eslint/issues/60
12411// eslint-disable-next-line no-redeclare
12412(function (FastGlob) {
12413 function sync(source, options) {
12414 assertPatternsInput$2(source);
12415 const works = getWorks$1(source, sync_1$2.default, options);
12416 return utils$9.array.flatten(works);
12417 }
12418 FastGlob.sync = sync;
12419 function stream(source, options) {
12420 assertPatternsInput$2(source);
12421 const works = getWorks$1(source, stream_1$4.default, options);
12422 /**
12423 * The stream returned by the provider cannot work with an asynchronous iterator.
12424 * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams.
12425 * This affects performance (+25%). I don't see best solution right now.
12426 */
12427 return utils$9.stream.merge(works);
12428 }
12429 FastGlob.stream = stream;
12430 function generateTasks(source, options) {
12431 assertPatternsInput$2(source);
12432 const patterns = [].concat(source);
12433 const settings = new settings_1$1.default(options);
12434 return taskManager$1.generate(patterns, settings);
12435 }
12436 FastGlob.generateTasks = generateTasks;
12437 function isDynamicPattern(source, options) {
12438 assertPatternsInput$2(source);
12439 const settings = new settings_1$1.default(options);
12440 return utils$9.pattern.isDynamicPattern(source, settings);
12441 }
12442 FastGlob.isDynamicPattern = isDynamicPattern;
12443 function escapePath(source) {
12444 assertPatternsInput$2(source);
12445 return utils$9.path.escape(source);
12446 }
12447 FastGlob.escapePath = escapePath;
12448})(FastGlob$1 || (FastGlob$1 = {}));
12449function getWorks$1(source, _Provider, options) {
12450 const patterns = [].concat(source);
12451 const settings = new settings_1$1.default(options);
12452 const tasks = taskManager$1.generate(patterns, settings);
12453 const provider = new _Provider(settings);
12454 return tasks.map(provider.read, provider);
12455}
12456function assertPatternsInput$2(input) {
12457 const source = [].concat(input);
12458 const isValidSource = source.every((item) => utils$9.string.isString(item) && !utils$9.string.isEmpty(item));
12459 if (!isValidSource) {
12460 throw new TypeError('Patterns must be a string (non empty) or an array of strings');
12461 }
12462}
12463var out$1 = FastGlob$1;
12464
12465var dist$3 = {};
12466
12467(function (exports) {
12468Object.defineProperty(exports, "__esModule", { value: true });
12469exports.lilconfigSync = exports.lilconfig = exports.defaultLoaders = void 0;
12470const path = path__default;
12471const fs = fs__default;
12472const os = require$$0__default$1;
12473const fsReadFileAsync = fs.promises.readFile;
12474function getDefaultSearchPlaces(name) {
12475 return [
12476 'package.json',
12477 `.${name}rc.json`,
12478 `.${name}rc.js`,
12479 `${name}.config.js`,
12480 `.${name}rc.cjs`,
12481 `${name}.config.cjs`,
12482 ];
12483}
12484function getSearchPaths(startDir, stopDir) {
12485 return startDir
12486 .split(path.sep)
12487 .reduceRight((acc, _, ind, arr) => {
12488 const currentPath = arr.slice(0, ind + 1).join(path.sep);
12489 if (!acc.passedStopDir)
12490 acc.searchPlaces.push(currentPath || path.sep);
12491 if (currentPath === stopDir)
12492 acc.passedStopDir = true;
12493 return acc;
12494 }, { searchPlaces: [], passedStopDir: false }).searchPlaces;
12495}
12496exports.defaultLoaders = Object.freeze({
12497 '.js': eval('require'),
12498 '.json': eval('require'),
12499 '.cjs': eval('require'),
12500 noExt(_, content) {
12501 return JSON.parse(content);
12502 },
12503});
12504function getExtDesc(ext) {
12505 return ext === 'noExt' ? 'files without extensions' : `extension "${ext}"`;
12506}
12507function getOptions(name, options = {}) {
12508 const conf = {
12509 stopDir: os.homedir(),
12510 searchPlaces: getDefaultSearchPlaces(name),
12511 ignoreEmptySearchPlaces: true,
12512 transform: (x) => x,
12513 packageProp: [name],
12514 ...options,
12515 loaders: { ...exports.defaultLoaders, ...options.loaders },
12516 };
12517 conf.searchPlaces.forEach(place => {
12518 const key = path.extname(place) || 'noExt';
12519 const loader = conf.loaders[key];
12520 if (!loader) {
12521 throw new Error(`No loader specified for ${getExtDesc(key)}, so searchPlaces item "${place}" is invalid`);
12522 }
12523 if (typeof loader !== 'function') {
12524 throw new Error(`loader for ${getExtDesc(key)} is not a function (type provided: "${typeof loader}"), so searchPlaces item "${place}" is invalid`);
12525 }
12526 });
12527 return conf;
12528}
12529function getPackageProp(props, obj) {
12530 if (typeof props === 'string' && props in obj)
12531 return obj[props];
12532 return ((Array.isArray(props) ? props : props.split('.')).reduce((acc, prop) => (acc === undefined ? acc : acc[prop]), obj) || null);
12533}
12534function getSearchItems(searchPlaces, searchPaths) {
12535 return searchPaths.reduce((acc, searchPath) => {
12536 searchPlaces.forEach(fileName => acc.push({
12537 fileName,
12538 filepath: path.join(searchPath, fileName),
12539 loaderKey: path.extname(fileName) || 'noExt',
12540 }));
12541 return acc;
12542 }, []);
12543}
12544function validateFilePath(filepath) {
12545 if (!filepath)
12546 throw new Error('load must pass a non-empty string');
12547}
12548function validateLoader(loader, ext) {
12549 if (!loader)
12550 throw new Error(`No loader specified for extension "${ext}"`);
12551 if (typeof loader !== 'function')
12552 throw new Error('loader is not a function');
12553}
12554function lilconfig(name, options) {
12555 const { ignoreEmptySearchPlaces, loaders, packageProp, searchPlaces, stopDir, transform, } = getOptions(name, options);
12556 return {
12557 async search(searchFrom = process.cwd()) {
12558 const searchPaths = getSearchPaths(searchFrom, stopDir);
12559 const result = {
12560 config: null,
12561 filepath: '',
12562 };
12563 const searchItems = getSearchItems(searchPlaces, searchPaths);
12564 for (const { fileName, filepath, loaderKey } of searchItems) {
12565 try {
12566 await fs.promises.access(filepath);
12567 }
12568 catch (_a) {
12569 continue;
12570 }
12571 const content = String(await fsReadFileAsync(filepath));
12572 const loader = loaders[loaderKey];
12573 if (fileName === 'package.json') {
12574 const pkg = loader(filepath, content);
12575 const maybeConfig = getPackageProp(packageProp, pkg);
12576 if (maybeConfig != null) {
12577 result.config = maybeConfig;
12578 result.filepath = filepath;
12579 break;
12580 }
12581 continue;
12582 }
12583 const isEmpty = content.trim() === '';
12584 if (isEmpty && ignoreEmptySearchPlaces)
12585 continue;
12586 if (isEmpty) {
12587 result.isEmpty = true;
12588 result.config = undefined;
12589 }
12590 else {
12591 validateLoader(loader, loaderKey);
12592 result.config = loader(filepath, content);
12593 }
12594 result.filepath = filepath;
12595 break;
12596 }
12597 if (result.filepath === '' && result.config === null)
12598 return transform(null);
12599 return transform(result);
12600 },
12601 async load(filepath) {
12602 validateFilePath(filepath);
12603 const { base, ext } = path.parse(filepath);
12604 const loaderKey = ext || 'noExt';
12605 const loader = loaders[loaderKey];
12606 validateLoader(loader, loaderKey);
12607 const content = String(await fsReadFileAsync(filepath));
12608 if (base === 'package.json') {
12609 const pkg = await loader(filepath, content);
12610 return transform({
12611 config: getPackageProp(packageProp, pkg),
12612 filepath,
12613 });
12614 }
12615 const result = {
12616 config: null,
12617 filepath,
12618 };
12619 const isEmpty = content.trim() === '';
12620 if (isEmpty && ignoreEmptySearchPlaces)
12621 return transform({
12622 config: undefined,
12623 filepath,
12624 isEmpty: true,
12625 });
12626 result.config = isEmpty
12627 ? undefined
12628 : await loader(filepath, content);
12629 return transform(isEmpty ? { ...result, isEmpty, config: undefined } : result);
12630 },
12631 };
12632}
12633exports.lilconfig = lilconfig;
12634function lilconfigSync(name, options) {
12635 const { ignoreEmptySearchPlaces, loaders, packageProp, searchPlaces, stopDir, transform, } = getOptions(name, options);
12636 return {
12637 search(searchFrom = process.cwd()) {
12638 const searchPaths = getSearchPaths(searchFrom, stopDir);
12639 const result = {
12640 config: null,
12641 filepath: '',
12642 };
12643 const searchItems = getSearchItems(searchPlaces, searchPaths);
12644 for (const { fileName, filepath, loaderKey } of searchItems) {
12645 try {
12646 fs.accessSync(filepath);
12647 }
12648 catch (_a) {
12649 continue;
12650 }
12651 const loader = loaders[loaderKey];
12652 const content = String(fs.readFileSync(filepath));
12653 if (fileName === 'package.json') {
12654 const pkg = loader(filepath, content);
12655 const maybeConfig = getPackageProp(packageProp, pkg);
12656 if (maybeConfig != null) {
12657 result.config = maybeConfig;
12658 result.filepath = filepath;
12659 break;
12660 }
12661 continue;
12662 }
12663 const isEmpty = content.trim() === '';
12664 if (isEmpty && ignoreEmptySearchPlaces)
12665 continue;
12666 if (isEmpty) {
12667 result.isEmpty = true;
12668 result.config = undefined;
12669 }
12670 else {
12671 validateLoader(loader, loaderKey);
12672 result.config = loader(filepath, content);
12673 }
12674 result.filepath = filepath;
12675 break;
12676 }
12677 if (result.filepath === '' && result.config === null)
12678 return transform(null);
12679 return transform(result);
12680 },
12681 load(filepath) {
12682 validateFilePath(filepath);
12683 const { base, ext } = path.parse(filepath);
12684 const loaderKey = ext || 'noExt';
12685 const loader = loaders[loaderKey];
12686 validateLoader(loader, loaderKey);
12687 const content = String(fs.readFileSync(filepath));
12688 if (base === 'package.json') {
12689 const pkg = loader(filepath, content);
12690 return transform({
12691 config: getPackageProp(packageProp, pkg),
12692 filepath,
12693 });
12694 }
12695 const result = {
12696 config: null,
12697 filepath,
12698 };
12699 const isEmpty = content.trim() === '';
12700 if (isEmpty && ignoreEmptySearchPlaces)
12701 return transform({
12702 filepath,
12703 config: undefined,
12704 isEmpty: true,
12705 });
12706 result.config = isEmpty ? undefined : loader(filepath, content);
12707 return transform(isEmpty ? { ...result, isEmpty, config: undefined } : result);
12708 },
12709 };
12710}
12711exports.lilconfigSync = lilconfigSync;
12712}(dist$3));
12713
12714var dist$2 = {};
12715
12716var parseCst$1 = {};
12717
12718var PlainValueEc8e588e = {};
12719
12720const Char = {
12721 ANCHOR: '&',
12722 COMMENT: '#',
12723 TAG: '!',
12724 DIRECTIVES_END: '-',
12725 DOCUMENT_END: '.'
12726};
12727const Type = {
12728 ALIAS: 'ALIAS',
12729 BLANK_LINE: 'BLANK_LINE',
12730 BLOCK_FOLDED: 'BLOCK_FOLDED',
12731 BLOCK_LITERAL: 'BLOCK_LITERAL',
12732 COMMENT: 'COMMENT',
12733 DIRECTIVE: 'DIRECTIVE',
12734 DOCUMENT: 'DOCUMENT',
12735 FLOW_MAP: 'FLOW_MAP',
12736 FLOW_SEQ: 'FLOW_SEQ',
12737 MAP: 'MAP',
12738 MAP_KEY: 'MAP_KEY',
12739 MAP_VALUE: 'MAP_VALUE',
12740 PLAIN: 'PLAIN',
12741 QUOTE_DOUBLE: 'QUOTE_DOUBLE',
12742 QUOTE_SINGLE: 'QUOTE_SINGLE',
12743 SEQ: 'SEQ',
12744 SEQ_ITEM: 'SEQ_ITEM'
12745};
12746const defaultTagPrefix = 'tag:yaml.org,2002:';
12747const defaultTags = {
12748 MAP: 'tag:yaml.org,2002:map',
12749 SEQ: 'tag:yaml.org,2002:seq',
12750 STR: 'tag:yaml.org,2002:str'
12751};
12752
12753function findLineStarts(src) {
12754 const ls = [0];
12755 let offset = src.indexOf('\n');
12756
12757 while (offset !== -1) {
12758 offset += 1;
12759 ls.push(offset);
12760 offset = src.indexOf('\n', offset);
12761 }
12762
12763 return ls;
12764}
12765
12766function getSrcInfo(cst) {
12767 let lineStarts, src;
12768
12769 if (typeof cst === 'string') {
12770 lineStarts = findLineStarts(cst);
12771 src = cst;
12772 } else {
12773 if (Array.isArray(cst)) cst = cst[0];
12774
12775 if (cst && cst.context) {
12776 if (!cst.lineStarts) cst.lineStarts = findLineStarts(cst.context.src);
12777 lineStarts = cst.lineStarts;
12778 src = cst.context.src;
12779 }
12780 }
12781
12782 return {
12783 lineStarts,
12784 src
12785 };
12786}
12787/**
12788 * @typedef {Object} LinePos - One-indexed position in the source
12789 * @property {number} line
12790 * @property {number} col
12791 */
12792
12793/**
12794 * Determine the line/col position matching a character offset.
12795 *
12796 * Accepts a source string or a CST document as the second parameter. With
12797 * the latter, starting indices for lines are cached in the document as
12798 * `lineStarts: number[]`.
12799 *
12800 * Returns a one-indexed `{ line, col }` location if found, or
12801 * `undefined` otherwise.
12802 *
12803 * @param {number} offset
12804 * @param {string|Document|Document[]} cst
12805 * @returns {?LinePos}
12806 */
12807
12808
12809function getLinePos(offset, cst) {
12810 if (typeof offset !== 'number' || offset < 0) return null;
12811 const {
12812 lineStarts,
12813 src
12814 } = getSrcInfo(cst);
12815 if (!lineStarts || !src || offset > src.length) return null;
12816
12817 for (let i = 0; i < lineStarts.length; ++i) {
12818 const start = lineStarts[i];
12819
12820 if (offset < start) {
12821 return {
12822 line: i,
12823 col: offset - lineStarts[i - 1] + 1
12824 };
12825 }
12826
12827 if (offset === start) return {
12828 line: i + 1,
12829 col: 1
12830 };
12831 }
12832
12833 const line = lineStarts.length;
12834 return {
12835 line,
12836 col: offset - lineStarts[line - 1] + 1
12837 };
12838}
12839/**
12840 * Get a specified line from the source.
12841 *
12842 * Accepts a source string or a CST document as the second parameter. With
12843 * the latter, starting indices for lines are cached in the document as
12844 * `lineStarts: number[]`.
12845 *
12846 * Returns the line as a string if found, or `null` otherwise.
12847 *
12848 * @param {number} line One-indexed line number
12849 * @param {string|Document|Document[]} cst
12850 * @returns {?string}
12851 */
12852
12853function getLine(line, cst) {
12854 const {
12855 lineStarts,
12856 src
12857 } = getSrcInfo(cst);
12858 if (!lineStarts || !(line >= 1) || line > lineStarts.length) return null;
12859 const start = lineStarts[line - 1];
12860 let end = lineStarts[line]; // undefined for last line; that's ok for slice()
12861
12862 while (end && end > start && src[end - 1] === '\n') --end;
12863
12864 return src.slice(start, end);
12865}
12866/**
12867 * Pretty-print the starting line from the source indicated by the range `pos`
12868 *
12869 * Trims output to `maxWidth` chars while keeping the starting column visible,
12870 * using `…` at either end to indicate dropped characters.
12871 *
12872 * Returns a two-line string (or `null`) with `\n` as separator; the second line
12873 * will hold appropriately indented `^` marks indicating the column range.
12874 *
12875 * @param {Object} pos
12876 * @param {LinePos} pos.start
12877 * @param {LinePos} [pos.end]
12878 * @param {string|Document|Document[]*} cst
12879 * @param {number} [maxWidth=80]
12880 * @returns {?string}
12881 */
12882
12883function getPrettyContext({
12884 start,
12885 end
12886}, cst, maxWidth = 80) {
12887 let src = getLine(start.line, cst);
12888 if (!src) return null;
12889 let {
12890 col
12891 } = start;
12892
12893 if (src.length > maxWidth) {
12894 if (col <= maxWidth - 10) {
12895 src = src.substr(0, maxWidth - 1) + '…';
12896 } else {
12897 const halfWidth = Math.round(maxWidth / 2);
12898 if (src.length > col + halfWidth) src = src.substr(0, col + halfWidth - 1) + '…';
12899 col -= src.length - maxWidth;
12900 src = '…' + src.substr(1 - maxWidth);
12901 }
12902 }
12903
12904 let errLen = 1;
12905 let errEnd = '';
12906
12907 if (end) {
12908 if (end.line === start.line && col + (end.col - start.col) <= maxWidth + 1) {
12909 errLen = end.col - start.col;
12910 } else {
12911 errLen = Math.min(src.length + 1, maxWidth) - col;
12912 errEnd = '…';
12913 }
12914 }
12915
12916 const offset = col > 1 ? ' '.repeat(col - 1) : '';
12917 const err = '^'.repeat(errLen);
12918 return `${src}\n${offset}${err}${errEnd}`;
12919}
12920
12921class Range {
12922 static copy(orig) {
12923 return new Range(orig.start, orig.end);
12924 }
12925
12926 constructor(start, end) {
12927 this.start = start;
12928 this.end = end || start;
12929 }
12930
12931 isEmpty() {
12932 return typeof this.start !== 'number' || !this.end || this.end <= this.start;
12933 }
12934 /**
12935 * Set `origStart` and `origEnd` to point to the original source range for
12936 * this node, which may differ due to dropped CR characters.
12937 *
12938 * @param {number[]} cr - Positions of dropped CR characters
12939 * @param {number} offset - Starting index of `cr` from the last call
12940 * @returns {number} - The next offset, matching the one found for `origStart`
12941 */
12942
12943
12944 setOrigRange(cr, offset) {
12945 const {
12946 start,
12947 end
12948 } = this;
12949
12950 if (cr.length === 0 || end <= cr[0]) {
12951 this.origStart = start;
12952 this.origEnd = end;
12953 return offset;
12954 }
12955
12956 let i = offset;
12957
12958 while (i < cr.length) {
12959 if (cr[i] > start) break;else ++i;
12960 }
12961
12962 this.origStart = start + i;
12963 const nextOffset = i;
12964
12965 while (i < cr.length) {
12966 // if end was at \n, it should now be at \r
12967 if (cr[i] >= end) break;else ++i;
12968 }
12969
12970 this.origEnd = end + i;
12971 return nextOffset;
12972 }
12973
12974}
12975
12976/** Root class of all nodes */
12977
12978class Node$2 {
12979 static addStringTerminator(src, offset, str) {
12980 if (str[str.length - 1] === '\n') return str;
12981 const next = Node$2.endOfWhiteSpace(src, offset);
12982 return next >= src.length || src[next] === '\n' ? str + '\n' : str;
12983 } // ^(---|...)
12984
12985
12986 static atDocumentBoundary(src, offset, sep) {
12987 const ch0 = src[offset];
12988 if (!ch0) return true;
12989 const prev = src[offset - 1];
12990 if (prev && prev !== '\n') return false;
12991
12992 if (sep) {
12993 if (ch0 !== sep) return false;
12994 } else {
12995 if (ch0 !== Char.DIRECTIVES_END && ch0 !== Char.DOCUMENT_END) return false;
12996 }
12997
12998 const ch1 = src[offset + 1];
12999 const ch2 = src[offset + 2];
13000 if (ch1 !== ch0 || ch2 !== ch0) return false;
13001 const ch3 = src[offset + 3];
13002 return !ch3 || ch3 === '\n' || ch3 === '\t' || ch3 === ' ';
13003 }
13004
13005 static endOfIdentifier(src, offset) {
13006 let ch = src[offset];
13007 const isVerbatim = ch === '<';
13008 const notOk = isVerbatim ? ['\n', '\t', ' ', '>'] : ['\n', '\t', ' ', '[', ']', '{', '}', ','];
13009
13010 while (ch && notOk.indexOf(ch) === -1) ch = src[offset += 1];
13011
13012 if (isVerbatim && ch === '>') offset += 1;
13013 return offset;
13014 }
13015
13016 static endOfIndent(src, offset) {
13017 let ch = src[offset];
13018
13019 while (ch === ' ') ch = src[offset += 1];
13020
13021 return offset;
13022 }
13023
13024 static endOfLine(src, offset) {
13025 let ch = src[offset];
13026
13027 while (ch && ch !== '\n') ch = src[offset += 1];
13028
13029 return offset;
13030 }
13031
13032 static endOfWhiteSpace(src, offset) {
13033 let ch = src[offset];
13034
13035 while (ch === '\t' || ch === ' ') ch = src[offset += 1];
13036
13037 return offset;
13038 }
13039
13040 static startOfLine(src, offset) {
13041 let ch = src[offset - 1];
13042 if (ch === '\n') return offset;
13043
13044 while (ch && ch !== '\n') ch = src[offset -= 1];
13045
13046 return offset + 1;
13047 }
13048 /**
13049 * End of indentation, or null if the line's indent level is not more
13050 * than `indent`
13051 *
13052 * @param {string} src
13053 * @param {number} indent
13054 * @param {number} lineStart
13055 * @returns {?number}
13056 */
13057
13058
13059 static endOfBlockIndent(src, indent, lineStart) {
13060 const inEnd = Node$2.endOfIndent(src, lineStart);
13061
13062 if (inEnd > lineStart + indent) {
13063 return inEnd;
13064 } else {
13065 const wsEnd = Node$2.endOfWhiteSpace(src, inEnd);
13066 const ch = src[wsEnd];
13067 if (!ch || ch === '\n') return wsEnd;
13068 }
13069
13070 return null;
13071 }
13072
13073 static atBlank(src, offset, endAsBlank) {
13074 const ch = src[offset];
13075 return ch === '\n' || ch === '\t' || ch === ' ' || endAsBlank && !ch;
13076 }
13077
13078 static nextNodeIsIndented(ch, indentDiff, indicatorAsIndent) {
13079 if (!ch || indentDiff < 0) return false;
13080 if (indentDiff > 0) return true;
13081 return indicatorAsIndent && ch === '-';
13082 } // should be at line or string end, or at next non-whitespace char
13083
13084
13085 static normalizeOffset(src, offset) {
13086 const ch = src[offset];
13087 return !ch ? offset : ch !== '\n' && src[offset - 1] === '\n' ? offset - 1 : Node$2.endOfWhiteSpace(src, offset);
13088 } // fold single newline into space, multiple newlines to N - 1 newlines
13089 // presumes src[offset] === '\n'
13090
13091
13092 static foldNewline(src, offset, indent) {
13093 let inCount = 0;
13094 let error = false;
13095 let fold = '';
13096 let ch = src[offset + 1];
13097
13098 while (ch === ' ' || ch === '\t' || ch === '\n') {
13099 switch (ch) {
13100 case '\n':
13101 inCount = 0;
13102 offset += 1;
13103 fold += '\n';
13104 break;
13105
13106 case '\t':
13107 if (inCount <= indent) error = true;
13108 offset = Node$2.endOfWhiteSpace(src, offset + 2) - 1;
13109 break;
13110
13111 case ' ':
13112 inCount += 1;
13113 offset += 1;
13114 break;
13115 }
13116
13117 ch = src[offset + 1];
13118 }
13119
13120 if (!fold) fold = ' ';
13121 if (ch && inCount <= indent) error = true;
13122 return {
13123 fold,
13124 offset,
13125 error
13126 };
13127 }
13128
13129 constructor(type, props, context) {
13130 Object.defineProperty(this, 'context', {
13131 value: context || null,
13132 writable: true
13133 });
13134 this.error = null;
13135 this.range = null;
13136 this.valueRange = null;
13137 this.props = props || [];
13138 this.type = type;
13139 this.value = null;
13140 }
13141
13142 getPropValue(idx, key, skipKey) {
13143 if (!this.context) return null;
13144 const {
13145 src
13146 } = this.context;
13147 const prop = this.props[idx];
13148 return prop && src[prop.start] === key ? src.slice(prop.start + (skipKey ? 1 : 0), prop.end) : null;
13149 }
13150
13151 get anchor() {
13152 for (let i = 0; i < this.props.length; ++i) {
13153 const anchor = this.getPropValue(i, Char.ANCHOR, true);
13154 if (anchor != null) return anchor;
13155 }
13156
13157 return null;
13158 }
13159
13160 get comment() {
13161 const comments = [];
13162
13163 for (let i = 0; i < this.props.length; ++i) {
13164 const comment = this.getPropValue(i, Char.COMMENT, true);
13165 if (comment != null) comments.push(comment);
13166 }
13167
13168 return comments.length > 0 ? comments.join('\n') : null;
13169 }
13170
13171 commentHasRequiredWhitespace(start) {
13172 const {
13173 src
13174 } = this.context;
13175 if (this.header && start === this.header.end) return false;
13176 if (!this.valueRange) return false;
13177 const {
13178 end
13179 } = this.valueRange;
13180 return start !== end || Node$2.atBlank(src, end - 1);
13181 }
13182
13183 get hasComment() {
13184 if (this.context) {
13185 const {
13186 src
13187 } = this.context;
13188
13189 for (let i = 0; i < this.props.length; ++i) {
13190 if (src[this.props[i].start] === Char.COMMENT) return true;
13191 }
13192 }
13193
13194 return false;
13195 }
13196
13197 get hasProps() {
13198 if (this.context) {
13199 const {
13200 src
13201 } = this.context;
13202
13203 for (let i = 0; i < this.props.length; ++i) {
13204 if (src[this.props[i].start] !== Char.COMMENT) return true;
13205 }
13206 }
13207
13208 return false;
13209 }
13210
13211 get includesTrailingLines() {
13212 return false;
13213 }
13214
13215 get jsonLike() {
13216 const jsonLikeTypes = [Type.FLOW_MAP, Type.FLOW_SEQ, Type.QUOTE_DOUBLE, Type.QUOTE_SINGLE];
13217 return jsonLikeTypes.indexOf(this.type) !== -1;
13218 }
13219
13220 get rangeAsLinePos() {
13221 if (!this.range || !this.context) return undefined;
13222 const start = getLinePos(this.range.start, this.context.root);
13223 if (!start) return undefined;
13224 const end = getLinePos(this.range.end, this.context.root);
13225 return {
13226 start,
13227 end
13228 };
13229 }
13230
13231 get rawValue() {
13232 if (!this.valueRange || !this.context) return null;
13233 const {
13234 start,
13235 end
13236 } = this.valueRange;
13237 return this.context.src.slice(start, end);
13238 }
13239
13240 get tag() {
13241 for (let i = 0; i < this.props.length; ++i) {
13242 const tag = this.getPropValue(i, Char.TAG, false);
13243
13244 if (tag != null) {
13245 if (tag[1] === '<') {
13246 return {
13247 verbatim: tag.slice(2, -1)
13248 };
13249 } else {
13250 // eslint-disable-next-line no-unused-vars
13251 const [_, handle, suffix] = tag.match(/^(.*!)([^!]*)$/);
13252 return {
13253 handle,
13254 suffix
13255 };
13256 }
13257 }
13258 }
13259
13260 return null;
13261 }
13262
13263 get valueRangeContainsNewline() {
13264 if (!this.valueRange || !this.context) return false;
13265 const {
13266 start,
13267 end
13268 } = this.valueRange;
13269 const {
13270 src
13271 } = this.context;
13272
13273 for (let i = start; i < end; ++i) {
13274 if (src[i] === '\n') return true;
13275 }
13276
13277 return false;
13278 }
13279
13280 parseComment(start) {
13281 const {
13282 src
13283 } = this.context;
13284
13285 if (src[start] === Char.COMMENT) {
13286 const end = Node$2.endOfLine(src, start + 1);
13287 const commentRange = new Range(start, end);
13288 this.props.push(commentRange);
13289 return end;
13290 }
13291
13292 return start;
13293 }
13294 /**
13295 * Populates the `origStart` and `origEnd` values of all ranges for this
13296 * node. Extended by child classes to handle descendant nodes.
13297 *
13298 * @param {number[]} cr - Positions of dropped CR characters
13299 * @param {number} offset - Starting index of `cr` from the last call
13300 * @returns {number} - The next offset, matching the one found for `origStart`
13301 */
13302
13303
13304 setOrigRanges(cr, offset) {
13305 if (this.range) offset = this.range.setOrigRange(cr, offset);
13306 if (this.valueRange) this.valueRange.setOrigRange(cr, offset);
13307 this.props.forEach(prop => prop.setOrigRange(cr, offset));
13308 return offset;
13309 }
13310
13311 toString() {
13312 const {
13313 context: {
13314 src
13315 },
13316 range,
13317 value
13318 } = this;
13319 if (value != null) return value;
13320 const str = src.slice(range.start, range.end);
13321 return Node$2.addStringTerminator(src, range.end, str);
13322 }
13323
13324}
13325
13326class YAMLError extends Error {
13327 constructor(name, source, message) {
13328 if (!message || !(source instanceof Node$2)) throw new Error(`Invalid arguments for new ${name}`);
13329 super();
13330 this.name = name;
13331 this.message = message;
13332 this.source = source;
13333 }
13334
13335 makePretty() {
13336 if (!this.source) return;
13337 this.nodeType = this.source.type;
13338 const cst = this.source.context && this.source.context.root;
13339
13340 if (typeof this.offset === 'number') {
13341 this.range = new Range(this.offset, this.offset + 1);
13342 const start = cst && getLinePos(this.offset, cst);
13343
13344 if (start) {
13345 const end = {
13346 line: start.line,
13347 col: start.col + 1
13348 };
13349 this.linePos = {
13350 start,
13351 end
13352 };
13353 }
13354
13355 delete this.offset;
13356 } else {
13357 this.range = this.source.range;
13358 this.linePos = this.source.rangeAsLinePos;
13359 }
13360
13361 if (this.linePos) {
13362 const {
13363 line,
13364 col
13365 } = this.linePos.start;
13366 this.message += ` at line ${line}, column ${col}`;
13367 const ctx = cst && getPrettyContext(this.linePos, cst);
13368 if (ctx) this.message += `:\n\n${ctx}\n`;
13369 }
13370
13371 delete this.source;
13372 }
13373
13374}
13375class YAMLReferenceError extends YAMLError {
13376 constructor(source, message) {
13377 super('YAMLReferenceError', source, message);
13378 }
13379
13380}
13381class YAMLSemanticError extends YAMLError {
13382 constructor(source, message) {
13383 super('YAMLSemanticError', source, message);
13384 }
13385
13386}
13387class YAMLSyntaxError extends YAMLError {
13388 constructor(source, message) {
13389 super('YAMLSyntaxError', source, message);
13390 }
13391
13392}
13393class YAMLWarning extends YAMLError {
13394 constructor(source, message) {
13395 super('YAMLWarning', source, message);
13396 }
13397
13398}
13399
13400function _defineProperty(obj, key, value) {
13401 if (key in obj) {
13402 Object.defineProperty(obj, key, {
13403 value: value,
13404 enumerable: true,
13405 configurable: true,
13406 writable: true
13407 });
13408 } else {
13409 obj[key] = value;
13410 }
13411
13412 return obj;
13413}
13414
13415class PlainValue$6 extends Node$2 {
13416 static endOfLine(src, start, inFlow) {
13417 let ch = src[start];
13418 let offset = start;
13419
13420 while (ch && ch !== '\n') {
13421 if (inFlow && (ch === '[' || ch === ']' || ch === '{' || ch === '}' || ch === ',')) break;
13422 const next = src[offset + 1];
13423 if (ch === ':' && (!next || next === '\n' || next === '\t' || next === ' ' || inFlow && next === ',')) break;
13424 if ((ch === ' ' || ch === '\t') && next === '#') break;
13425 offset += 1;
13426 ch = next;
13427 }
13428
13429 return offset;
13430 }
13431
13432 get strValue() {
13433 if (!this.valueRange || !this.context) return null;
13434 let {
13435 start,
13436 end
13437 } = this.valueRange;
13438 const {
13439 src
13440 } = this.context;
13441 let ch = src[end - 1];
13442
13443 while (start < end && (ch === '\n' || ch === '\t' || ch === ' ')) ch = src[--end - 1];
13444
13445 let str = '';
13446
13447 for (let i = start; i < end; ++i) {
13448 const ch = src[i];
13449
13450 if (ch === '\n') {
13451 const {
13452 fold,
13453 offset
13454 } = Node$2.foldNewline(src, i, -1);
13455 str += fold;
13456 i = offset;
13457 } else if (ch === ' ' || ch === '\t') {
13458 // trim trailing whitespace
13459 const wsStart = i;
13460 let next = src[i + 1];
13461
13462 while (i < end && (next === ' ' || next === '\t')) {
13463 i += 1;
13464 next = src[i + 1];
13465 }
13466
13467 if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch;
13468 } else {
13469 str += ch;
13470 }
13471 }
13472
13473 const ch0 = src[start];
13474
13475 switch (ch0) {
13476 case '\t':
13477 {
13478 const msg = 'Plain value cannot start with a tab character';
13479 const errors = [new YAMLSemanticError(this, msg)];
13480 return {
13481 errors,
13482 str
13483 };
13484 }
13485
13486 case '@':
13487 case '`':
13488 {
13489 const msg = `Plain value cannot start with reserved character ${ch0}`;
13490 const errors = [new YAMLSemanticError(this, msg)];
13491 return {
13492 errors,
13493 str
13494 };
13495 }
13496
13497 default:
13498 return str;
13499 }
13500 }
13501
13502 parseBlockValue(start) {
13503 const {
13504 indent,
13505 inFlow,
13506 src
13507 } = this.context;
13508 let offset = start;
13509 let valueEnd = start;
13510
13511 for (let ch = src[offset]; ch === '\n'; ch = src[offset]) {
13512 if (Node$2.atDocumentBoundary(src, offset + 1)) break;
13513 const end = Node$2.endOfBlockIndent(src, indent, offset + 1);
13514 if (end === null || src[end] === '#') break;
13515
13516 if (src[end] === '\n') {
13517 offset = end;
13518 } else {
13519 valueEnd = PlainValue$6.endOfLine(src, end, inFlow);
13520 offset = valueEnd;
13521 }
13522 }
13523
13524 if (this.valueRange.isEmpty()) this.valueRange.start = start;
13525 this.valueRange.end = valueEnd;
13526 return valueEnd;
13527 }
13528 /**
13529 * Parses a plain value from the source
13530 *
13531 * Accepted forms are:
13532 * ```
13533 * #comment
13534 *
13535 * first line
13536 *
13537 * first line #comment
13538 *
13539 * first line
13540 * block
13541 * lines
13542 *
13543 * #comment
13544 * block
13545 * lines
13546 * ```
13547 * where block lines are empty or have an indent level greater than `indent`.
13548 *
13549 * @param {ParseContext} context
13550 * @param {number} start - Index of first character
13551 * @returns {number} - Index of the character after this scalar, may be `\n`
13552 */
13553
13554
13555 parse(context, start) {
13556 this.context = context;
13557 const {
13558 inFlow,
13559 src
13560 } = context;
13561 let offset = start;
13562 const ch = src[offset];
13563
13564 if (ch && ch !== '#' && ch !== '\n') {
13565 offset = PlainValue$6.endOfLine(src, start, inFlow);
13566 }
13567
13568 this.valueRange = new Range(start, offset);
13569 offset = Node$2.endOfWhiteSpace(src, offset);
13570 offset = this.parseComment(offset);
13571
13572 if (!this.hasComment || this.valueRange.isEmpty()) {
13573 offset = this.parseBlockValue(offset);
13574 }
13575
13576 return offset;
13577 }
13578
13579}
13580
13581PlainValueEc8e588e.Char = Char;
13582PlainValueEc8e588e.Node = Node$2;
13583PlainValueEc8e588e.PlainValue = PlainValue$6;
13584PlainValueEc8e588e.Range = Range;
13585PlainValueEc8e588e.Type = Type;
13586PlainValueEc8e588e.YAMLError = YAMLError;
13587PlainValueEc8e588e.YAMLReferenceError = YAMLReferenceError;
13588PlainValueEc8e588e.YAMLSemanticError = YAMLSemanticError;
13589PlainValueEc8e588e.YAMLSyntaxError = YAMLSyntaxError;
13590PlainValueEc8e588e.YAMLWarning = YAMLWarning;
13591PlainValueEc8e588e._defineProperty = _defineProperty;
13592PlainValueEc8e588e.defaultTagPrefix = defaultTagPrefix;
13593PlainValueEc8e588e.defaultTags = defaultTags;
13594
13595var PlainValue$5 = PlainValueEc8e588e;
13596
13597class BlankLine extends PlainValue$5.Node {
13598 constructor() {
13599 super(PlainValue$5.Type.BLANK_LINE);
13600 }
13601 /* istanbul ignore next */
13602
13603
13604 get includesTrailingLines() {
13605 // This is never called from anywhere, but if it were,
13606 // this is the value it should return.
13607 return true;
13608 }
13609 /**
13610 * Parses a blank line from the source
13611 *
13612 * @param {ParseContext} context
13613 * @param {number} start - Index of first \n character
13614 * @returns {number} - Index of the character after this
13615 */
13616
13617
13618 parse(context, start) {
13619 this.context = context;
13620 this.range = new PlainValue$5.Range(start, start + 1);
13621 return start + 1;
13622 }
13623
13624}
13625
13626class CollectionItem extends PlainValue$5.Node {
13627 constructor(type, props) {
13628 super(type, props);
13629 this.node = null;
13630 }
13631
13632 get includesTrailingLines() {
13633 return !!this.node && this.node.includesTrailingLines;
13634 }
13635 /**
13636 * @param {ParseContext} context
13637 * @param {number} start - Index of first character
13638 * @returns {number} - Index of the character after this
13639 */
13640
13641
13642 parse(context, start) {
13643 this.context = context;
13644 const {
13645 parseNode,
13646 src
13647 } = context;
13648 let {
13649 atLineStart,
13650 lineStart
13651 } = context;
13652 if (!atLineStart && this.type === PlainValue$5.Type.SEQ_ITEM) this.error = new PlainValue$5.YAMLSemanticError(this, 'Sequence items must not have preceding content on the same line');
13653 const indent = atLineStart ? start - lineStart : context.indent;
13654 let offset = PlainValue$5.Node.endOfWhiteSpace(src, start + 1);
13655 let ch = src[offset];
13656 const inlineComment = ch === '#';
13657 const comments = [];
13658 let blankLine = null;
13659
13660 while (ch === '\n' || ch === '#') {
13661 if (ch === '#') {
13662 const end = PlainValue$5.Node.endOfLine(src, offset + 1);
13663 comments.push(new PlainValue$5.Range(offset, end));
13664 offset = end;
13665 } else {
13666 atLineStart = true;
13667 lineStart = offset + 1;
13668 const wsEnd = PlainValue$5.Node.endOfWhiteSpace(src, lineStart);
13669
13670 if (src[wsEnd] === '\n' && comments.length === 0) {
13671 blankLine = new BlankLine();
13672 lineStart = blankLine.parse({
13673 src
13674 }, lineStart);
13675 }
13676
13677 offset = PlainValue$5.Node.endOfIndent(src, lineStart);
13678 }
13679
13680 ch = src[offset];
13681 }
13682
13683 if (PlainValue$5.Node.nextNodeIsIndented(ch, offset - (lineStart + indent), this.type !== PlainValue$5.Type.SEQ_ITEM)) {
13684 this.node = parseNode({
13685 atLineStart,
13686 inCollection: false,
13687 indent,
13688 lineStart,
13689 parent: this
13690 }, offset);
13691 } else if (ch && lineStart > start + 1) {
13692 offset = lineStart - 1;
13693 }
13694
13695 if (this.node) {
13696 if (blankLine) {
13697 // Only blank lines preceding non-empty nodes are captured. Note that
13698 // this means that collection item range start indices do not always
13699 // increase monotonically. -- eemeli/yaml#126
13700 const items = context.parent.items || context.parent.contents;
13701 if (items) items.push(blankLine);
13702 }
13703
13704 if (comments.length) Array.prototype.push.apply(this.props, comments);
13705 offset = this.node.range.end;
13706 } else {
13707 if (inlineComment) {
13708 const c = comments[0];
13709 this.props.push(c);
13710 offset = c.end;
13711 } else {
13712 offset = PlainValue$5.Node.endOfLine(src, start + 1);
13713 }
13714 }
13715
13716 const end = this.node ? this.node.valueRange.end : offset;
13717 this.valueRange = new PlainValue$5.Range(start, end);
13718 return offset;
13719 }
13720
13721 setOrigRanges(cr, offset) {
13722 offset = super.setOrigRanges(cr, offset);
13723 return this.node ? this.node.setOrigRanges(cr, offset) : offset;
13724 }
13725
13726 toString() {
13727 const {
13728 context: {
13729 src
13730 },
13731 node,
13732 range,
13733 value
13734 } = this;
13735 if (value != null) return value;
13736 const str = node ? src.slice(range.start, node.range.start) + String(node) : src.slice(range.start, range.end);
13737 return PlainValue$5.Node.addStringTerminator(src, range.end, str);
13738 }
13739
13740}
13741
13742class Comment extends PlainValue$5.Node {
13743 constructor() {
13744 super(PlainValue$5.Type.COMMENT);
13745 }
13746 /**
13747 * Parses a comment line from the source
13748 *
13749 * @param {ParseContext} context
13750 * @param {number} start - Index of first character
13751 * @returns {number} - Index of the character after this scalar
13752 */
13753
13754
13755 parse(context, start) {
13756 this.context = context;
13757 const offset = this.parseComment(start);
13758 this.range = new PlainValue$5.Range(start, offset);
13759 return offset;
13760 }
13761
13762}
13763
13764function grabCollectionEndComments(node) {
13765 let cnode = node;
13766
13767 while (cnode instanceof CollectionItem) cnode = cnode.node;
13768
13769 if (!(cnode instanceof Collection$1)) return null;
13770 const len = cnode.items.length;
13771 let ci = -1;
13772
13773 for (let i = len - 1; i >= 0; --i) {
13774 const n = cnode.items[i];
13775
13776 if (n.type === PlainValue$5.Type.COMMENT) {
13777 // Keep sufficiently indented comments with preceding node
13778 const {
13779 indent,
13780 lineStart
13781 } = n.context;
13782 if (indent > 0 && n.range.start >= lineStart + indent) break;
13783 ci = i;
13784 } else if (n.type === PlainValue$5.Type.BLANK_LINE) ci = i;else break;
13785 }
13786
13787 if (ci === -1) return null;
13788 const ca = cnode.items.splice(ci, len - ci);
13789 const prevEnd = ca[0].range.start;
13790
13791 while (true) {
13792 cnode.range.end = prevEnd;
13793 if (cnode.valueRange && cnode.valueRange.end > prevEnd) cnode.valueRange.end = prevEnd;
13794 if (cnode === node) break;
13795 cnode = cnode.context.parent;
13796 }
13797
13798 return ca;
13799}
13800class Collection$1 extends PlainValue$5.Node {
13801 static nextContentHasIndent(src, offset, indent) {
13802 const lineStart = PlainValue$5.Node.endOfLine(src, offset) + 1;
13803 offset = PlainValue$5.Node.endOfWhiteSpace(src, lineStart);
13804 const ch = src[offset];
13805 if (!ch) return false;
13806 if (offset >= lineStart + indent) return true;
13807 if (ch !== '#' && ch !== '\n') return false;
13808 return Collection$1.nextContentHasIndent(src, offset, indent);
13809 }
13810
13811 constructor(firstItem) {
13812 super(firstItem.type === PlainValue$5.Type.SEQ_ITEM ? PlainValue$5.Type.SEQ : PlainValue$5.Type.MAP);
13813
13814 for (let i = firstItem.props.length - 1; i >= 0; --i) {
13815 if (firstItem.props[i].start < firstItem.context.lineStart) {
13816 // props on previous line are assumed by the collection
13817 this.props = firstItem.props.slice(0, i + 1);
13818 firstItem.props = firstItem.props.slice(i + 1);
13819 const itemRange = firstItem.props[0] || firstItem.valueRange;
13820 firstItem.range.start = itemRange.start;
13821 break;
13822 }
13823 }
13824
13825 this.items = [firstItem];
13826 const ec = grabCollectionEndComments(firstItem);
13827 if (ec) Array.prototype.push.apply(this.items, ec);
13828 }
13829
13830 get includesTrailingLines() {
13831 return this.items.length > 0;
13832 }
13833 /**
13834 * @param {ParseContext} context
13835 * @param {number} start - Index of first character
13836 * @returns {number} - Index of the character after this
13837 */
13838
13839
13840 parse(context, start) {
13841 this.context = context;
13842 const {
13843 parseNode,
13844 src
13845 } = context; // It's easier to recalculate lineStart here rather than tracking down the
13846 // last context from which to read it -- eemeli/yaml#2
13847
13848 let lineStart = PlainValue$5.Node.startOfLine(src, start);
13849 const firstItem = this.items[0]; // First-item context needs to be correct for later comment handling
13850 // -- eemeli/yaml#17
13851
13852 firstItem.context.parent = this;
13853 this.valueRange = PlainValue$5.Range.copy(firstItem.valueRange);
13854 const indent = firstItem.range.start - firstItem.context.lineStart;
13855 let offset = start;
13856 offset = PlainValue$5.Node.normalizeOffset(src, offset);
13857 let ch = src[offset];
13858 let atLineStart = PlainValue$5.Node.endOfWhiteSpace(src, lineStart) === offset;
13859 let prevIncludesTrailingLines = false;
13860
13861 while (ch) {
13862 while (ch === '\n' || ch === '#') {
13863 if (atLineStart && ch === '\n' && !prevIncludesTrailingLines) {
13864 const blankLine = new BlankLine();
13865 offset = blankLine.parse({
13866 src
13867 }, offset);
13868 this.valueRange.end = offset;
13869
13870 if (offset >= src.length) {
13871 ch = null;
13872 break;
13873 }
13874
13875 this.items.push(blankLine);
13876 offset -= 1; // blankLine.parse() consumes terminal newline
13877 } else if (ch === '#') {
13878 if (offset < lineStart + indent && !Collection$1.nextContentHasIndent(src, offset, indent)) {
13879 return offset;
13880 }
13881
13882 const comment = new Comment();
13883 offset = comment.parse({
13884 indent,
13885 lineStart,
13886 src
13887 }, offset);
13888 this.items.push(comment);
13889 this.valueRange.end = offset;
13890
13891 if (offset >= src.length) {
13892 ch = null;
13893 break;
13894 }
13895 }
13896
13897 lineStart = offset + 1;
13898 offset = PlainValue$5.Node.endOfIndent(src, lineStart);
13899
13900 if (PlainValue$5.Node.atBlank(src, offset)) {
13901 const wsEnd = PlainValue$5.Node.endOfWhiteSpace(src, offset);
13902 const next = src[wsEnd];
13903
13904 if (!next || next === '\n' || next === '#') {
13905 offset = wsEnd;
13906 }
13907 }
13908
13909 ch = src[offset];
13910 atLineStart = true;
13911 }
13912
13913 if (!ch) {
13914 break;
13915 }
13916
13917 if (offset !== lineStart + indent && (atLineStart || ch !== ':')) {
13918 if (offset < lineStart + indent) {
13919 if (lineStart > start) offset = lineStart;
13920 break;
13921 } else if (!this.error) {
13922 const msg = 'All collection items must start at the same column';
13923 this.error = new PlainValue$5.YAMLSyntaxError(this, msg);
13924 }
13925 }
13926
13927 if (firstItem.type === PlainValue$5.Type.SEQ_ITEM) {
13928 if (ch !== '-') {
13929 if (lineStart > start) offset = lineStart;
13930 break;
13931 }
13932 } else if (ch === '-' && !this.error) {
13933 // map key may start with -, as long as it's followed by a non-whitespace char
13934 const next = src[offset + 1];
13935
13936 if (!next || next === '\n' || next === '\t' || next === ' ') {
13937 const msg = 'A collection cannot be both a mapping and a sequence';
13938 this.error = new PlainValue$5.YAMLSyntaxError(this, msg);
13939 }
13940 }
13941
13942 const node = parseNode({
13943 atLineStart,
13944 inCollection: true,
13945 indent,
13946 lineStart,
13947 parent: this
13948 }, offset);
13949 if (!node) return offset; // at next document start
13950
13951 this.items.push(node);
13952 this.valueRange.end = node.valueRange.end;
13953 offset = PlainValue$5.Node.normalizeOffset(src, node.range.end);
13954 ch = src[offset];
13955 atLineStart = false;
13956 prevIncludesTrailingLines = node.includesTrailingLines; // Need to reset lineStart and atLineStart here if preceding node's range
13957 // has advanced to check the current line's indentation level
13958 // -- eemeli/yaml#10 & eemeli/yaml#38
13959
13960 if (ch) {
13961 let ls = offset - 1;
13962 let prev = src[ls];
13963
13964 while (prev === ' ' || prev === '\t') prev = src[--ls];
13965
13966 if (prev === '\n') {
13967 lineStart = ls + 1;
13968 atLineStart = true;
13969 }
13970 }
13971
13972 const ec = grabCollectionEndComments(node);
13973 if (ec) Array.prototype.push.apply(this.items, ec);
13974 }
13975
13976 return offset;
13977 }
13978
13979 setOrigRanges(cr, offset) {
13980 offset = super.setOrigRanges(cr, offset);
13981 this.items.forEach(node => {
13982 offset = node.setOrigRanges(cr, offset);
13983 });
13984 return offset;
13985 }
13986
13987 toString() {
13988 const {
13989 context: {
13990 src
13991 },
13992 items,
13993 range,
13994 value
13995 } = this;
13996 if (value != null) return value;
13997 let str = src.slice(range.start, items[0].range.start) + String(items[0]);
13998
13999 for (let i = 1; i < items.length; ++i) {
14000 const item = items[i];
14001 const {
14002 atLineStart,
14003 indent
14004 } = item.context;
14005 if (atLineStart) for (let i = 0; i < indent; ++i) str += ' ';
14006 str += String(item);
14007 }
14008
14009 return PlainValue$5.Node.addStringTerminator(src, range.end, str);
14010 }
14011
14012}
14013
14014class Directive extends PlainValue$5.Node {
14015 constructor() {
14016 super(PlainValue$5.Type.DIRECTIVE);
14017 this.name = null;
14018 }
14019
14020 get parameters() {
14021 const raw = this.rawValue;
14022 return raw ? raw.trim().split(/[ \t]+/) : [];
14023 }
14024
14025 parseName(start) {
14026 const {
14027 src
14028 } = this.context;
14029 let offset = start;
14030 let ch = src[offset];
14031
14032 while (ch && ch !== '\n' && ch !== '\t' && ch !== ' ') ch = src[offset += 1];
14033
14034 this.name = src.slice(start, offset);
14035 return offset;
14036 }
14037
14038 parseParameters(start) {
14039 const {
14040 src
14041 } = this.context;
14042 let offset = start;
14043 let ch = src[offset];
14044
14045 while (ch && ch !== '\n' && ch !== '#') ch = src[offset += 1];
14046
14047 this.valueRange = new PlainValue$5.Range(start, offset);
14048 return offset;
14049 }
14050
14051 parse(context, start) {
14052 this.context = context;
14053 let offset = this.parseName(start + 1);
14054 offset = this.parseParameters(offset);
14055 offset = this.parseComment(offset);
14056 this.range = new PlainValue$5.Range(start, offset);
14057 return offset;
14058 }
14059
14060}
14061
14062class Document$3 extends PlainValue$5.Node {
14063 static startCommentOrEndBlankLine(src, start) {
14064 const offset = PlainValue$5.Node.endOfWhiteSpace(src, start);
14065 const ch = src[offset];
14066 return ch === '#' || ch === '\n' ? offset : start;
14067 }
14068
14069 constructor() {
14070 super(PlainValue$5.Type.DOCUMENT);
14071 this.directives = null;
14072 this.contents = null;
14073 this.directivesEndMarker = null;
14074 this.documentEndMarker = null;
14075 }
14076
14077 parseDirectives(start) {
14078 const {
14079 src
14080 } = this.context;
14081 this.directives = [];
14082 let atLineStart = true;
14083 let hasDirectives = false;
14084 let offset = start;
14085
14086 while (!PlainValue$5.Node.atDocumentBoundary(src, offset, PlainValue$5.Char.DIRECTIVES_END)) {
14087 offset = Document$3.startCommentOrEndBlankLine(src, offset);
14088
14089 switch (src[offset]) {
14090 case '\n':
14091 if (atLineStart) {
14092 const blankLine = new BlankLine();
14093 offset = blankLine.parse({
14094 src
14095 }, offset);
14096
14097 if (offset < src.length) {
14098 this.directives.push(blankLine);
14099 }
14100 } else {
14101 offset += 1;
14102 atLineStart = true;
14103 }
14104
14105 break;
14106
14107 case '#':
14108 {
14109 const comment = new Comment();
14110 offset = comment.parse({
14111 src
14112 }, offset);
14113 this.directives.push(comment);
14114 atLineStart = false;
14115 }
14116 break;
14117
14118 case '%':
14119 {
14120 const directive = new Directive();
14121 offset = directive.parse({
14122 parent: this,
14123 src
14124 }, offset);
14125 this.directives.push(directive);
14126 hasDirectives = true;
14127 atLineStart = false;
14128 }
14129 break;
14130
14131 default:
14132 if (hasDirectives) {
14133 this.error = new PlainValue$5.YAMLSemanticError(this, 'Missing directives-end indicator line');
14134 } else if (this.directives.length > 0) {
14135 this.contents = this.directives;
14136 this.directives = [];
14137 }
14138
14139 return offset;
14140 }
14141 }
14142
14143 if (src[offset]) {
14144 this.directivesEndMarker = new PlainValue$5.Range(offset, offset + 3);
14145 return offset + 3;
14146 }
14147
14148 if (hasDirectives) {
14149 this.error = new PlainValue$5.YAMLSemanticError(this, 'Missing directives-end indicator line');
14150 } else if (this.directives.length > 0) {
14151 this.contents = this.directives;
14152 this.directives = [];
14153 }
14154
14155 return offset;
14156 }
14157
14158 parseContents(start) {
14159 const {
14160 parseNode,
14161 src
14162 } = this.context;
14163 if (!this.contents) this.contents = [];
14164 let lineStart = start;
14165
14166 while (src[lineStart - 1] === '-') lineStart -= 1;
14167
14168 let offset = PlainValue$5.Node.endOfWhiteSpace(src, start);
14169 let atLineStart = lineStart === start;
14170 this.valueRange = new PlainValue$5.Range(offset);
14171
14172 while (!PlainValue$5.Node.atDocumentBoundary(src, offset, PlainValue$5.Char.DOCUMENT_END)) {
14173 switch (src[offset]) {
14174 case '\n':
14175 if (atLineStart) {
14176 const blankLine = new BlankLine();
14177 offset = blankLine.parse({
14178 src
14179 }, offset);
14180
14181 if (offset < src.length) {
14182 this.contents.push(blankLine);
14183 }
14184 } else {
14185 offset += 1;
14186 atLineStart = true;
14187 }
14188
14189 lineStart = offset;
14190 break;
14191
14192 case '#':
14193 {
14194 const comment = new Comment();
14195 offset = comment.parse({
14196 src
14197 }, offset);
14198 this.contents.push(comment);
14199 atLineStart = false;
14200 }
14201 break;
14202
14203 default:
14204 {
14205 const iEnd = PlainValue$5.Node.endOfIndent(src, offset);
14206 const context = {
14207 atLineStart,
14208 indent: -1,
14209 inFlow: false,
14210 inCollection: false,
14211 lineStart,
14212 parent: this
14213 };
14214 const node = parseNode(context, iEnd);
14215 if (!node) return this.valueRange.end = iEnd; // at next document start
14216
14217 this.contents.push(node);
14218 offset = node.range.end;
14219 atLineStart = false;
14220 const ec = grabCollectionEndComments(node);
14221 if (ec) Array.prototype.push.apply(this.contents, ec);
14222 }
14223 }
14224
14225 offset = Document$3.startCommentOrEndBlankLine(src, offset);
14226 }
14227
14228 this.valueRange.end = offset;
14229
14230 if (src[offset]) {
14231 this.documentEndMarker = new PlainValue$5.Range(offset, offset + 3);
14232 offset += 3;
14233
14234 if (src[offset]) {
14235 offset = PlainValue$5.Node.endOfWhiteSpace(src, offset);
14236
14237 if (src[offset] === '#') {
14238 const comment = new Comment();
14239 offset = comment.parse({
14240 src
14241 }, offset);
14242 this.contents.push(comment);
14243 }
14244
14245 switch (src[offset]) {
14246 case '\n':
14247 offset += 1;
14248 break;
14249
14250 case undefined:
14251 break;
14252
14253 default:
14254 this.error = new PlainValue$5.YAMLSyntaxError(this, 'Document end marker line cannot have a non-comment suffix');
14255 }
14256 }
14257 }
14258
14259 return offset;
14260 }
14261 /**
14262 * @param {ParseContext} context
14263 * @param {number} start - Index of first character
14264 * @returns {number} - Index of the character after this
14265 */
14266
14267
14268 parse(context, start) {
14269 context.root = this;
14270 this.context = context;
14271 const {
14272 src
14273 } = context;
14274 let offset = src.charCodeAt(start) === 0xfeff ? start + 1 : start; // skip BOM
14275
14276 offset = this.parseDirectives(offset);
14277 offset = this.parseContents(offset);
14278 return offset;
14279 }
14280
14281 setOrigRanges(cr, offset) {
14282 offset = super.setOrigRanges(cr, offset);
14283 this.directives.forEach(node => {
14284 offset = node.setOrigRanges(cr, offset);
14285 });
14286 if (this.directivesEndMarker) offset = this.directivesEndMarker.setOrigRange(cr, offset);
14287 this.contents.forEach(node => {
14288 offset = node.setOrigRanges(cr, offset);
14289 });
14290 if (this.documentEndMarker) offset = this.documentEndMarker.setOrigRange(cr, offset);
14291 return offset;
14292 }
14293
14294 toString() {
14295 const {
14296 contents,
14297 directives,
14298 value
14299 } = this;
14300 if (value != null) return value;
14301 let str = directives.join('');
14302
14303 if (contents.length > 0) {
14304 if (directives.length > 0 || contents[0].type === PlainValue$5.Type.COMMENT) str += '---\n';
14305 str += contents.join('');
14306 }
14307
14308 if (str[str.length - 1] !== '\n') str += '\n';
14309 return str;
14310 }
14311
14312}
14313
14314class Alias$1 extends PlainValue$5.Node {
14315 /**
14316 * Parses an *alias from the source
14317 *
14318 * @param {ParseContext} context
14319 * @param {number} start - Index of first character
14320 * @returns {number} - Index of the character after this scalar
14321 */
14322 parse(context, start) {
14323 this.context = context;
14324 const {
14325 src
14326 } = context;
14327 let offset = PlainValue$5.Node.endOfIdentifier(src, start + 1);
14328 this.valueRange = new PlainValue$5.Range(start + 1, offset);
14329 offset = PlainValue$5.Node.endOfWhiteSpace(src, offset);
14330 offset = this.parseComment(offset);
14331 return offset;
14332 }
14333
14334}
14335
14336const Chomp = {
14337 CLIP: 'CLIP',
14338 KEEP: 'KEEP',
14339 STRIP: 'STRIP'
14340};
14341class BlockValue extends PlainValue$5.Node {
14342 constructor(type, props) {
14343 super(type, props);
14344 this.blockIndent = null;
14345 this.chomping = Chomp.CLIP;
14346 this.header = null;
14347 }
14348
14349 get includesTrailingLines() {
14350 return this.chomping === Chomp.KEEP;
14351 }
14352
14353 get strValue() {
14354 if (!this.valueRange || !this.context) return null;
14355 let {
14356 start,
14357 end
14358 } = this.valueRange;
14359 const {
14360 indent,
14361 src
14362 } = this.context;
14363 if (this.valueRange.isEmpty()) return '';
14364 let lastNewLine = null;
14365 let ch = src[end - 1];
14366
14367 while (ch === '\n' || ch === '\t' || ch === ' ') {
14368 end -= 1;
14369
14370 if (end <= start) {
14371 if (this.chomping === Chomp.KEEP) break;else return ''; // probably never happens
14372 }
14373
14374 if (ch === '\n') lastNewLine = end;
14375 ch = src[end - 1];
14376 }
14377
14378 let keepStart = end + 1;
14379
14380 if (lastNewLine) {
14381 if (this.chomping === Chomp.KEEP) {
14382 keepStart = lastNewLine;
14383 end = this.valueRange.end;
14384 } else {
14385 end = lastNewLine;
14386 }
14387 }
14388
14389 const bi = indent + this.blockIndent;
14390 const folded = this.type === PlainValue$5.Type.BLOCK_FOLDED;
14391 let atStart = true;
14392 let str = '';
14393 let sep = '';
14394 let prevMoreIndented = false;
14395
14396 for (let i = start; i < end; ++i) {
14397 for (let j = 0; j < bi; ++j) {
14398 if (src[i] !== ' ') break;
14399 i += 1;
14400 }
14401
14402 const ch = src[i];
14403
14404 if (ch === '\n') {
14405 if (sep === '\n') str += '\n';else sep = '\n';
14406 } else {
14407 const lineEnd = PlainValue$5.Node.endOfLine(src, i);
14408 const line = src.slice(i, lineEnd);
14409 i = lineEnd;
14410
14411 if (folded && (ch === ' ' || ch === '\t') && i < keepStart) {
14412 if (sep === ' ') sep = '\n';else if (!prevMoreIndented && !atStart && sep === '\n') sep = '\n\n';
14413 str += sep + line; //+ ((lineEnd < end && src[lineEnd]) || '')
14414
14415 sep = lineEnd < end && src[lineEnd] || '';
14416 prevMoreIndented = true;
14417 } else {
14418 str += sep + line;
14419 sep = folded && i < keepStart ? ' ' : '\n';
14420 prevMoreIndented = false;
14421 }
14422
14423 if (atStart && line !== '') atStart = false;
14424 }
14425 }
14426
14427 return this.chomping === Chomp.STRIP ? str : str + '\n';
14428 }
14429
14430 parseBlockHeader(start) {
14431 const {
14432 src
14433 } = this.context;
14434 let offset = start + 1;
14435 let bi = '';
14436
14437 while (true) {
14438 const ch = src[offset];
14439
14440 switch (ch) {
14441 case '-':
14442 this.chomping = Chomp.STRIP;
14443 break;
14444
14445 case '+':
14446 this.chomping = Chomp.KEEP;
14447 break;
14448
14449 case '0':
14450 case '1':
14451 case '2':
14452 case '3':
14453 case '4':
14454 case '5':
14455 case '6':
14456 case '7':
14457 case '8':
14458 case '9':
14459 bi += ch;
14460 break;
14461
14462 default:
14463 this.blockIndent = Number(bi) || null;
14464 this.header = new PlainValue$5.Range(start, offset);
14465 return offset;
14466 }
14467
14468 offset += 1;
14469 }
14470 }
14471
14472 parseBlockValue(start) {
14473 const {
14474 indent,
14475 src
14476 } = this.context;
14477 const explicit = !!this.blockIndent;
14478 let offset = start;
14479 let valueEnd = start;
14480 let minBlockIndent = 1;
14481
14482 for (let ch = src[offset]; ch === '\n'; ch = src[offset]) {
14483 offset += 1;
14484 if (PlainValue$5.Node.atDocumentBoundary(src, offset)) break;
14485 const end = PlainValue$5.Node.endOfBlockIndent(src, indent, offset); // should not include tab?
14486
14487 if (end === null) break;
14488 const ch = src[end];
14489 const lineIndent = end - (offset + indent);
14490
14491 if (!this.blockIndent) {
14492 // no explicit block indent, none yet detected
14493 if (src[end] !== '\n') {
14494 // first line with non-whitespace content
14495 if (lineIndent < minBlockIndent) {
14496 const msg = 'Block scalars with more-indented leading empty lines must use an explicit indentation indicator';
14497 this.error = new PlainValue$5.YAMLSemanticError(this, msg);
14498 }
14499
14500 this.blockIndent = lineIndent;
14501 } else if (lineIndent > minBlockIndent) {
14502 // empty line with more whitespace
14503 minBlockIndent = lineIndent;
14504 }
14505 } else if (ch && ch !== '\n' && lineIndent < this.blockIndent) {
14506 if (src[end] === '#') break;
14507
14508 if (!this.error) {
14509 const src = explicit ? 'explicit indentation indicator' : 'first line';
14510 const msg = `Block scalars must not be less indented than their ${src}`;
14511 this.error = new PlainValue$5.YAMLSemanticError(this, msg);
14512 }
14513 }
14514
14515 if (src[end] === '\n') {
14516 offset = end;
14517 } else {
14518 offset = valueEnd = PlainValue$5.Node.endOfLine(src, end);
14519 }
14520 }
14521
14522 if (this.chomping !== Chomp.KEEP) {
14523 offset = src[valueEnd] ? valueEnd + 1 : valueEnd;
14524 }
14525
14526 this.valueRange = new PlainValue$5.Range(start + 1, offset);
14527 return offset;
14528 }
14529 /**
14530 * Parses a block value from the source
14531 *
14532 * Accepted forms are:
14533 * ```
14534 * BS
14535 * block
14536 * lines
14537 *
14538 * BS #comment
14539 * block
14540 * lines
14541 * ```
14542 * where the block style BS matches the regexp `[|>][-+1-9]*` and block lines
14543 * are empty or have an indent level greater than `indent`.
14544 *
14545 * @param {ParseContext} context
14546 * @param {number} start - Index of first character
14547 * @returns {number} - Index of the character after this block
14548 */
14549
14550
14551 parse(context, start) {
14552 this.context = context;
14553 const {
14554 src
14555 } = context;
14556 let offset = this.parseBlockHeader(start);
14557 offset = PlainValue$5.Node.endOfWhiteSpace(src, offset);
14558 offset = this.parseComment(offset);
14559 offset = this.parseBlockValue(offset);
14560 return offset;
14561 }
14562
14563 setOrigRanges(cr, offset) {
14564 offset = super.setOrigRanges(cr, offset);
14565 return this.header ? this.header.setOrigRange(cr, offset) : offset;
14566 }
14567
14568}
14569
14570class FlowCollection extends PlainValue$5.Node {
14571 constructor(type, props) {
14572 super(type, props);
14573 this.items = null;
14574 }
14575
14576 prevNodeIsJsonLike(idx = this.items.length) {
14577 const node = this.items[idx - 1];
14578 return !!node && (node.jsonLike || node.type === PlainValue$5.Type.COMMENT && this.prevNodeIsJsonLike(idx - 1));
14579 }
14580 /**
14581 * @param {ParseContext} context
14582 * @param {number} start - Index of first character
14583 * @returns {number} - Index of the character after this
14584 */
14585
14586
14587 parse(context, start) {
14588 this.context = context;
14589 const {
14590 parseNode,
14591 src
14592 } = context;
14593 let {
14594 indent,
14595 lineStart
14596 } = context;
14597 let char = src[start]; // { or [
14598
14599 this.items = [{
14600 char,
14601 offset: start
14602 }];
14603 let offset = PlainValue$5.Node.endOfWhiteSpace(src, start + 1);
14604 char = src[offset];
14605
14606 while (char && char !== ']' && char !== '}') {
14607 switch (char) {
14608 case '\n':
14609 {
14610 lineStart = offset + 1;
14611 const wsEnd = PlainValue$5.Node.endOfWhiteSpace(src, lineStart);
14612
14613 if (src[wsEnd] === '\n') {
14614 const blankLine = new BlankLine();
14615 lineStart = blankLine.parse({
14616 src
14617 }, lineStart);
14618 this.items.push(blankLine);
14619 }
14620
14621 offset = PlainValue$5.Node.endOfIndent(src, lineStart);
14622
14623 if (offset <= lineStart + indent) {
14624 char = src[offset];
14625
14626 if (offset < lineStart + indent || char !== ']' && char !== '}') {
14627 const msg = 'Insufficient indentation in flow collection';
14628 this.error = new PlainValue$5.YAMLSemanticError(this, msg);
14629 }
14630 }
14631 }
14632 break;
14633
14634 case ',':
14635 {
14636 this.items.push({
14637 char,
14638 offset
14639 });
14640 offset += 1;
14641 }
14642 break;
14643
14644 case '#':
14645 {
14646 const comment = new Comment();
14647 offset = comment.parse({
14648 src
14649 }, offset);
14650 this.items.push(comment);
14651 }
14652 break;
14653
14654 case '?':
14655 case ':':
14656 {
14657 const next = src[offset + 1];
14658
14659 if (next === '\n' || next === '\t' || next === ' ' || next === ',' || // in-flow : after JSON-like key does not need to be followed by whitespace
14660 char === ':' && this.prevNodeIsJsonLike()) {
14661 this.items.push({
14662 char,
14663 offset
14664 });
14665 offset += 1;
14666 break;
14667 }
14668 }
14669 // fallthrough
14670
14671 default:
14672 {
14673 const node = parseNode({
14674 atLineStart: false,
14675 inCollection: false,
14676 inFlow: true,
14677 indent: -1,
14678 lineStart,
14679 parent: this
14680 }, offset);
14681
14682 if (!node) {
14683 // at next document start
14684 this.valueRange = new PlainValue$5.Range(start, offset);
14685 return offset;
14686 }
14687
14688 this.items.push(node);
14689 offset = PlainValue$5.Node.normalizeOffset(src, node.range.end);
14690 }
14691 }
14692
14693 offset = PlainValue$5.Node.endOfWhiteSpace(src, offset);
14694 char = src[offset];
14695 }
14696
14697 this.valueRange = new PlainValue$5.Range(start, offset + 1);
14698
14699 if (char) {
14700 this.items.push({
14701 char,
14702 offset
14703 });
14704 offset = PlainValue$5.Node.endOfWhiteSpace(src, offset + 1);
14705 offset = this.parseComment(offset);
14706 }
14707
14708 return offset;
14709 }
14710
14711 setOrigRanges(cr, offset) {
14712 offset = super.setOrigRanges(cr, offset);
14713 this.items.forEach(node => {
14714 if (node instanceof PlainValue$5.Node) {
14715 offset = node.setOrigRanges(cr, offset);
14716 } else if (cr.length === 0) {
14717 node.origOffset = node.offset;
14718 } else {
14719 let i = offset;
14720
14721 while (i < cr.length) {
14722 if (cr[i] > node.offset) break;else ++i;
14723 }
14724
14725 node.origOffset = node.offset + i;
14726 offset = i;
14727 }
14728 });
14729 return offset;
14730 }
14731
14732 toString() {
14733 const {
14734 context: {
14735 src
14736 },
14737 items,
14738 range,
14739 value
14740 } = this;
14741 if (value != null) return value;
14742 const nodes = items.filter(item => item instanceof PlainValue$5.Node);
14743 let str = '';
14744 let prevEnd = range.start;
14745 nodes.forEach(node => {
14746 const prefix = src.slice(prevEnd, node.range.start);
14747 prevEnd = node.range.end;
14748 str += prefix + String(node);
14749
14750 if (str[str.length - 1] === '\n' && src[prevEnd - 1] !== '\n' && src[prevEnd] === '\n') {
14751 // Comment range does not include the terminal newline, but its
14752 // stringified value does. Without this fix, newlines at comment ends
14753 // get duplicated.
14754 prevEnd += 1;
14755 }
14756 });
14757 str += src.slice(prevEnd, range.end);
14758 return PlainValue$5.Node.addStringTerminator(src, range.end, str);
14759 }
14760
14761}
14762
14763class QuoteDouble extends PlainValue$5.Node {
14764 static endOfQuote(src, offset) {
14765 let ch = src[offset];
14766
14767 while (ch && ch !== '"') {
14768 offset += ch === '\\' ? 2 : 1;
14769 ch = src[offset];
14770 }
14771
14772 return offset + 1;
14773 }
14774 /**
14775 * @returns {string | { str: string, errors: YAMLSyntaxError[] }}
14776 */
14777
14778
14779 get strValue() {
14780 if (!this.valueRange || !this.context) return null;
14781 const errors = [];
14782 const {
14783 start,
14784 end
14785 } = this.valueRange;
14786 const {
14787 indent,
14788 src
14789 } = this.context;
14790 if (src[end - 1] !== '"') errors.push(new PlainValue$5.YAMLSyntaxError(this, 'Missing closing "quote')); // Using String#replace is too painful with escaped newlines preceded by
14791 // escaped backslashes; also, this should be faster.
14792
14793 let str = '';
14794
14795 for (let i = start + 1; i < end - 1; ++i) {
14796 const ch = src[i];
14797
14798 if (ch === '\n') {
14799 if (PlainValue$5.Node.atDocumentBoundary(src, i + 1)) errors.push(new PlainValue$5.YAMLSemanticError(this, 'Document boundary indicators are not allowed within string values'));
14800 const {
14801 fold,
14802 offset,
14803 error
14804 } = PlainValue$5.Node.foldNewline(src, i, indent);
14805 str += fold;
14806 i = offset;
14807 if (error) errors.push(new PlainValue$5.YAMLSemanticError(this, 'Multi-line double-quoted string needs to be sufficiently indented'));
14808 } else if (ch === '\\') {
14809 i += 1;
14810
14811 switch (src[i]) {
14812 case '0':
14813 str += '\0';
14814 break;
14815 // null character
14816
14817 case 'a':
14818 str += '\x07';
14819 break;
14820 // bell character
14821
14822 case 'b':
14823 str += '\b';
14824 break;
14825 // backspace
14826
14827 case 'e':
14828 str += '\x1b';
14829 break;
14830 // escape character
14831
14832 case 'f':
14833 str += '\f';
14834 break;
14835 // form feed
14836
14837 case 'n':
14838 str += '\n';
14839 break;
14840 // line feed
14841
14842 case 'r':
14843 str += '\r';
14844 break;
14845 // carriage return
14846
14847 case 't':
14848 str += '\t';
14849 break;
14850 // horizontal tab
14851
14852 case 'v':
14853 str += '\v';
14854 break;
14855 // vertical tab
14856
14857 case 'N':
14858 str += '\u0085';
14859 break;
14860 // Unicode next line
14861
14862 case '_':
14863 str += '\u00a0';
14864 break;
14865 // Unicode non-breaking space
14866
14867 case 'L':
14868 str += '\u2028';
14869 break;
14870 // Unicode line separator
14871
14872 case 'P':
14873 str += '\u2029';
14874 break;
14875 // Unicode paragraph separator
14876
14877 case ' ':
14878 str += ' ';
14879 break;
14880
14881 case '"':
14882 str += '"';
14883 break;
14884
14885 case '/':
14886 str += '/';
14887 break;
14888
14889 case '\\':
14890 str += '\\';
14891 break;
14892
14893 case '\t':
14894 str += '\t';
14895 break;
14896
14897 case 'x':
14898 str += this.parseCharCode(i + 1, 2, errors);
14899 i += 2;
14900 break;
14901
14902 case 'u':
14903 str += this.parseCharCode(i + 1, 4, errors);
14904 i += 4;
14905 break;
14906
14907 case 'U':
14908 str += this.parseCharCode(i + 1, 8, errors);
14909 i += 8;
14910 break;
14911
14912 case '\n':
14913 // skip escaped newlines, but still trim the following line
14914 while (src[i + 1] === ' ' || src[i + 1] === '\t') i += 1;
14915
14916 break;
14917
14918 default:
14919 errors.push(new PlainValue$5.YAMLSyntaxError(this, `Invalid escape sequence ${src.substr(i - 1, 2)}`));
14920 str += '\\' + src[i];
14921 }
14922 } else if (ch === ' ' || ch === '\t') {
14923 // trim trailing whitespace
14924 const wsStart = i;
14925 let next = src[i + 1];
14926
14927 while (next === ' ' || next === '\t') {
14928 i += 1;
14929 next = src[i + 1];
14930 }
14931
14932 if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch;
14933 } else {
14934 str += ch;
14935 }
14936 }
14937
14938 return errors.length > 0 ? {
14939 errors,
14940 str
14941 } : str;
14942 }
14943
14944 parseCharCode(offset, length, errors) {
14945 const {
14946 src
14947 } = this.context;
14948 const cc = src.substr(offset, length);
14949 const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc);
14950 const code = ok ? parseInt(cc, 16) : NaN;
14951
14952 if (isNaN(code)) {
14953 errors.push(new PlainValue$5.YAMLSyntaxError(this, `Invalid escape sequence ${src.substr(offset - 2, length + 2)}`));
14954 return src.substr(offset - 2, length + 2);
14955 }
14956
14957 return String.fromCodePoint(code);
14958 }
14959 /**
14960 * Parses a "double quoted" value from the source
14961 *
14962 * @param {ParseContext} context
14963 * @param {number} start - Index of first character
14964 * @returns {number} - Index of the character after this scalar
14965 */
14966
14967
14968 parse(context, start) {
14969 this.context = context;
14970 const {
14971 src
14972 } = context;
14973 let offset = QuoteDouble.endOfQuote(src, start + 1);
14974 this.valueRange = new PlainValue$5.Range(start, offset);
14975 offset = PlainValue$5.Node.endOfWhiteSpace(src, offset);
14976 offset = this.parseComment(offset);
14977 return offset;
14978 }
14979
14980}
14981
14982class QuoteSingle extends PlainValue$5.Node {
14983 static endOfQuote(src, offset) {
14984 let ch = src[offset];
14985
14986 while (ch) {
14987 if (ch === "'") {
14988 if (src[offset + 1] !== "'") break;
14989 ch = src[offset += 2];
14990 } else {
14991 ch = src[offset += 1];
14992 }
14993 }
14994
14995 return offset + 1;
14996 }
14997 /**
14998 * @returns {string | { str: string, errors: YAMLSyntaxError[] }}
14999 */
15000
15001
15002 get strValue() {
15003 if (!this.valueRange || !this.context) return null;
15004 const errors = [];
15005 const {
15006 start,
15007 end
15008 } = this.valueRange;
15009 const {
15010 indent,
15011 src
15012 } = this.context;
15013 if (src[end - 1] !== "'") errors.push(new PlainValue$5.YAMLSyntaxError(this, "Missing closing 'quote"));
15014 let str = '';
15015
15016 for (let i = start + 1; i < end - 1; ++i) {
15017 const ch = src[i];
15018
15019 if (ch === '\n') {
15020 if (PlainValue$5.Node.atDocumentBoundary(src, i + 1)) errors.push(new PlainValue$5.YAMLSemanticError(this, 'Document boundary indicators are not allowed within string values'));
15021 const {
15022 fold,
15023 offset,
15024 error
15025 } = PlainValue$5.Node.foldNewline(src, i, indent);
15026 str += fold;
15027 i = offset;
15028 if (error) errors.push(new PlainValue$5.YAMLSemanticError(this, 'Multi-line single-quoted string needs to be sufficiently indented'));
15029 } else if (ch === "'") {
15030 str += ch;
15031 i += 1;
15032 if (src[i] !== "'") errors.push(new PlainValue$5.YAMLSyntaxError(this, 'Unescaped single quote? This should not happen.'));
15033 } else if (ch === ' ' || ch === '\t') {
15034 // trim trailing whitespace
15035 const wsStart = i;
15036 let next = src[i + 1];
15037
15038 while (next === ' ' || next === '\t') {
15039 i += 1;
15040 next = src[i + 1];
15041 }
15042
15043 if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch;
15044 } else {
15045 str += ch;
15046 }
15047 }
15048
15049 return errors.length > 0 ? {
15050 errors,
15051 str
15052 } : str;
15053 }
15054 /**
15055 * Parses a 'single quoted' value from the source
15056 *
15057 * @param {ParseContext} context
15058 * @param {number} start - Index of first character
15059 * @returns {number} - Index of the character after this scalar
15060 */
15061
15062
15063 parse(context, start) {
15064 this.context = context;
15065 const {
15066 src
15067 } = context;
15068 let offset = QuoteSingle.endOfQuote(src, start + 1);
15069 this.valueRange = new PlainValue$5.Range(start, offset);
15070 offset = PlainValue$5.Node.endOfWhiteSpace(src, offset);
15071 offset = this.parseComment(offset);
15072 return offset;
15073 }
15074
15075}
15076
15077function createNewNode(type, props) {
15078 switch (type) {
15079 case PlainValue$5.Type.ALIAS:
15080 return new Alias$1(type, props);
15081
15082 case PlainValue$5.Type.BLOCK_FOLDED:
15083 case PlainValue$5.Type.BLOCK_LITERAL:
15084 return new BlockValue(type, props);
15085
15086 case PlainValue$5.Type.FLOW_MAP:
15087 case PlainValue$5.Type.FLOW_SEQ:
15088 return new FlowCollection(type, props);
15089
15090 case PlainValue$5.Type.MAP_KEY:
15091 case PlainValue$5.Type.MAP_VALUE:
15092 case PlainValue$5.Type.SEQ_ITEM:
15093 return new CollectionItem(type, props);
15094
15095 case PlainValue$5.Type.COMMENT:
15096 case PlainValue$5.Type.PLAIN:
15097 return new PlainValue$5.PlainValue(type, props);
15098
15099 case PlainValue$5.Type.QUOTE_DOUBLE:
15100 return new QuoteDouble(type, props);
15101
15102 case PlainValue$5.Type.QUOTE_SINGLE:
15103 return new QuoteSingle(type, props);
15104
15105 /* istanbul ignore next */
15106
15107 default:
15108 return null;
15109 // should never happen
15110 }
15111}
15112/**
15113 * @param {boolean} atLineStart - Node starts at beginning of line
15114 * @param {boolean} inFlow - true if currently in a flow context
15115 * @param {boolean} inCollection - true if currently in a collection context
15116 * @param {number} indent - Current level of indentation
15117 * @param {number} lineStart - Start of the current line
15118 * @param {Node} parent - The parent of the node
15119 * @param {string} src - Source of the YAML document
15120 */
15121
15122
15123class ParseContext {
15124 static parseType(src, offset, inFlow) {
15125 switch (src[offset]) {
15126 case '*':
15127 return PlainValue$5.Type.ALIAS;
15128
15129 case '>':
15130 return PlainValue$5.Type.BLOCK_FOLDED;
15131
15132 case '|':
15133 return PlainValue$5.Type.BLOCK_LITERAL;
15134
15135 case '{':
15136 return PlainValue$5.Type.FLOW_MAP;
15137
15138 case '[':
15139 return PlainValue$5.Type.FLOW_SEQ;
15140
15141 case '?':
15142 return !inFlow && PlainValue$5.Node.atBlank(src, offset + 1, true) ? PlainValue$5.Type.MAP_KEY : PlainValue$5.Type.PLAIN;
15143
15144 case ':':
15145 return !inFlow && PlainValue$5.Node.atBlank(src, offset + 1, true) ? PlainValue$5.Type.MAP_VALUE : PlainValue$5.Type.PLAIN;
15146
15147 case '-':
15148 return !inFlow && PlainValue$5.Node.atBlank(src, offset + 1, true) ? PlainValue$5.Type.SEQ_ITEM : PlainValue$5.Type.PLAIN;
15149
15150 case '"':
15151 return PlainValue$5.Type.QUOTE_DOUBLE;
15152
15153 case "'":
15154 return PlainValue$5.Type.QUOTE_SINGLE;
15155
15156 default:
15157 return PlainValue$5.Type.PLAIN;
15158 }
15159 }
15160
15161 constructor(orig = {}, {
15162 atLineStart,
15163 inCollection,
15164 inFlow,
15165 indent,
15166 lineStart,
15167 parent
15168 } = {}) {
15169 PlainValue$5._defineProperty(this, "parseNode", (overlay, start) => {
15170 if (PlainValue$5.Node.atDocumentBoundary(this.src, start)) return null;
15171 const context = new ParseContext(this, overlay);
15172 const {
15173 props,
15174 type,
15175 valueStart
15176 } = context.parseProps(start);
15177 const node = createNewNode(type, props);
15178 let offset = node.parse(context, valueStart);
15179 node.range = new PlainValue$5.Range(start, offset);
15180 /* istanbul ignore if */
15181
15182 if (offset <= start) {
15183 // This should never happen, but if it does, let's make sure to at least
15184 // step one character forward to avoid a busy loop.
15185 node.error = new Error(`Node#parse consumed no characters`);
15186 node.error.parseEnd = offset;
15187 node.error.source = node;
15188 node.range.end = start + 1;
15189 }
15190
15191 if (context.nodeStartsCollection(node)) {
15192 if (!node.error && !context.atLineStart && context.parent.type === PlainValue$5.Type.DOCUMENT) {
15193 node.error = new PlainValue$5.YAMLSyntaxError(node, 'Block collection must not have preceding content here (e.g. directives-end indicator)');
15194 }
15195
15196 const collection = new Collection$1(node);
15197 offset = collection.parse(new ParseContext(context), offset);
15198 collection.range = new PlainValue$5.Range(start, offset);
15199 return collection;
15200 }
15201
15202 return node;
15203 });
15204
15205 this.atLineStart = atLineStart != null ? atLineStart : orig.atLineStart || false;
15206 this.inCollection = inCollection != null ? inCollection : orig.inCollection || false;
15207 this.inFlow = inFlow != null ? inFlow : orig.inFlow || false;
15208 this.indent = indent != null ? indent : orig.indent;
15209 this.lineStart = lineStart != null ? lineStart : orig.lineStart;
15210 this.parent = parent != null ? parent : orig.parent || {};
15211 this.root = orig.root;
15212 this.src = orig.src;
15213 }
15214
15215 nodeStartsCollection(node) {
15216 const {
15217 inCollection,
15218 inFlow,
15219 src
15220 } = this;
15221 if (inCollection || inFlow) return false;
15222 if (node instanceof CollectionItem) return true; // check for implicit key
15223
15224 let offset = node.range.end;
15225 if (src[offset] === '\n' || src[offset - 1] === '\n') return false;
15226 offset = PlainValue$5.Node.endOfWhiteSpace(src, offset);
15227 return src[offset] === ':';
15228 } // Anchor and tag are before type, which determines the node implementation
15229 // class; hence this intermediate step.
15230
15231
15232 parseProps(offset) {
15233 const {
15234 inFlow,
15235 parent,
15236 src
15237 } = this;
15238 const props = [];
15239 let lineHasProps = false;
15240 offset = this.atLineStart ? PlainValue$5.Node.endOfIndent(src, offset) : PlainValue$5.Node.endOfWhiteSpace(src, offset);
15241 let ch = src[offset];
15242
15243 while (ch === PlainValue$5.Char.ANCHOR || ch === PlainValue$5.Char.COMMENT || ch === PlainValue$5.Char.TAG || ch === '\n') {
15244 if (ch === '\n') {
15245 let inEnd = offset;
15246 let lineStart;
15247
15248 do {
15249 lineStart = inEnd + 1;
15250 inEnd = PlainValue$5.Node.endOfIndent(src, lineStart);
15251 } while (src[inEnd] === '\n');
15252
15253 const indentDiff = inEnd - (lineStart + this.indent);
15254 const noIndicatorAsIndent = parent.type === PlainValue$5.Type.SEQ_ITEM && parent.context.atLineStart;
15255 if (src[inEnd] !== '#' && !PlainValue$5.Node.nextNodeIsIndented(src[inEnd], indentDiff, !noIndicatorAsIndent)) break;
15256 this.atLineStart = true;
15257 this.lineStart = lineStart;
15258 lineHasProps = false;
15259 offset = inEnd;
15260 } else if (ch === PlainValue$5.Char.COMMENT) {
15261 const end = PlainValue$5.Node.endOfLine(src, offset + 1);
15262 props.push(new PlainValue$5.Range(offset, end));
15263 offset = end;
15264 } else {
15265 let end = PlainValue$5.Node.endOfIdentifier(src, offset + 1);
15266
15267 if (ch === PlainValue$5.Char.TAG && src[end] === ',' && /^[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+,\d\d\d\d(-\d\d){0,2}\/\S/.test(src.slice(offset + 1, end + 13))) {
15268 // Let's presume we're dealing with a YAML 1.0 domain tag here, rather
15269 // than an empty but 'foo.bar' private-tagged node in a flow collection
15270 // followed without whitespace by a plain string starting with a year
15271 // or date divided by something.
15272 end = PlainValue$5.Node.endOfIdentifier(src, end + 5);
15273 }
15274
15275 props.push(new PlainValue$5.Range(offset, end));
15276 lineHasProps = true;
15277 offset = PlainValue$5.Node.endOfWhiteSpace(src, end);
15278 }
15279
15280 ch = src[offset];
15281 } // '- &a : b' has an anchor on an empty node
15282
15283
15284 if (lineHasProps && ch === ':' && PlainValue$5.Node.atBlank(src, offset + 1, true)) offset -= 1;
15285 const type = ParseContext.parseType(src, offset, inFlow);
15286 return {
15287 props,
15288 type,
15289 valueStart: offset
15290 };
15291 }
15292 /**
15293 * Parses a node from the source
15294 * @param {ParseContext} overlay
15295 * @param {number} start - Index of first non-whitespace character for the node
15296 * @returns {?Node} - null if at a document boundary
15297 */
15298
15299
15300}
15301
15302// Published as 'yaml/parse-cst'
15303function parse$h(src) {
15304 const cr = [];
15305
15306 if (src.indexOf('\r') !== -1) {
15307 src = src.replace(/\r\n?/g, (match, offset) => {
15308 if (match.length > 1) cr.push(offset);
15309 return '\n';
15310 });
15311 }
15312
15313 const documents = [];
15314 let offset = 0;
15315
15316 do {
15317 const doc = new Document$3();
15318 const context = new ParseContext({
15319 src
15320 });
15321 offset = doc.parse(context, offset);
15322 documents.push(doc);
15323 } while (offset < src.length);
15324
15325 documents.setOrigRanges = () => {
15326 if (cr.length === 0) return false;
15327
15328 for (let i = 1; i < cr.length; ++i) cr[i] -= i;
15329
15330 let crOffset = 0;
15331
15332 for (let i = 0; i < documents.length; ++i) {
15333 crOffset = documents[i].setOrigRanges(cr, crOffset);
15334 }
15335
15336 cr.splice(0, cr.length);
15337 return true;
15338 };
15339
15340 documents.toString = () => documents.join('...\n');
15341
15342 return documents;
15343}
15344
15345parseCst$1.parse = parse$h;
15346
15347var Document9b4560a1 = {};
15348
15349var resolveSeqD03cb037 = {};
15350
15351var PlainValue$4 = PlainValueEc8e588e;
15352
15353function addCommentBefore(str, indent, comment) {
15354 if (!comment) return str;
15355 const cc = comment.replace(/[\s\S]^/gm, `$&${indent}#`);
15356 return `#${cc}\n${indent}${str}`;
15357}
15358function addComment(str, indent, comment) {
15359 return !comment ? str : comment.indexOf('\n') === -1 ? `${str} #${comment}` : `${str}\n` + comment.replace(/^/gm, `${indent || ''}#`);
15360}
15361
15362class Node$1 {}
15363
15364function toJSON(value, arg, ctx) {
15365 if (Array.isArray(value)) return value.map((v, i) => toJSON(v, String(i), ctx));
15366
15367 if (value && typeof value.toJSON === 'function') {
15368 const anchor = ctx && ctx.anchors && ctx.anchors.get(value);
15369 if (anchor) ctx.onCreate = res => {
15370 anchor.res = res;
15371 delete ctx.onCreate;
15372 };
15373 const res = value.toJSON(arg, ctx);
15374 if (anchor && ctx.onCreate) ctx.onCreate(res);
15375 return res;
15376 }
15377
15378 if ((!ctx || !ctx.keep) && typeof value === 'bigint') return Number(value);
15379 return value;
15380}
15381
15382class Scalar extends Node$1 {
15383 constructor(value) {
15384 super();
15385 this.value = value;
15386 }
15387
15388 toJSON(arg, ctx) {
15389 return ctx && ctx.keep ? this.value : toJSON(this.value, arg, ctx);
15390 }
15391
15392 toString() {
15393 return String(this.value);
15394 }
15395
15396}
15397
15398function collectionFromPath(schema, path, value) {
15399 let v = value;
15400
15401 for (let i = path.length - 1; i >= 0; --i) {
15402 const k = path[i];
15403
15404 if (Number.isInteger(k) && k >= 0) {
15405 const a = [];
15406 a[k] = v;
15407 v = a;
15408 } else {
15409 const o = {};
15410 Object.defineProperty(o, k, {
15411 value: v,
15412 writable: true,
15413 enumerable: true,
15414 configurable: true
15415 });
15416 v = o;
15417 }
15418 }
15419
15420 return schema.createNode(v, false);
15421} // null, undefined, or an empty non-string iterable (e.g. [])
15422
15423
15424const isEmptyPath = path => path == null || typeof path === 'object' && path[Symbol.iterator]().next().done;
15425class Collection extends Node$1 {
15426 constructor(schema) {
15427 super();
15428
15429 PlainValue$4._defineProperty(this, "items", []);
15430
15431 this.schema = schema;
15432 }
15433
15434 addIn(path, value) {
15435 if (isEmptyPath(path)) this.add(value);else {
15436 const [key, ...rest] = path;
15437 const node = this.get(key, true);
15438 if (node instanceof Collection) node.addIn(rest, value);else if (node === undefined && this.schema) this.set(key, collectionFromPath(this.schema, rest, value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
15439 }
15440 }
15441
15442 deleteIn([key, ...rest]) {
15443 if (rest.length === 0) return this.delete(key);
15444 const node = this.get(key, true);
15445 if (node instanceof Collection) return node.deleteIn(rest);else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
15446 }
15447
15448 getIn([key, ...rest], keepScalar) {
15449 const node = this.get(key, true);
15450 if (rest.length === 0) return !keepScalar && node instanceof Scalar ? node.value : node;else return node instanceof Collection ? node.getIn(rest, keepScalar) : undefined;
15451 }
15452
15453 hasAllNullValues() {
15454 return this.items.every(node => {
15455 if (!node || node.type !== 'PAIR') return false;
15456 const n = node.value;
15457 return n == null || n instanceof Scalar && n.value == null && !n.commentBefore && !n.comment && !n.tag;
15458 });
15459 }
15460
15461 hasIn([key, ...rest]) {
15462 if (rest.length === 0) return this.has(key);
15463 const node = this.get(key, true);
15464 return node instanceof Collection ? node.hasIn(rest) : false;
15465 }
15466
15467 setIn([key, ...rest], value) {
15468 if (rest.length === 0) {
15469 this.set(key, value);
15470 } else {
15471 const node = this.get(key, true);
15472 if (node instanceof Collection) node.setIn(rest, value);else if (node === undefined && this.schema) this.set(key, collectionFromPath(this.schema, rest, value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
15473 }
15474 } // overridden in implementations
15475
15476 /* istanbul ignore next */
15477
15478
15479 toJSON() {
15480 return null;
15481 }
15482
15483 toString(ctx, {
15484 blockItem,
15485 flowChars,
15486 isMap,
15487 itemIndent
15488 }, onComment, onChompKeep) {
15489 const {
15490 indent,
15491 indentStep,
15492 stringify
15493 } = ctx;
15494 const inFlow = this.type === PlainValue$4.Type.FLOW_MAP || this.type === PlainValue$4.Type.FLOW_SEQ || ctx.inFlow;
15495 if (inFlow) itemIndent += indentStep;
15496 const allNullValues = isMap && this.hasAllNullValues();
15497 ctx = Object.assign({}, ctx, {
15498 allNullValues,
15499 indent: itemIndent,
15500 inFlow,
15501 type: null
15502 });
15503 let chompKeep = false;
15504 let hasItemWithNewLine = false;
15505 const nodes = this.items.reduce((nodes, item, i) => {
15506 let comment;
15507
15508 if (item) {
15509 if (!chompKeep && item.spaceBefore) nodes.push({
15510 type: 'comment',
15511 str: ''
15512 });
15513 if (item.commentBefore) item.commentBefore.match(/^.*$/gm).forEach(line => {
15514 nodes.push({
15515 type: 'comment',
15516 str: `#${line}`
15517 });
15518 });
15519 if (item.comment) comment = item.comment;
15520 if (inFlow && (!chompKeep && item.spaceBefore || item.commentBefore || item.comment || item.key && (item.key.commentBefore || item.key.comment) || item.value && (item.value.commentBefore || item.value.comment))) hasItemWithNewLine = true;
15521 }
15522
15523 chompKeep = false;
15524 let str = stringify(item, ctx, () => comment = null, () => chompKeep = true);
15525 if (inFlow && !hasItemWithNewLine && str.includes('\n')) hasItemWithNewLine = true;
15526 if (inFlow && i < this.items.length - 1) str += ',';
15527 str = addComment(str, itemIndent, comment);
15528 if (chompKeep && (comment || inFlow)) chompKeep = false;
15529 nodes.push({
15530 type: 'item',
15531 str
15532 });
15533 return nodes;
15534 }, []);
15535 let str;
15536
15537 if (nodes.length === 0) {
15538 str = flowChars.start + flowChars.end;
15539 } else if (inFlow) {
15540 const {
15541 start,
15542 end
15543 } = flowChars;
15544 const strings = nodes.map(n => n.str);
15545
15546 if (hasItemWithNewLine || strings.reduce((sum, str) => sum + str.length + 2, 2) > Collection.maxFlowStringSingleLineLength) {
15547 str = start;
15548
15549 for (const s of strings) {
15550 str += s ? `\n${indentStep}${indent}${s}` : '\n';
15551 }
15552
15553 str += `\n${indent}${end}`;
15554 } else {
15555 str = `${start} ${strings.join(' ')} ${end}`;
15556 }
15557 } else {
15558 const strings = nodes.map(blockItem);
15559 str = strings.shift();
15560
15561 for (const s of strings) str += s ? `\n${indent}${s}` : '\n';
15562 }
15563
15564 if (this.comment) {
15565 str += '\n' + this.comment.replace(/^/gm, `${indent}#`);
15566 if (onComment) onComment();
15567 } else if (chompKeep && onChompKeep) onChompKeep();
15568
15569 return str;
15570 }
15571
15572}
15573
15574PlainValue$4._defineProperty(Collection, "maxFlowStringSingleLineLength", 60);
15575
15576function asItemIndex(key) {
15577 let idx = key instanceof Scalar ? key.value : key;
15578 if (idx && typeof idx === 'string') idx = Number(idx);
15579 return Number.isInteger(idx) && idx >= 0 ? idx : null;
15580}
15581
15582class YAMLSeq extends Collection {
15583 add(value) {
15584 this.items.push(value);
15585 }
15586
15587 delete(key) {
15588 const idx = asItemIndex(key);
15589 if (typeof idx !== 'number') return false;
15590 const del = this.items.splice(idx, 1);
15591 return del.length > 0;
15592 }
15593
15594 get(key, keepScalar) {
15595 const idx = asItemIndex(key);
15596 if (typeof idx !== 'number') return undefined;
15597 const it = this.items[idx];
15598 return !keepScalar && it instanceof Scalar ? it.value : it;
15599 }
15600
15601 has(key) {
15602 const idx = asItemIndex(key);
15603 return typeof idx === 'number' && idx < this.items.length;
15604 }
15605
15606 set(key, value) {
15607 const idx = asItemIndex(key);
15608 if (typeof idx !== 'number') throw new Error(`Expected a valid index, not ${key}.`);
15609 this.items[idx] = value;
15610 }
15611
15612 toJSON(_, ctx) {
15613 const seq = [];
15614 if (ctx && ctx.onCreate) ctx.onCreate(seq);
15615 let i = 0;
15616
15617 for (const item of this.items) seq.push(toJSON(item, String(i++), ctx));
15618
15619 return seq;
15620 }
15621
15622 toString(ctx, onComment, onChompKeep) {
15623 if (!ctx) return JSON.stringify(this);
15624 return super.toString(ctx, {
15625 blockItem: n => n.type === 'comment' ? n.str : `- ${n.str}`,
15626 flowChars: {
15627 start: '[',
15628 end: ']'
15629 },
15630 isMap: false,
15631 itemIndent: (ctx.indent || '') + ' '
15632 }, onComment, onChompKeep);
15633 }
15634
15635}
15636
15637const stringifyKey = (key, jsKey, ctx) => {
15638 if (jsKey === null) return '';
15639 if (typeof jsKey !== 'object') return String(jsKey);
15640 if (key instanceof Node$1 && ctx && ctx.doc) return key.toString({
15641 anchors: Object.create(null),
15642 doc: ctx.doc,
15643 indent: '',
15644 indentStep: ctx.indentStep,
15645 inFlow: true,
15646 inStringifyKey: true,
15647 stringify: ctx.stringify
15648 });
15649 return JSON.stringify(jsKey);
15650};
15651
15652class Pair extends Node$1 {
15653 constructor(key, value = null) {
15654 super();
15655 this.key = key;
15656 this.value = value;
15657 this.type = Pair.Type.PAIR;
15658 }
15659
15660 get commentBefore() {
15661 return this.key instanceof Node$1 ? this.key.commentBefore : undefined;
15662 }
15663
15664 set commentBefore(cb) {
15665 if (this.key == null) this.key = new Scalar(null);
15666 if (this.key instanceof Node$1) this.key.commentBefore = cb;else {
15667 const msg = 'Pair.commentBefore is an alias for Pair.key.commentBefore. To set it, the key must be a Node.';
15668 throw new Error(msg);
15669 }
15670 }
15671
15672 addToJSMap(ctx, map) {
15673 const key = toJSON(this.key, '', ctx);
15674
15675 if (map instanceof Map) {
15676 const value = toJSON(this.value, key, ctx);
15677 map.set(key, value);
15678 } else if (map instanceof Set) {
15679 map.add(key);
15680 } else {
15681 const stringKey = stringifyKey(this.key, key, ctx);
15682 const value = toJSON(this.value, stringKey, ctx);
15683 if (stringKey in map) Object.defineProperty(map, stringKey, {
15684 value,
15685 writable: true,
15686 enumerable: true,
15687 configurable: true
15688 });else map[stringKey] = value;
15689 }
15690
15691 return map;
15692 }
15693
15694 toJSON(_, ctx) {
15695 const pair = ctx && ctx.mapAsMap ? new Map() : {};
15696 return this.addToJSMap(ctx, pair);
15697 }
15698
15699 toString(ctx, onComment, onChompKeep) {
15700 if (!ctx || !ctx.doc) return JSON.stringify(this);
15701 const {
15702 indent: indentSize,
15703 indentSeq,
15704 simpleKeys
15705 } = ctx.doc.options;
15706 let {
15707 key,
15708 value
15709 } = this;
15710 let keyComment = key instanceof Node$1 && key.comment;
15711
15712 if (simpleKeys) {
15713 if (keyComment) {
15714 throw new Error('With simple keys, key nodes cannot have comments');
15715 }
15716
15717 if (key instanceof Collection) {
15718 const msg = 'With simple keys, collection cannot be used as a key value';
15719 throw new Error(msg);
15720 }
15721 }
15722
15723 let explicitKey = !simpleKeys && (!key || keyComment || (key instanceof Node$1 ? key instanceof Collection || key.type === PlainValue$4.Type.BLOCK_FOLDED || key.type === PlainValue$4.Type.BLOCK_LITERAL : typeof key === 'object'));
15724 const {
15725 doc,
15726 indent,
15727 indentStep,
15728 stringify
15729 } = ctx;
15730 ctx = Object.assign({}, ctx, {
15731 implicitKey: !explicitKey,
15732 indent: indent + indentStep
15733 });
15734 let chompKeep = false;
15735 let str = stringify(key, ctx, () => keyComment = null, () => chompKeep = true);
15736 str = addComment(str, ctx.indent, keyComment);
15737
15738 if (!explicitKey && str.length > 1024) {
15739 if (simpleKeys) throw new Error('With simple keys, single line scalar must not span more than 1024 characters');
15740 explicitKey = true;
15741 }
15742
15743 if (ctx.allNullValues && !simpleKeys) {
15744 if (this.comment) {
15745 str = addComment(str, ctx.indent, this.comment);
15746 if (onComment) onComment();
15747 } else if (chompKeep && !keyComment && onChompKeep) onChompKeep();
15748
15749 return ctx.inFlow && !explicitKey ? str : `? ${str}`;
15750 }
15751
15752 str = explicitKey ? `? ${str}\n${indent}:` : `${str}:`;
15753
15754 if (this.comment) {
15755 // expected (but not strictly required) to be a single-line comment
15756 str = addComment(str, ctx.indent, this.comment);
15757 if (onComment) onComment();
15758 }
15759
15760 let vcb = '';
15761 let valueComment = null;
15762
15763 if (value instanceof Node$1) {
15764 if (value.spaceBefore) vcb = '\n';
15765
15766 if (value.commentBefore) {
15767 const cs = value.commentBefore.replace(/^/gm, `${ctx.indent}#`);
15768 vcb += `\n${cs}`;
15769 }
15770
15771 valueComment = value.comment;
15772 } else if (value && typeof value === 'object') {
15773 value = doc.schema.createNode(value, true);
15774 }
15775
15776 ctx.implicitKey = false;
15777 if (!explicitKey && !this.comment && value instanceof Scalar) ctx.indentAtStart = str.length + 1;
15778 chompKeep = false;
15779
15780 if (!indentSeq && indentSize >= 2 && !ctx.inFlow && !explicitKey && value instanceof YAMLSeq && value.type !== PlainValue$4.Type.FLOW_SEQ && !value.tag && !doc.anchors.getName(value)) {
15781 // If indentSeq === false, consider '- ' as part of indentation where possible
15782 ctx.indent = ctx.indent.substr(2);
15783 }
15784
15785 const valueStr = stringify(value, ctx, () => valueComment = null, () => chompKeep = true);
15786 let ws = ' ';
15787
15788 if (vcb || this.comment) {
15789 ws = `${vcb}\n${ctx.indent}`;
15790 } else if (!explicitKey && value instanceof Collection) {
15791 const flow = valueStr[0] === '[' || valueStr[0] === '{';
15792 if (!flow || valueStr.includes('\n')) ws = `\n${ctx.indent}`;
15793 } else if (valueStr[0] === '\n') ws = '';
15794
15795 if (chompKeep && !valueComment && onChompKeep) onChompKeep();
15796 return addComment(str + ws + valueStr, ctx.indent, valueComment);
15797 }
15798
15799}
15800
15801PlainValue$4._defineProperty(Pair, "Type", {
15802 PAIR: 'PAIR',
15803 MERGE_PAIR: 'MERGE_PAIR'
15804});
15805
15806const getAliasCount = (node, anchors) => {
15807 if (node instanceof Alias) {
15808 const anchor = anchors.get(node.source);
15809 return anchor.count * anchor.aliasCount;
15810 } else if (node instanceof Collection) {
15811 let count = 0;
15812
15813 for (const item of node.items) {
15814 const c = getAliasCount(item, anchors);
15815 if (c > count) count = c;
15816 }
15817
15818 return count;
15819 } else if (node instanceof Pair) {
15820 const kc = getAliasCount(node.key, anchors);
15821 const vc = getAliasCount(node.value, anchors);
15822 return Math.max(kc, vc);
15823 }
15824
15825 return 1;
15826};
15827
15828class Alias extends Node$1 {
15829 static stringify({
15830 range,
15831 source
15832 }, {
15833 anchors,
15834 doc,
15835 implicitKey,
15836 inStringifyKey
15837 }) {
15838 let anchor = Object.keys(anchors).find(a => anchors[a] === source);
15839 if (!anchor && inStringifyKey) anchor = doc.anchors.getName(source) || doc.anchors.newName();
15840 if (anchor) return `*${anchor}${implicitKey ? ' ' : ''}`;
15841 const msg = doc.anchors.getName(source) ? 'Alias node must be after source node' : 'Source node not found for alias node';
15842 throw new Error(`${msg} [${range}]`);
15843 }
15844
15845 constructor(source) {
15846 super();
15847 this.source = source;
15848 this.type = PlainValue$4.Type.ALIAS;
15849 }
15850
15851 set tag(t) {
15852 throw new Error('Alias nodes cannot have tags');
15853 }
15854
15855 toJSON(arg, ctx) {
15856 if (!ctx) return toJSON(this.source, arg, ctx);
15857 const {
15858 anchors,
15859 maxAliasCount
15860 } = ctx;
15861 const anchor = anchors.get(this.source);
15862 /* istanbul ignore if */
15863
15864 if (!anchor || anchor.res === undefined) {
15865 const msg = 'This should not happen: Alias anchor was not resolved?';
15866 if (this.cstNode) throw new PlainValue$4.YAMLReferenceError(this.cstNode, msg);else throw new ReferenceError(msg);
15867 }
15868
15869 if (maxAliasCount >= 0) {
15870 anchor.count += 1;
15871 if (anchor.aliasCount === 0) anchor.aliasCount = getAliasCount(this.source, anchors);
15872
15873 if (anchor.count * anchor.aliasCount > maxAliasCount) {
15874 const msg = 'Excessive alias count indicates a resource exhaustion attack';
15875 if (this.cstNode) throw new PlainValue$4.YAMLReferenceError(this.cstNode, msg);else throw new ReferenceError(msg);
15876 }
15877 }
15878
15879 return anchor.res;
15880 } // Only called when stringifying an alias mapping key while constructing
15881 // Object output.
15882
15883
15884 toString(ctx) {
15885 return Alias.stringify(this, ctx);
15886 }
15887
15888}
15889
15890PlainValue$4._defineProperty(Alias, "default", true);
15891
15892function findPair(items, key) {
15893 const k = key instanceof Scalar ? key.value : key;
15894
15895 for (const it of items) {
15896 if (it instanceof Pair) {
15897 if (it.key === key || it.key === k) return it;
15898 if (it.key && it.key.value === k) return it;
15899 }
15900 }
15901
15902 return undefined;
15903}
15904class YAMLMap extends Collection {
15905 add(pair, overwrite) {
15906 if (!pair) pair = new Pair(pair);else if (!(pair instanceof Pair)) pair = new Pair(pair.key || pair, pair.value);
15907 const prev = findPair(this.items, pair.key);
15908 const sortEntries = this.schema && this.schema.sortMapEntries;
15909
15910 if (prev) {
15911 if (overwrite) prev.value = pair.value;else throw new Error(`Key ${pair.key} already set`);
15912 } else if (sortEntries) {
15913 const i = this.items.findIndex(item => sortEntries(pair, item) < 0);
15914 if (i === -1) this.items.push(pair);else this.items.splice(i, 0, pair);
15915 } else {
15916 this.items.push(pair);
15917 }
15918 }
15919
15920 delete(key) {
15921 const it = findPair(this.items, key);
15922 if (!it) return false;
15923 const del = this.items.splice(this.items.indexOf(it), 1);
15924 return del.length > 0;
15925 }
15926
15927 get(key, keepScalar) {
15928 const it = findPair(this.items, key);
15929 const node = it && it.value;
15930 return !keepScalar && node instanceof Scalar ? node.value : node;
15931 }
15932
15933 has(key) {
15934 return !!findPair(this.items, key);
15935 }
15936
15937 set(key, value) {
15938 this.add(new Pair(key, value), true);
15939 }
15940 /**
15941 * @param {*} arg ignored
15942 * @param {*} ctx Conversion context, originally set in Document#toJSON()
15943 * @param {Class} Type If set, forces the returned collection type
15944 * @returns {*} Instance of Type, Map, or Object
15945 */
15946
15947
15948 toJSON(_, ctx, Type) {
15949 const map = Type ? new Type() : ctx && ctx.mapAsMap ? new Map() : {};
15950 if (ctx && ctx.onCreate) ctx.onCreate(map);
15951
15952 for (const item of this.items) item.addToJSMap(ctx, map);
15953
15954 return map;
15955 }
15956
15957 toString(ctx, onComment, onChompKeep) {
15958 if (!ctx) return JSON.stringify(this);
15959
15960 for (const item of this.items) {
15961 if (!(item instanceof Pair)) throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);
15962 }
15963
15964 return super.toString(ctx, {
15965 blockItem: n => n.str,
15966 flowChars: {
15967 start: '{',
15968 end: '}'
15969 },
15970 isMap: true,
15971 itemIndent: ctx.indent || ''
15972 }, onComment, onChompKeep);
15973 }
15974
15975}
15976
15977const MERGE_KEY = '<<';
15978class Merge extends Pair {
15979 constructor(pair) {
15980 if (pair instanceof Pair) {
15981 let seq = pair.value;
15982
15983 if (!(seq instanceof YAMLSeq)) {
15984 seq = new YAMLSeq();
15985 seq.items.push(pair.value);
15986 seq.range = pair.value.range;
15987 }
15988
15989 super(pair.key, seq);
15990 this.range = pair.range;
15991 } else {
15992 super(new Scalar(MERGE_KEY), new YAMLSeq());
15993 }
15994
15995 this.type = Pair.Type.MERGE_PAIR;
15996 } // If the value associated with a merge key is a single mapping node, each of
15997 // its key/value pairs is inserted into the current mapping, unless the key
15998 // already exists in it. If the value associated with the merge key is a
15999 // sequence, then this sequence is expected to contain mapping nodes and each
16000 // of these nodes is merged in turn according to its order in the sequence.
16001 // Keys in mapping nodes earlier in the sequence override keys specified in
16002 // later mapping nodes. -- http://yaml.org/type/merge.html
16003
16004
16005 addToJSMap(ctx, map) {
16006 for (const {
16007 source
16008 } of this.value.items) {
16009 if (!(source instanceof YAMLMap)) throw new Error('Merge sources must be maps');
16010 const srcMap = source.toJSON(null, ctx, Map);
16011
16012 for (const [key, value] of srcMap) {
16013 if (map instanceof Map) {
16014 if (!map.has(key)) map.set(key, value);
16015 } else if (map instanceof Set) {
16016 map.add(key);
16017 } else if (!Object.prototype.hasOwnProperty.call(map, key)) {
16018 Object.defineProperty(map, key, {
16019 value,
16020 writable: true,
16021 enumerable: true,
16022 configurable: true
16023 });
16024 }
16025 }
16026 }
16027
16028 return map;
16029 }
16030
16031 toString(ctx, onComment) {
16032 const seq = this.value;
16033 if (seq.items.length > 1) return super.toString(ctx, onComment);
16034 this.value = seq.items[0];
16035 const str = super.toString(ctx, onComment);
16036 this.value = seq;
16037 return str;
16038 }
16039
16040}
16041
16042const binaryOptions = {
16043 defaultType: PlainValue$4.Type.BLOCK_LITERAL,
16044 lineWidth: 76
16045};
16046const boolOptions = {
16047 trueStr: 'true',
16048 falseStr: 'false'
16049};
16050const intOptions = {
16051 asBigInt: false
16052};
16053const nullOptions = {
16054 nullStr: 'null'
16055};
16056const strOptions = {
16057 defaultType: PlainValue$4.Type.PLAIN,
16058 doubleQuoted: {
16059 jsonEncoding: false,
16060 minMultiLineLength: 40
16061 },
16062 fold: {
16063 lineWidth: 80,
16064 minContentWidth: 20
16065 }
16066};
16067
16068function resolveScalar(str, tags, scalarFallback) {
16069 for (const {
16070 format,
16071 test,
16072 resolve
16073 } of tags) {
16074 if (test) {
16075 const match = str.match(test);
16076
16077 if (match) {
16078 let res = resolve.apply(null, match);
16079 if (!(res instanceof Scalar)) res = new Scalar(res);
16080 if (format) res.format = format;
16081 return res;
16082 }
16083 }
16084 }
16085
16086 if (scalarFallback) str = scalarFallback(str);
16087 return new Scalar(str);
16088}
16089
16090const FOLD_FLOW = 'flow';
16091const FOLD_BLOCK = 'block';
16092const FOLD_QUOTED = 'quoted'; // presumes i+1 is at the start of a line
16093// returns index of last newline in more-indented block
16094
16095const consumeMoreIndentedLines = (text, i) => {
16096 let ch = text[i + 1];
16097
16098 while (ch === ' ' || ch === '\t') {
16099 do {
16100 ch = text[i += 1];
16101 } while (ch && ch !== '\n');
16102
16103 ch = text[i + 1];
16104 }
16105
16106 return i;
16107};
16108/**
16109 * Tries to keep input at up to `lineWidth` characters, splitting only on spaces
16110 * not followed by newlines or spaces unless `mode` is `'quoted'`. Lines are
16111 * terminated with `\n` and started with `indent`.
16112 *
16113 * @param {string} text
16114 * @param {string} indent
16115 * @param {string} [mode='flow'] `'block'` prevents more-indented lines
16116 * from being folded; `'quoted'` allows for `\` escapes, including escaped
16117 * newlines
16118 * @param {Object} options
16119 * @param {number} [options.indentAtStart] Accounts for leading contents on
16120 * the first line, defaulting to `indent.length`
16121 * @param {number} [options.lineWidth=80]
16122 * @param {number} [options.minContentWidth=20] Allow highly indented lines to
16123 * stretch the line width or indent content from the start
16124 * @param {function} options.onFold Called once if the text is folded
16125 * @param {function} options.onFold Called once if any line of text exceeds
16126 * lineWidth characters
16127 */
16128
16129
16130function foldFlowLines(text, indent, mode, {
16131 indentAtStart,
16132 lineWidth = 80,
16133 minContentWidth = 20,
16134 onFold,
16135 onOverflow
16136}) {
16137 if (!lineWidth || lineWidth < 0) return text;
16138 const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length);
16139 if (text.length <= endStep) return text;
16140 const folds = [];
16141 const escapedFolds = {};
16142 let end = lineWidth - indent.length;
16143
16144 if (typeof indentAtStart === 'number') {
16145 if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) folds.push(0);else end = lineWidth - indentAtStart;
16146 }
16147
16148 let split = undefined;
16149 let prev = undefined;
16150 let overflow = false;
16151 let i = -1;
16152 let escStart = -1;
16153 let escEnd = -1;
16154
16155 if (mode === FOLD_BLOCK) {
16156 i = consumeMoreIndentedLines(text, i);
16157 if (i !== -1) end = i + endStep;
16158 }
16159
16160 for (let ch; ch = text[i += 1];) {
16161 if (mode === FOLD_QUOTED && ch === '\\') {
16162 escStart = i;
16163
16164 switch (text[i + 1]) {
16165 case 'x':
16166 i += 3;
16167 break;
16168
16169 case 'u':
16170 i += 5;
16171 break;
16172
16173 case 'U':
16174 i += 9;
16175 break;
16176
16177 default:
16178 i += 1;
16179 }
16180
16181 escEnd = i;
16182 }
16183
16184 if (ch === '\n') {
16185 if (mode === FOLD_BLOCK) i = consumeMoreIndentedLines(text, i);
16186 end = i + endStep;
16187 split = undefined;
16188 } else {
16189 if (ch === ' ' && prev && prev !== ' ' && prev !== '\n' && prev !== '\t') {
16190 // space surrounded by non-space can be replaced with newline + indent
16191 const next = text[i + 1];
16192 if (next && next !== ' ' && next !== '\n' && next !== '\t') split = i;
16193 }
16194
16195 if (i >= end) {
16196 if (split) {
16197 folds.push(split);
16198 end = split + endStep;
16199 split = undefined;
16200 } else if (mode === FOLD_QUOTED) {
16201 // white-space collected at end may stretch past lineWidth
16202 while (prev === ' ' || prev === '\t') {
16203 prev = ch;
16204 ch = text[i += 1];
16205 overflow = true;
16206 } // Account for newline escape, but don't break preceding escape
16207
16208
16209 const j = i > escEnd + 1 ? i - 2 : escStart - 1; // Bail out if lineWidth & minContentWidth are shorter than an escape string
16210
16211 if (escapedFolds[j]) return text;
16212 folds.push(j);
16213 escapedFolds[j] = true;
16214 end = j + endStep;
16215 split = undefined;
16216 } else {
16217 overflow = true;
16218 }
16219 }
16220 }
16221
16222 prev = ch;
16223 }
16224
16225 if (overflow && onOverflow) onOverflow();
16226 if (folds.length === 0) return text;
16227 if (onFold) onFold();
16228 let res = text.slice(0, folds[0]);
16229
16230 for (let i = 0; i < folds.length; ++i) {
16231 const fold = folds[i];
16232 const end = folds[i + 1] || text.length;
16233 if (fold === 0) res = `\n${indent}${text.slice(0, end)}`;else {
16234 if (mode === FOLD_QUOTED && escapedFolds[fold]) res += `${text[fold]}\\`;
16235 res += `\n${indent}${text.slice(fold + 1, end)}`;
16236 }
16237 }
16238
16239 return res;
16240}
16241
16242const getFoldOptions = ({
16243 indentAtStart
16244}) => indentAtStart ? Object.assign({
16245 indentAtStart
16246}, strOptions.fold) : strOptions.fold; // Also checks for lines starting with %, as parsing the output as YAML 1.1 will
16247// presume that's starting a new document.
16248
16249
16250const containsDocumentMarker = str => /^(%|---|\.\.\.)/m.test(str);
16251
16252function lineLengthOverLimit(str, lineWidth, indentLength) {
16253 if (!lineWidth || lineWidth < 0) return false;
16254 const limit = lineWidth - indentLength;
16255 const strLen = str.length;
16256 if (strLen <= limit) return false;
16257
16258 for (let i = 0, start = 0; i < strLen; ++i) {
16259 if (str[i] === '\n') {
16260 if (i - start > limit) return true;
16261 start = i + 1;
16262 if (strLen - start <= limit) return false;
16263 }
16264 }
16265
16266 return true;
16267}
16268
16269function doubleQuotedString(value, ctx) {
16270 const {
16271 implicitKey
16272 } = ctx;
16273 const {
16274 jsonEncoding,
16275 minMultiLineLength
16276 } = strOptions.doubleQuoted;
16277 const json = JSON.stringify(value);
16278 if (jsonEncoding) return json;
16279 const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : '');
16280 let str = '';
16281 let start = 0;
16282
16283 for (let i = 0, ch = json[i]; ch; ch = json[++i]) {
16284 if (ch === ' ' && json[i + 1] === '\\' && json[i + 2] === 'n') {
16285 // space before newline needs to be escaped to not be folded
16286 str += json.slice(start, i) + '\\ ';
16287 i += 1;
16288 start = i;
16289 ch = '\\';
16290 }
16291
16292 if (ch === '\\') switch (json[i + 1]) {
16293 case 'u':
16294 {
16295 str += json.slice(start, i);
16296 const code = json.substr(i + 2, 4);
16297
16298 switch (code) {
16299 case '0000':
16300 str += '\\0';
16301 break;
16302
16303 case '0007':
16304 str += '\\a';
16305 break;
16306
16307 case '000b':
16308 str += '\\v';
16309 break;
16310
16311 case '001b':
16312 str += '\\e';
16313 break;
16314
16315 case '0085':
16316 str += '\\N';
16317 break;
16318
16319 case '00a0':
16320 str += '\\_';
16321 break;
16322
16323 case '2028':
16324 str += '\\L';
16325 break;
16326
16327 case '2029':
16328 str += '\\P';
16329 break;
16330
16331 default:
16332 if (code.substr(0, 2) === '00') str += '\\x' + code.substr(2);else str += json.substr(i, 6);
16333 }
16334
16335 i += 5;
16336 start = i + 1;
16337 }
16338 break;
16339
16340 case 'n':
16341 if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) {
16342 i += 1;
16343 } else {
16344 // folding will eat first newline
16345 str += json.slice(start, i) + '\n\n';
16346
16347 while (json[i + 2] === '\\' && json[i + 3] === 'n' && json[i + 4] !== '"') {
16348 str += '\n';
16349 i += 2;
16350 }
16351
16352 str += indent; // space after newline needs to be escaped to not be folded
16353
16354 if (json[i + 2] === ' ') str += '\\';
16355 i += 1;
16356 start = i + 1;
16357 }
16358
16359 break;
16360
16361 default:
16362 i += 1;
16363 }
16364 }
16365
16366 str = start ? str + json.slice(start) : json;
16367 return implicitKey ? str : foldFlowLines(str, indent, FOLD_QUOTED, getFoldOptions(ctx));
16368}
16369
16370function singleQuotedString(value, ctx) {
16371 if (ctx.implicitKey) {
16372 if (/\n/.test(value)) return doubleQuotedString(value, ctx);
16373 } else {
16374 // single quoted string can't have leading or trailing whitespace around newline
16375 if (/[ \t]\n|\n[ \t]/.test(value)) return doubleQuotedString(value, ctx);
16376 }
16377
16378 const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : '');
16379 const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$&\n${indent}`) + "'";
16380 return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx));
16381}
16382
16383function blockString({
16384 comment,
16385 type,
16386 value
16387}, ctx, onComment, onChompKeep) {
16388 // 1. Block can't end in whitespace unless the last line is non-empty.
16389 // 2. Strings consisting of only whitespace are best rendered explicitly.
16390 if (/\n[\t ]+$/.test(value) || /^\s*$/.test(value)) {
16391 return doubleQuotedString(value, ctx);
16392 }
16393
16394 const indent = ctx.indent || (ctx.forceBlockIndent || containsDocumentMarker(value) ? ' ' : '');
16395 const indentSize = indent ? '2' : '1'; // root is at -1
16396
16397 const literal = type === PlainValue$4.Type.BLOCK_FOLDED ? false : type === PlainValue$4.Type.BLOCK_LITERAL ? true : !lineLengthOverLimit(value, strOptions.fold.lineWidth, indent.length);
16398 let header = literal ? '|' : '>';
16399 if (!value) return header + '\n';
16400 let wsStart = '';
16401 let wsEnd = '';
16402 value = value.replace(/[\n\t ]*$/, ws => {
16403 const n = ws.indexOf('\n');
16404
16405 if (n === -1) {
16406 header += '-'; // strip
16407 } else if (value === ws || n !== ws.length - 1) {
16408 header += '+'; // keep
16409
16410 if (onChompKeep) onChompKeep();
16411 }
16412
16413 wsEnd = ws.replace(/\n$/, '');
16414 return '';
16415 }).replace(/^[\n ]*/, ws => {
16416 if (ws.indexOf(' ') !== -1) header += indentSize;
16417 const m = ws.match(/ +$/);
16418
16419 if (m) {
16420 wsStart = ws.slice(0, -m[0].length);
16421 return m[0];
16422 } else {
16423 wsStart = ws;
16424 return '';
16425 }
16426 });
16427 if (wsEnd) wsEnd = wsEnd.replace(/\n+(?!\n|$)/g, `$&${indent}`);
16428 if (wsStart) wsStart = wsStart.replace(/\n+/g, `$&${indent}`);
16429
16430 if (comment) {
16431 header += ' #' + comment.replace(/ ?[\r\n]+/g, ' ');
16432 if (onComment) onComment();
16433 }
16434
16435 if (!value) return `${header}${indentSize}\n${indent}${wsEnd}`;
16436
16437 if (literal) {
16438 value = value.replace(/\n+/g, `$&${indent}`);
16439 return `${header}\n${indent}${wsStart}${value}${wsEnd}`;
16440 }
16441
16442 value = value.replace(/\n+/g, '\n$&').replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, '$1$2') // more-indented lines aren't folded
16443 // ^ ind.line ^ empty ^ capture next empty lines only at end of indent
16444 .replace(/\n+/g, `$&${indent}`);
16445 const body = foldFlowLines(`${wsStart}${value}${wsEnd}`, indent, FOLD_BLOCK, strOptions.fold);
16446 return `${header}\n${indent}${body}`;
16447}
16448
16449function plainString(item, ctx, onComment, onChompKeep) {
16450 const {
16451 comment,
16452 type,
16453 value
16454 } = item;
16455 const {
16456 actualString,
16457 implicitKey,
16458 indent,
16459 inFlow
16460 } = ctx;
16461
16462 if (implicitKey && /[\n[\]{},]/.test(value) || inFlow && /[[\]{},]/.test(value)) {
16463 return doubleQuotedString(value, ctx);
16464 }
16465
16466 if (!value || /^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) {
16467 // not allowed:
16468 // - empty string, '-' or '?'
16469 // - start with an indicator character (except [?:-]) or /[?-] /
16470 // - '\n ', ': ' or ' \n' anywhere
16471 // - '#' not preceded by a non-space char
16472 // - end with ' ' or ':'
16473 return implicitKey || inFlow || value.indexOf('\n') === -1 ? value.indexOf('"') !== -1 && value.indexOf("'") === -1 ? singleQuotedString(value, ctx) : doubleQuotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep);
16474 }
16475
16476 if (!implicitKey && !inFlow && type !== PlainValue$4.Type.PLAIN && value.indexOf('\n') !== -1) {
16477 // Where allowed & type not set explicitly, prefer block style for multiline strings
16478 return blockString(item, ctx, onComment, onChompKeep);
16479 }
16480
16481 if (indent === '' && containsDocumentMarker(value)) {
16482 ctx.forceBlockIndent = true;
16483 return blockString(item, ctx, onComment, onChompKeep);
16484 }
16485
16486 const str = value.replace(/\n+/g, `$&\n${indent}`); // Verify that output will be parsed as a string, as e.g. plain numbers and
16487 // booleans get parsed with those types in v1.2 (e.g. '42', 'true' & '0.9e-3'),
16488 // and others in v1.1.
16489
16490 if (actualString) {
16491 const {
16492 tags
16493 } = ctx.doc.schema;
16494 const resolved = resolveScalar(str, tags, tags.scalarFallback).value;
16495 if (typeof resolved !== 'string') return doubleQuotedString(value, ctx);
16496 }
16497
16498 const body = implicitKey ? str : foldFlowLines(str, indent, FOLD_FLOW, getFoldOptions(ctx));
16499
16500 if (comment && !inFlow && (body.indexOf('\n') !== -1 || comment.indexOf('\n') !== -1)) {
16501 if (onComment) onComment();
16502 return addCommentBefore(body, indent, comment);
16503 }
16504
16505 return body;
16506}
16507
16508function stringifyString(item, ctx, onComment, onChompKeep) {
16509 const {
16510 defaultType
16511 } = strOptions;
16512 const {
16513 implicitKey,
16514 inFlow
16515 } = ctx;
16516 let {
16517 type,
16518 value
16519 } = item;
16520
16521 if (typeof value !== 'string') {
16522 value = String(value);
16523 item = Object.assign({}, item, {
16524 value
16525 });
16526 }
16527
16528 const _stringify = _type => {
16529 switch (_type) {
16530 case PlainValue$4.Type.BLOCK_FOLDED:
16531 case PlainValue$4.Type.BLOCK_LITERAL:
16532 return blockString(item, ctx, onComment, onChompKeep);
16533
16534 case PlainValue$4.Type.QUOTE_DOUBLE:
16535 return doubleQuotedString(value, ctx);
16536
16537 case PlainValue$4.Type.QUOTE_SINGLE:
16538 return singleQuotedString(value, ctx);
16539
16540 case PlainValue$4.Type.PLAIN:
16541 return plainString(item, ctx, onComment, onChompKeep);
16542
16543 default:
16544 return null;
16545 }
16546 };
16547
16548 if (type !== PlainValue$4.Type.QUOTE_DOUBLE && /[\x00-\x08\x0b-\x1f\x7f-\x9f]/.test(value)) {
16549 // force double quotes on control characters
16550 type = PlainValue$4.Type.QUOTE_DOUBLE;
16551 } else if ((implicitKey || inFlow) && (type === PlainValue$4.Type.BLOCK_FOLDED || type === PlainValue$4.Type.BLOCK_LITERAL)) {
16552 // should not happen; blocks are not valid inside flow containers
16553 type = PlainValue$4.Type.QUOTE_DOUBLE;
16554 }
16555
16556 let res = _stringify(type);
16557
16558 if (res === null) {
16559 res = _stringify(defaultType);
16560 if (res === null) throw new Error(`Unsupported default string type ${defaultType}`);
16561 }
16562
16563 return res;
16564}
16565
16566function stringifyNumber({
16567 format,
16568 minFractionDigits,
16569 tag,
16570 value
16571}) {
16572 if (typeof value === 'bigint') return String(value);
16573 if (!isFinite(value)) return isNaN(value) ? '.nan' : value < 0 ? '-.inf' : '.inf';
16574 let n = JSON.stringify(value);
16575
16576 if (!format && minFractionDigits && (!tag || tag === 'tag:yaml.org,2002:float') && /^\d/.test(n)) {
16577 let i = n.indexOf('.');
16578
16579 if (i < 0) {
16580 i = n.length;
16581 n += '.';
16582 }
16583
16584 let d = minFractionDigits - (n.length - i - 1);
16585
16586 while (d-- > 0) n += '0';
16587 }
16588
16589 return n;
16590}
16591
16592function checkFlowCollectionEnd(errors, cst) {
16593 let char, name;
16594
16595 switch (cst.type) {
16596 case PlainValue$4.Type.FLOW_MAP:
16597 char = '}';
16598 name = 'flow map';
16599 break;
16600
16601 case PlainValue$4.Type.FLOW_SEQ:
16602 char = ']';
16603 name = 'flow sequence';
16604 break;
16605
16606 default:
16607 errors.push(new PlainValue$4.YAMLSemanticError(cst, 'Not a flow collection!?'));
16608 return;
16609 }
16610
16611 let lastItem;
16612
16613 for (let i = cst.items.length - 1; i >= 0; --i) {
16614 const item = cst.items[i];
16615
16616 if (!item || item.type !== PlainValue$4.Type.COMMENT) {
16617 lastItem = item;
16618 break;
16619 }
16620 }
16621
16622 if (lastItem && lastItem.char !== char) {
16623 const msg = `Expected ${name} to end with ${char}`;
16624 let err;
16625
16626 if (typeof lastItem.offset === 'number') {
16627 err = new PlainValue$4.YAMLSemanticError(cst, msg);
16628 err.offset = lastItem.offset + 1;
16629 } else {
16630 err = new PlainValue$4.YAMLSemanticError(lastItem, msg);
16631 if (lastItem.range && lastItem.range.end) err.offset = lastItem.range.end - lastItem.range.start;
16632 }
16633
16634 errors.push(err);
16635 }
16636}
16637function checkFlowCommentSpace(errors, comment) {
16638 const prev = comment.context.src[comment.range.start - 1];
16639
16640 if (prev !== '\n' && prev !== '\t' && prev !== ' ') {
16641 const msg = 'Comments must be separated from other tokens by white space characters';
16642 errors.push(new PlainValue$4.YAMLSemanticError(comment, msg));
16643 }
16644}
16645function getLongKeyError(source, key) {
16646 const sk = String(key);
16647 const k = sk.substr(0, 8) + '...' + sk.substr(-8);
16648 return new PlainValue$4.YAMLSemanticError(source, `The "${k}" key is too long`);
16649}
16650function resolveComments(collection, comments) {
16651 for (const {
16652 afterKey,
16653 before,
16654 comment
16655 } of comments) {
16656 let item = collection.items[before];
16657
16658 if (!item) {
16659 if (comment !== undefined) {
16660 if (collection.comment) collection.comment += '\n' + comment;else collection.comment = comment;
16661 }
16662 } else {
16663 if (afterKey && item.value) item = item.value;
16664
16665 if (comment === undefined) {
16666 if (afterKey || !item.commentBefore) item.spaceBefore = true;
16667 } else {
16668 if (item.commentBefore) item.commentBefore += '\n' + comment;else item.commentBefore = comment;
16669 }
16670 }
16671 }
16672}
16673
16674// on error, will return { str: string, errors: Error[] }
16675function resolveString(doc, node) {
16676 const res = node.strValue;
16677 if (!res) return '';
16678 if (typeof res === 'string') return res;
16679 res.errors.forEach(error => {
16680 if (!error.source) error.source = node;
16681 doc.errors.push(error);
16682 });
16683 return res.str;
16684}
16685
16686function resolveTagHandle(doc, node) {
16687 const {
16688 handle,
16689 suffix
16690 } = node.tag;
16691 let prefix = doc.tagPrefixes.find(p => p.handle === handle);
16692
16693 if (!prefix) {
16694 const dtp = doc.getDefaults().tagPrefixes;
16695 if (dtp) prefix = dtp.find(p => p.handle === handle);
16696 if (!prefix) throw new PlainValue$4.YAMLSemanticError(node, `The ${handle} tag handle is non-default and was not declared.`);
16697 }
16698
16699 if (!suffix) throw new PlainValue$4.YAMLSemanticError(node, `The ${handle} tag has no suffix.`);
16700
16701 if (handle === '!' && (doc.version || doc.options.version) === '1.0') {
16702 if (suffix[0] === '^') {
16703 doc.warnings.push(new PlainValue$4.YAMLWarning(node, 'YAML 1.0 ^ tag expansion is not supported'));
16704 return suffix;
16705 }
16706
16707 if (/[:/]/.test(suffix)) {
16708 // word/foo -> tag:word.yaml.org,2002:foo
16709 const vocab = suffix.match(/^([a-z0-9-]+)\/(.*)/i);
16710 return vocab ? `tag:${vocab[1]}.yaml.org,2002:${vocab[2]}` : `tag:${suffix}`;
16711 }
16712 }
16713
16714 return prefix.prefix + decodeURIComponent(suffix);
16715}
16716
16717function resolveTagName(doc, node) {
16718 const {
16719 tag,
16720 type
16721 } = node;
16722 let nonSpecific = false;
16723
16724 if (tag) {
16725 const {
16726 handle,
16727 suffix,
16728 verbatim
16729 } = tag;
16730
16731 if (verbatim) {
16732 if (verbatim !== '!' && verbatim !== '!!') return verbatim;
16733 const msg = `Verbatim tags aren't resolved, so ${verbatim} is invalid.`;
16734 doc.errors.push(new PlainValue$4.YAMLSemanticError(node, msg));
16735 } else if (handle === '!' && !suffix) {
16736 nonSpecific = true;
16737 } else {
16738 try {
16739 return resolveTagHandle(doc, node);
16740 } catch (error) {
16741 doc.errors.push(error);
16742 }
16743 }
16744 }
16745
16746 switch (type) {
16747 case PlainValue$4.Type.BLOCK_FOLDED:
16748 case PlainValue$4.Type.BLOCK_LITERAL:
16749 case PlainValue$4.Type.QUOTE_DOUBLE:
16750 case PlainValue$4.Type.QUOTE_SINGLE:
16751 return PlainValue$4.defaultTags.STR;
16752
16753 case PlainValue$4.Type.FLOW_MAP:
16754 case PlainValue$4.Type.MAP:
16755 return PlainValue$4.defaultTags.MAP;
16756
16757 case PlainValue$4.Type.FLOW_SEQ:
16758 case PlainValue$4.Type.SEQ:
16759 return PlainValue$4.defaultTags.SEQ;
16760
16761 case PlainValue$4.Type.PLAIN:
16762 return nonSpecific ? PlainValue$4.defaultTags.STR : null;
16763
16764 default:
16765 return null;
16766 }
16767}
16768
16769function resolveByTagName(doc, node, tagName) {
16770 const {
16771 tags
16772 } = doc.schema;
16773 const matchWithTest = [];
16774
16775 for (const tag of tags) {
16776 if (tag.tag === tagName) {
16777 if (tag.test) matchWithTest.push(tag);else {
16778 const res = tag.resolve(doc, node);
16779 return res instanceof Collection ? res : new Scalar(res);
16780 }
16781 }
16782 }
16783
16784 const str = resolveString(doc, node);
16785 if (typeof str === 'string' && matchWithTest.length > 0) return resolveScalar(str, matchWithTest, tags.scalarFallback);
16786 return null;
16787}
16788
16789function getFallbackTagName({
16790 type
16791}) {
16792 switch (type) {
16793 case PlainValue$4.Type.FLOW_MAP:
16794 case PlainValue$4.Type.MAP:
16795 return PlainValue$4.defaultTags.MAP;
16796
16797 case PlainValue$4.Type.FLOW_SEQ:
16798 case PlainValue$4.Type.SEQ:
16799 return PlainValue$4.defaultTags.SEQ;
16800
16801 default:
16802 return PlainValue$4.defaultTags.STR;
16803 }
16804}
16805
16806function resolveTag(doc, node, tagName) {
16807 try {
16808 const res = resolveByTagName(doc, node, tagName);
16809
16810 if (res) {
16811 if (tagName && node.tag) res.tag = tagName;
16812 return res;
16813 }
16814 } catch (error) {
16815 /* istanbul ignore if */
16816 if (!error.source) error.source = node;
16817 doc.errors.push(error);
16818 return null;
16819 }
16820
16821 try {
16822 const fallback = getFallbackTagName(node);
16823 if (!fallback) throw new Error(`The tag ${tagName} is unavailable`);
16824 const msg = `The tag ${tagName} is unavailable, falling back to ${fallback}`;
16825 doc.warnings.push(new PlainValue$4.YAMLWarning(node, msg));
16826 const res = resolveByTagName(doc, node, fallback);
16827 res.tag = tagName;
16828 return res;
16829 } catch (error) {
16830 const refError = new PlainValue$4.YAMLReferenceError(node, error.message);
16831 refError.stack = error.stack;
16832 doc.errors.push(refError);
16833 return null;
16834 }
16835}
16836
16837const isCollectionItem = node => {
16838 if (!node) return false;
16839 const {
16840 type
16841 } = node;
16842 return type === PlainValue$4.Type.MAP_KEY || type === PlainValue$4.Type.MAP_VALUE || type === PlainValue$4.Type.SEQ_ITEM;
16843};
16844
16845function resolveNodeProps(errors, node) {
16846 const comments = {
16847 before: [],
16848 after: []
16849 };
16850 let hasAnchor = false;
16851 let hasTag = false;
16852 const props = isCollectionItem(node.context.parent) ? node.context.parent.props.concat(node.props) : node.props;
16853
16854 for (const {
16855 start,
16856 end
16857 } of props) {
16858 switch (node.context.src[start]) {
16859 case PlainValue$4.Char.COMMENT:
16860 {
16861 if (!node.commentHasRequiredWhitespace(start)) {
16862 const msg = 'Comments must be separated from other tokens by white space characters';
16863 errors.push(new PlainValue$4.YAMLSemanticError(node, msg));
16864 }
16865
16866 const {
16867 header,
16868 valueRange
16869 } = node;
16870 const cc = valueRange && (start > valueRange.start || header && start > header.start) ? comments.after : comments.before;
16871 cc.push(node.context.src.slice(start + 1, end));
16872 break;
16873 }
16874 // Actual anchor & tag resolution is handled by schema, here we just complain
16875
16876 case PlainValue$4.Char.ANCHOR:
16877 if (hasAnchor) {
16878 const msg = 'A node can have at most one anchor';
16879 errors.push(new PlainValue$4.YAMLSemanticError(node, msg));
16880 }
16881
16882 hasAnchor = true;
16883 break;
16884
16885 case PlainValue$4.Char.TAG:
16886 if (hasTag) {
16887 const msg = 'A node can have at most one tag';
16888 errors.push(new PlainValue$4.YAMLSemanticError(node, msg));
16889 }
16890
16891 hasTag = true;
16892 break;
16893 }
16894 }
16895
16896 return {
16897 comments,
16898 hasAnchor,
16899 hasTag
16900 };
16901}
16902
16903function resolveNodeValue(doc, node) {
16904 const {
16905 anchors,
16906 errors,
16907 schema
16908 } = doc;
16909
16910 if (node.type === PlainValue$4.Type.ALIAS) {
16911 const name = node.rawValue;
16912 const src = anchors.getNode(name);
16913
16914 if (!src) {
16915 const msg = `Aliased anchor not found: ${name}`;
16916 errors.push(new PlainValue$4.YAMLReferenceError(node, msg));
16917 return null;
16918 } // Lazy resolution for circular references
16919
16920
16921 const res = new Alias(src);
16922
16923 anchors._cstAliases.push(res);
16924
16925 return res;
16926 }
16927
16928 const tagName = resolveTagName(doc, node);
16929 if (tagName) return resolveTag(doc, node, tagName);
16930
16931 if (node.type !== PlainValue$4.Type.PLAIN) {
16932 const msg = `Failed to resolve ${node.type} node here`;
16933 errors.push(new PlainValue$4.YAMLSyntaxError(node, msg));
16934 return null;
16935 }
16936
16937 try {
16938 const str = resolveString(doc, node);
16939 return resolveScalar(str, schema.tags, schema.tags.scalarFallback);
16940 } catch (error) {
16941 if (!error.source) error.source = node;
16942 errors.push(error);
16943 return null;
16944 }
16945} // sets node.resolved on success
16946
16947
16948function resolveNode(doc, node) {
16949 if (!node) return null;
16950 if (node.error) doc.errors.push(node.error);
16951 const {
16952 comments,
16953 hasAnchor,
16954 hasTag
16955 } = resolveNodeProps(doc.errors, node);
16956
16957 if (hasAnchor) {
16958 const {
16959 anchors
16960 } = doc;
16961 const name = node.anchor;
16962 const prev = anchors.getNode(name); // At this point, aliases for any preceding node with the same anchor
16963 // name have already been resolved, so it may safely be renamed.
16964
16965 if (prev) anchors.map[anchors.newName(name)] = prev; // During parsing, we need to store the CST node in anchors.map as
16966 // anchors need to be available during resolution to allow for
16967 // circular references.
16968
16969 anchors.map[name] = node;
16970 }
16971
16972 if (node.type === PlainValue$4.Type.ALIAS && (hasAnchor || hasTag)) {
16973 const msg = 'An alias node must not specify any properties';
16974 doc.errors.push(new PlainValue$4.YAMLSemanticError(node, msg));
16975 }
16976
16977 const res = resolveNodeValue(doc, node);
16978
16979 if (res) {
16980 res.range = [node.range.start, node.range.end];
16981 if (doc.options.keepCstNodes) res.cstNode = node;
16982 if (doc.options.keepNodeTypes) res.type = node.type;
16983 const cb = comments.before.join('\n');
16984
16985 if (cb) {
16986 res.commentBefore = res.commentBefore ? `${res.commentBefore}\n${cb}` : cb;
16987 }
16988
16989 const ca = comments.after.join('\n');
16990 if (ca) res.comment = res.comment ? `${res.comment}\n${ca}` : ca;
16991 }
16992
16993 return node.resolved = res;
16994}
16995
16996function resolveMap(doc, cst) {
16997 if (cst.type !== PlainValue$4.Type.MAP && cst.type !== PlainValue$4.Type.FLOW_MAP) {
16998 const msg = `A ${cst.type} node cannot be resolved as a mapping`;
16999 doc.errors.push(new PlainValue$4.YAMLSyntaxError(cst, msg));
17000 return null;
17001 }
17002
17003 const {
17004 comments,
17005 items
17006 } = cst.type === PlainValue$4.Type.FLOW_MAP ? resolveFlowMapItems(doc, cst) : resolveBlockMapItems(doc, cst);
17007 const map = new YAMLMap();
17008 map.items = items;
17009 resolveComments(map, comments);
17010 let hasCollectionKey = false;
17011
17012 for (let i = 0; i < items.length; ++i) {
17013 const {
17014 key: iKey
17015 } = items[i];
17016 if (iKey instanceof Collection) hasCollectionKey = true;
17017
17018 if (doc.schema.merge && iKey && iKey.value === MERGE_KEY) {
17019 items[i] = new Merge(items[i]);
17020 const sources = items[i].value.items;
17021 let error = null;
17022 sources.some(node => {
17023 if (node instanceof Alias) {
17024 // During parsing, alias sources are CST nodes; to account for
17025 // circular references their resolved values can't be used here.
17026 const {
17027 type
17028 } = node.source;
17029 if (type === PlainValue$4.Type.MAP || type === PlainValue$4.Type.FLOW_MAP) return false;
17030 return error = 'Merge nodes aliases can only point to maps';
17031 }
17032
17033 return error = 'Merge nodes can only have Alias nodes as values';
17034 });
17035 if (error) doc.errors.push(new PlainValue$4.YAMLSemanticError(cst, error));
17036 } else {
17037 for (let j = i + 1; j < items.length; ++j) {
17038 const {
17039 key: jKey
17040 } = items[j];
17041
17042 if (iKey === jKey || iKey && jKey && Object.prototype.hasOwnProperty.call(iKey, 'value') && iKey.value === jKey.value) {
17043 const msg = `Map keys must be unique; "${iKey}" is repeated`;
17044 doc.errors.push(new PlainValue$4.YAMLSemanticError(cst, msg));
17045 break;
17046 }
17047 }
17048 }
17049 }
17050
17051 if (hasCollectionKey && !doc.options.mapAsMap) {
17052 const warn = 'Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.';
17053 doc.warnings.push(new PlainValue$4.YAMLWarning(cst, warn));
17054 }
17055
17056 cst.resolved = map;
17057 return map;
17058}
17059
17060const valueHasPairComment = ({
17061 context: {
17062 lineStart,
17063 node,
17064 src
17065 },
17066 props
17067}) => {
17068 if (props.length === 0) return false;
17069 const {
17070 start
17071 } = props[0];
17072 if (node && start > node.valueRange.start) return false;
17073 if (src[start] !== PlainValue$4.Char.COMMENT) return false;
17074
17075 for (let i = lineStart; i < start; ++i) if (src[i] === '\n') return false;
17076
17077 return true;
17078};
17079
17080function resolvePairComment(item, pair) {
17081 if (!valueHasPairComment(item)) return;
17082 const comment = item.getPropValue(0, PlainValue$4.Char.COMMENT, true);
17083 let found = false;
17084 const cb = pair.value.commentBefore;
17085
17086 if (cb && cb.startsWith(comment)) {
17087 pair.value.commentBefore = cb.substr(comment.length + 1);
17088 found = true;
17089 } else {
17090 const cc = pair.value.comment;
17091
17092 if (!item.node && cc && cc.startsWith(comment)) {
17093 pair.value.comment = cc.substr(comment.length + 1);
17094 found = true;
17095 }
17096 }
17097
17098 if (found) pair.comment = comment;
17099}
17100
17101function resolveBlockMapItems(doc, cst) {
17102 const comments = [];
17103 const items = [];
17104 let key = undefined;
17105 let keyStart = null;
17106
17107 for (let i = 0; i < cst.items.length; ++i) {
17108 const item = cst.items[i];
17109
17110 switch (item.type) {
17111 case PlainValue$4.Type.BLANK_LINE:
17112 comments.push({
17113 afterKey: !!key,
17114 before: items.length
17115 });
17116 break;
17117
17118 case PlainValue$4.Type.COMMENT:
17119 comments.push({
17120 afterKey: !!key,
17121 before: items.length,
17122 comment: item.comment
17123 });
17124 break;
17125
17126 case PlainValue$4.Type.MAP_KEY:
17127 if (key !== undefined) items.push(new Pair(key));
17128 if (item.error) doc.errors.push(item.error);
17129 key = resolveNode(doc, item.node);
17130 keyStart = null;
17131 break;
17132
17133 case PlainValue$4.Type.MAP_VALUE:
17134 {
17135 if (key === undefined) key = null;
17136 if (item.error) doc.errors.push(item.error);
17137
17138 if (!item.context.atLineStart && item.node && item.node.type === PlainValue$4.Type.MAP && !item.node.context.atLineStart) {
17139 const msg = 'Nested mappings are not allowed in compact mappings';
17140 doc.errors.push(new PlainValue$4.YAMLSemanticError(item.node, msg));
17141 }
17142
17143 let valueNode = item.node;
17144
17145 if (!valueNode && item.props.length > 0) {
17146 // Comments on an empty mapping value need to be preserved, so we
17147 // need to construct a minimal empty node here to use instead of the
17148 // missing `item.node`. -- eemeli/yaml#19
17149 valueNode = new PlainValue$4.PlainValue(PlainValue$4.Type.PLAIN, []);
17150 valueNode.context = {
17151 parent: item,
17152 src: item.context.src
17153 };
17154 const pos = item.range.start + 1;
17155 valueNode.range = {
17156 start: pos,
17157 end: pos
17158 };
17159 valueNode.valueRange = {
17160 start: pos,
17161 end: pos
17162 };
17163
17164 if (typeof item.range.origStart === 'number') {
17165 const origPos = item.range.origStart + 1;
17166 valueNode.range.origStart = valueNode.range.origEnd = origPos;
17167 valueNode.valueRange.origStart = valueNode.valueRange.origEnd = origPos;
17168 }
17169 }
17170
17171 const pair = new Pair(key, resolveNode(doc, valueNode));
17172 resolvePairComment(item, pair);
17173 items.push(pair);
17174
17175 if (key && typeof keyStart === 'number') {
17176 if (item.range.start > keyStart + 1024) doc.errors.push(getLongKeyError(cst, key));
17177 }
17178
17179 key = undefined;
17180 keyStart = null;
17181 }
17182 break;
17183
17184 default:
17185 if (key !== undefined) items.push(new Pair(key));
17186 key = resolveNode(doc, item);
17187 keyStart = item.range.start;
17188 if (item.error) doc.errors.push(item.error);
17189
17190 next: for (let j = i + 1;; ++j) {
17191 const nextItem = cst.items[j];
17192
17193 switch (nextItem && nextItem.type) {
17194 case PlainValue$4.Type.BLANK_LINE:
17195 case PlainValue$4.Type.COMMENT:
17196 continue next;
17197
17198 case PlainValue$4.Type.MAP_VALUE:
17199 break next;
17200
17201 default:
17202 {
17203 const msg = 'Implicit map keys need to be followed by map values';
17204 doc.errors.push(new PlainValue$4.YAMLSemanticError(item, msg));
17205 break next;
17206 }
17207 }
17208 }
17209
17210 if (item.valueRangeContainsNewline) {
17211 const msg = 'Implicit map keys need to be on a single line';
17212 doc.errors.push(new PlainValue$4.YAMLSemanticError(item, msg));
17213 }
17214
17215 }
17216 }
17217
17218 if (key !== undefined) items.push(new Pair(key));
17219 return {
17220 comments,
17221 items
17222 };
17223}
17224
17225function resolveFlowMapItems(doc, cst) {
17226 const comments = [];
17227 const items = [];
17228 let key = undefined;
17229 let explicitKey = false;
17230 let next = '{';
17231
17232 for (let i = 0; i < cst.items.length; ++i) {
17233 const item = cst.items[i];
17234
17235 if (typeof item.char === 'string') {
17236 const {
17237 char,
17238 offset
17239 } = item;
17240
17241 if (char === '?' && key === undefined && !explicitKey) {
17242 explicitKey = true;
17243 next = ':';
17244 continue;
17245 }
17246
17247 if (char === ':') {
17248 if (key === undefined) key = null;
17249
17250 if (next === ':') {
17251 next = ',';
17252 continue;
17253 }
17254 } else {
17255 if (explicitKey) {
17256 if (key === undefined && char !== ',') key = null;
17257 explicitKey = false;
17258 }
17259
17260 if (key !== undefined) {
17261 items.push(new Pair(key));
17262 key = undefined;
17263
17264 if (char === ',') {
17265 next = ':';
17266 continue;
17267 }
17268 }
17269 }
17270
17271 if (char === '}') {
17272 if (i === cst.items.length - 1) continue;
17273 } else if (char === next) {
17274 next = ':';
17275 continue;
17276 }
17277
17278 const msg = `Flow map contains an unexpected ${char}`;
17279 const err = new PlainValue$4.YAMLSyntaxError(cst, msg);
17280 err.offset = offset;
17281 doc.errors.push(err);
17282 } else if (item.type === PlainValue$4.Type.BLANK_LINE) {
17283 comments.push({
17284 afterKey: !!key,
17285 before: items.length
17286 });
17287 } else if (item.type === PlainValue$4.Type.COMMENT) {
17288 checkFlowCommentSpace(doc.errors, item);
17289 comments.push({
17290 afterKey: !!key,
17291 before: items.length,
17292 comment: item.comment
17293 });
17294 } else if (key === undefined) {
17295 if (next === ',') doc.errors.push(new PlainValue$4.YAMLSemanticError(item, 'Separator , missing in flow map'));
17296 key = resolveNode(doc, item);
17297 } else {
17298 if (next !== ',') doc.errors.push(new PlainValue$4.YAMLSemanticError(item, 'Indicator : missing in flow map entry'));
17299 items.push(new Pair(key, resolveNode(doc, item)));
17300 key = undefined;
17301 explicitKey = false;
17302 }
17303 }
17304
17305 checkFlowCollectionEnd(doc.errors, cst);
17306 if (key !== undefined) items.push(new Pair(key));
17307 return {
17308 comments,
17309 items
17310 };
17311}
17312
17313function resolveSeq$3(doc, cst) {
17314 if (cst.type !== PlainValue$4.Type.SEQ && cst.type !== PlainValue$4.Type.FLOW_SEQ) {
17315 const msg = `A ${cst.type} node cannot be resolved as a sequence`;
17316 doc.errors.push(new PlainValue$4.YAMLSyntaxError(cst, msg));
17317 return null;
17318 }
17319
17320 const {
17321 comments,
17322 items
17323 } = cst.type === PlainValue$4.Type.FLOW_SEQ ? resolveFlowSeqItems(doc, cst) : resolveBlockSeqItems(doc, cst);
17324 const seq = new YAMLSeq();
17325 seq.items = items;
17326 resolveComments(seq, comments);
17327
17328 if (!doc.options.mapAsMap && items.some(it => it instanceof Pair && it.key instanceof Collection)) {
17329 const warn = 'Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.';
17330 doc.warnings.push(new PlainValue$4.YAMLWarning(cst, warn));
17331 }
17332
17333 cst.resolved = seq;
17334 return seq;
17335}
17336
17337function resolveBlockSeqItems(doc, cst) {
17338 const comments = [];
17339 const items = [];
17340
17341 for (let i = 0; i < cst.items.length; ++i) {
17342 const item = cst.items[i];
17343
17344 switch (item.type) {
17345 case PlainValue$4.Type.BLANK_LINE:
17346 comments.push({
17347 before: items.length
17348 });
17349 break;
17350
17351 case PlainValue$4.Type.COMMENT:
17352 comments.push({
17353 comment: item.comment,
17354 before: items.length
17355 });
17356 break;
17357
17358 case PlainValue$4.Type.SEQ_ITEM:
17359 if (item.error) doc.errors.push(item.error);
17360 items.push(resolveNode(doc, item.node));
17361
17362 if (item.hasProps) {
17363 const msg = 'Sequence items cannot have tags or anchors before the - indicator';
17364 doc.errors.push(new PlainValue$4.YAMLSemanticError(item, msg));
17365 }
17366
17367 break;
17368
17369 default:
17370 if (item.error) doc.errors.push(item.error);
17371 doc.errors.push(new PlainValue$4.YAMLSyntaxError(item, `Unexpected ${item.type} node in sequence`));
17372 }
17373 }
17374
17375 return {
17376 comments,
17377 items
17378 };
17379}
17380
17381function resolveFlowSeqItems(doc, cst) {
17382 const comments = [];
17383 const items = [];
17384 let explicitKey = false;
17385 let key = undefined;
17386 let keyStart = null;
17387 let next = '[';
17388 let prevItem = null;
17389
17390 for (let i = 0; i < cst.items.length; ++i) {
17391 const item = cst.items[i];
17392
17393 if (typeof item.char === 'string') {
17394 const {
17395 char,
17396 offset
17397 } = item;
17398
17399 if (char !== ':' && (explicitKey || key !== undefined)) {
17400 if (explicitKey && key === undefined) key = next ? items.pop() : null;
17401 items.push(new Pair(key));
17402 explicitKey = false;
17403 key = undefined;
17404 keyStart = null;
17405 }
17406
17407 if (char === next) {
17408 next = null;
17409 } else if (!next && char === '?') {
17410 explicitKey = true;
17411 } else if (next !== '[' && char === ':' && key === undefined) {
17412 if (next === ',') {
17413 key = items.pop();
17414
17415 if (key instanceof Pair) {
17416 const msg = 'Chaining flow sequence pairs is invalid';
17417 const err = new PlainValue$4.YAMLSemanticError(cst, msg);
17418 err.offset = offset;
17419 doc.errors.push(err);
17420 }
17421
17422 if (!explicitKey && typeof keyStart === 'number') {
17423 const keyEnd = item.range ? item.range.start : item.offset;
17424 if (keyEnd > keyStart + 1024) doc.errors.push(getLongKeyError(cst, key));
17425 const {
17426 src
17427 } = prevItem.context;
17428
17429 for (let i = keyStart; i < keyEnd; ++i) if (src[i] === '\n') {
17430 const msg = 'Implicit keys of flow sequence pairs need to be on a single line';
17431 doc.errors.push(new PlainValue$4.YAMLSemanticError(prevItem, msg));
17432 break;
17433 }
17434 }
17435 } else {
17436 key = null;
17437 }
17438
17439 keyStart = null;
17440 explicitKey = false;
17441 next = null;
17442 } else if (next === '[' || char !== ']' || i < cst.items.length - 1) {
17443 const msg = `Flow sequence contains an unexpected ${char}`;
17444 const err = new PlainValue$4.YAMLSyntaxError(cst, msg);
17445 err.offset = offset;
17446 doc.errors.push(err);
17447 }
17448 } else if (item.type === PlainValue$4.Type.BLANK_LINE) {
17449 comments.push({
17450 before: items.length
17451 });
17452 } else if (item.type === PlainValue$4.Type.COMMENT) {
17453 checkFlowCommentSpace(doc.errors, item);
17454 comments.push({
17455 comment: item.comment,
17456 before: items.length
17457 });
17458 } else {
17459 if (next) {
17460 const msg = `Expected a ${next} in flow sequence`;
17461 doc.errors.push(new PlainValue$4.YAMLSemanticError(item, msg));
17462 }
17463
17464 const value = resolveNode(doc, item);
17465
17466 if (key === undefined) {
17467 items.push(value);
17468 prevItem = item;
17469 } else {
17470 items.push(new Pair(key, value));
17471 key = undefined;
17472 }
17473
17474 keyStart = item.range.start;
17475 next = ',';
17476 }
17477 }
17478
17479 checkFlowCollectionEnd(doc.errors, cst);
17480 if (key !== undefined) items.push(new Pair(key));
17481 return {
17482 comments,
17483 items
17484 };
17485}
17486
17487resolveSeqD03cb037.Alias = Alias;
17488resolveSeqD03cb037.Collection = Collection;
17489resolveSeqD03cb037.Merge = Merge;
17490resolveSeqD03cb037.Node = Node$1;
17491resolveSeqD03cb037.Pair = Pair;
17492resolveSeqD03cb037.Scalar = Scalar;
17493resolveSeqD03cb037.YAMLMap = YAMLMap;
17494resolveSeqD03cb037.YAMLSeq = YAMLSeq;
17495resolveSeqD03cb037.addComment = addComment;
17496resolveSeqD03cb037.binaryOptions = binaryOptions;
17497resolveSeqD03cb037.boolOptions = boolOptions;
17498resolveSeqD03cb037.findPair = findPair;
17499resolveSeqD03cb037.intOptions = intOptions;
17500resolveSeqD03cb037.isEmptyPath = isEmptyPath;
17501resolveSeqD03cb037.nullOptions = nullOptions;
17502resolveSeqD03cb037.resolveMap = resolveMap;
17503resolveSeqD03cb037.resolveNode = resolveNode;
17504resolveSeqD03cb037.resolveSeq = resolveSeq$3;
17505resolveSeqD03cb037.resolveString = resolveString;
17506resolveSeqD03cb037.strOptions = strOptions;
17507resolveSeqD03cb037.stringifyNumber = stringifyNumber;
17508resolveSeqD03cb037.stringifyString = stringifyString;
17509resolveSeqD03cb037.toJSON = toJSON;
17510
17511var Schema88e323a7 = {};
17512
17513var warnings1000a372 = {};
17514
17515var PlainValue$3 = PlainValueEc8e588e;
17516var resolveSeq$2 = resolveSeqD03cb037;
17517
17518/* global atob, btoa, Buffer */
17519const binary = {
17520 identify: value => value instanceof Uint8Array,
17521 // Buffer inherits from Uint8Array
17522 default: false,
17523 tag: 'tag:yaml.org,2002:binary',
17524
17525 /**
17526 * Returns a Buffer in node and an Uint8Array in browsers
17527 *
17528 * To use the resulting buffer as an image, you'll want to do something like:
17529 *
17530 * const blob = new Blob([buffer], { type: 'image/jpeg' })
17531 * document.querySelector('#photo').src = URL.createObjectURL(blob)
17532 */
17533 resolve: (doc, node) => {
17534 const src = resolveSeq$2.resolveString(doc, node);
17535
17536 if (typeof Buffer === 'function') {
17537 return Buffer.from(src, 'base64');
17538 } else if (typeof atob === 'function') {
17539 // On IE 11, atob() can't handle newlines
17540 const str = atob(src.replace(/[\n\r]/g, ''));
17541 const buffer = new Uint8Array(str.length);
17542
17543 for (let i = 0; i < str.length; ++i) buffer[i] = str.charCodeAt(i);
17544
17545 return buffer;
17546 } else {
17547 const msg = 'This environment does not support reading binary tags; either Buffer or atob is required';
17548 doc.errors.push(new PlainValue$3.YAMLReferenceError(node, msg));
17549 return null;
17550 }
17551 },
17552 options: resolveSeq$2.binaryOptions,
17553 stringify: ({
17554 comment,
17555 type,
17556 value
17557 }, ctx, onComment, onChompKeep) => {
17558 let src;
17559
17560 if (typeof Buffer === 'function') {
17561 src = value instanceof Buffer ? value.toString('base64') : Buffer.from(value.buffer).toString('base64');
17562 } else if (typeof btoa === 'function') {
17563 let s = '';
17564
17565 for (let i = 0; i < value.length; ++i) s += String.fromCharCode(value[i]);
17566
17567 src = btoa(s);
17568 } else {
17569 throw new Error('This environment does not support writing binary tags; either Buffer or btoa is required');
17570 }
17571
17572 if (!type) type = resolveSeq$2.binaryOptions.defaultType;
17573
17574 if (type === PlainValue$3.Type.QUOTE_DOUBLE) {
17575 value = src;
17576 } else {
17577 const {
17578 lineWidth
17579 } = resolveSeq$2.binaryOptions;
17580 const n = Math.ceil(src.length / lineWidth);
17581 const lines = new Array(n);
17582
17583 for (let i = 0, o = 0; i < n; ++i, o += lineWidth) {
17584 lines[i] = src.substr(o, lineWidth);
17585 }
17586
17587 value = lines.join(type === PlainValue$3.Type.BLOCK_LITERAL ? '\n' : ' ');
17588 }
17589
17590 return resolveSeq$2.stringifyString({
17591 comment,
17592 type,
17593 value
17594 }, ctx, onComment, onChompKeep);
17595 }
17596};
17597
17598function parsePairs(doc, cst) {
17599 const seq = resolveSeq$2.resolveSeq(doc, cst);
17600
17601 for (let i = 0; i < seq.items.length; ++i) {
17602 let item = seq.items[i];
17603 if (item instanceof resolveSeq$2.Pair) continue;else if (item instanceof resolveSeq$2.YAMLMap) {
17604 if (item.items.length > 1) {
17605 const msg = 'Each pair must have its own sequence indicator';
17606 throw new PlainValue$3.YAMLSemanticError(cst, msg);
17607 }
17608
17609 const pair = item.items[0] || new resolveSeq$2.Pair();
17610 if (item.commentBefore) pair.commentBefore = pair.commentBefore ? `${item.commentBefore}\n${pair.commentBefore}` : item.commentBefore;
17611 if (item.comment) pair.comment = pair.comment ? `${item.comment}\n${pair.comment}` : item.comment;
17612 item = pair;
17613 }
17614 seq.items[i] = item instanceof resolveSeq$2.Pair ? item : new resolveSeq$2.Pair(item);
17615 }
17616
17617 return seq;
17618}
17619function createPairs(schema, iterable, ctx) {
17620 const pairs = new resolveSeq$2.YAMLSeq(schema);
17621 pairs.tag = 'tag:yaml.org,2002:pairs';
17622
17623 for (const it of iterable) {
17624 let key, value;
17625
17626 if (Array.isArray(it)) {
17627 if (it.length === 2) {
17628 key = it[0];
17629 value = it[1];
17630 } else throw new TypeError(`Expected [key, value] tuple: ${it}`);
17631 } else if (it && it instanceof Object) {
17632 const keys = Object.keys(it);
17633
17634 if (keys.length === 1) {
17635 key = keys[0];
17636 value = it[key];
17637 } else throw new TypeError(`Expected { key: value } tuple: ${it}`);
17638 } else {
17639 key = it;
17640 }
17641
17642 const pair = schema.createPair(key, value, ctx);
17643 pairs.items.push(pair);
17644 }
17645
17646 return pairs;
17647}
17648const pairs = {
17649 default: false,
17650 tag: 'tag:yaml.org,2002:pairs',
17651 resolve: parsePairs,
17652 createNode: createPairs
17653};
17654
17655class YAMLOMap extends resolveSeq$2.YAMLSeq {
17656 constructor() {
17657 super();
17658
17659 PlainValue$3._defineProperty(this, "add", resolveSeq$2.YAMLMap.prototype.add.bind(this));
17660
17661 PlainValue$3._defineProperty(this, "delete", resolveSeq$2.YAMLMap.prototype.delete.bind(this));
17662
17663 PlainValue$3._defineProperty(this, "get", resolveSeq$2.YAMLMap.prototype.get.bind(this));
17664
17665 PlainValue$3._defineProperty(this, "has", resolveSeq$2.YAMLMap.prototype.has.bind(this));
17666
17667 PlainValue$3._defineProperty(this, "set", resolveSeq$2.YAMLMap.prototype.set.bind(this));
17668
17669 this.tag = YAMLOMap.tag;
17670 }
17671
17672 toJSON(_, ctx) {
17673 const map = new Map();
17674 if (ctx && ctx.onCreate) ctx.onCreate(map);
17675
17676 for (const pair of this.items) {
17677 let key, value;
17678
17679 if (pair instanceof resolveSeq$2.Pair) {
17680 key = resolveSeq$2.toJSON(pair.key, '', ctx);
17681 value = resolveSeq$2.toJSON(pair.value, key, ctx);
17682 } else {
17683 key = resolveSeq$2.toJSON(pair, '', ctx);
17684 }
17685
17686 if (map.has(key)) throw new Error('Ordered maps must not include duplicate keys');
17687 map.set(key, value);
17688 }
17689
17690 return map;
17691 }
17692
17693}
17694
17695PlainValue$3._defineProperty(YAMLOMap, "tag", 'tag:yaml.org,2002:omap');
17696
17697function parseOMap(doc, cst) {
17698 const pairs = parsePairs(doc, cst);
17699 const seenKeys = [];
17700
17701 for (const {
17702 key
17703 } of pairs.items) {
17704 if (key instanceof resolveSeq$2.Scalar) {
17705 if (seenKeys.includes(key.value)) {
17706 const msg = 'Ordered maps must not include duplicate keys';
17707 throw new PlainValue$3.YAMLSemanticError(cst, msg);
17708 } else {
17709 seenKeys.push(key.value);
17710 }
17711 }
17712 }
17713
17714 return Object.assign(new YAMLOMap(), pairs);
17715}
17716
17717function createOMap(schema, iterable, ctx) {
17718 const pairs = createPairs(schema, iterable, ctx);
17719 const omap = new YAMLOMap();
17720 omap.items = pairs.items;
17721 return omap;
17722}
17723
17724const omap = {
17725 identify: value => value instanceof Map,
17726 nodeClass: YAMLOMap,
17727 default: false,
17728 tag: 'tag:yaml.org,2002:omap',
17729 resolve: parseOMap,
17730 createNode: createOMap
17731};
17732
17733class YAMLSet extends resolveSeq$2.YAMLMap {
17734 constructor() {
17735 super();
17736 this.tag = YAMLSet.tag;
17737 }
17738
17739 add(key) {
17740 const pair = key instanceof resolveSeq$2.Pair ? key : new resolveSeq$2.Pair(key);
17741 const prev = resolveSeq$2.findPair(this.items, pair.key);
17742 if (!prev) this.items.push(pair);
17743 }
17744
17745 get(key, keepPair) {
17746 const pair = resolveSeq$2.findPair(this.items, key);
17747 return !keepPair && pair instanceof resolveSeq$2.Pair ? pair.key instanceof resolveSeq$2.Scalar ? pair.key.value : pair.key : pair;
17748 }
17749
17750 set(key, value) {
17751 if (typeof value !== 'boolean') throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`);
17752 const prev = resolveSeq$2.findPair(this.items, key);
17753
17754 if (prev && !value) {
17755 this.items.splice(this.items.indexOf(prev), 1);
17756 } else if (!prev && value) {
17757 this.items.push(new resolveSeq$2.Pair(key));
17758 }
17759 }
17760
17761 toJSON(_, ctx) {
17762 return super.toJSON(_, ctx, Set);
17763 }
17764
17765 toString(ctx, onComment, onChompKeep) {
17766 if (!ctx) return JSON.stringify(this);
17767 if (this.hasAllNullValues()) return super.toString(ctx, onComment, onChompKeep);else throw new Error('Set items must all have null values');
17768 }
17769
17770}
17771
17772PlainValue$3._defineProperty(YAMLSet, "tag", 'tag:yaml.org,2002:set');
17773
17774function parseSet(doc, cst) {
17775 const map = resolveSeq$2.resolveMap(doc, cst);
17776 if (!map.hasAllNullValues()) throw new PlainValue$3.YAMLSemanticError(cst, 'Set items must all have null values');
17777 return Object.assign(new YAMLSet(), map);
17778}
17779
17780function createSet(schema, iterable, ctx) {
17781 const set = new YAMLSet();
17782
17783 for (const value of iterable) set.items.push(schema.createPair(value, null, ctx));
17784
17785 return set;
17786}
17787
17788const set = {
17789 identify: value => value instanceof Set,
17790 nodeClass: YAMLSet,
17791 default: false,
17792 tag: 'tag:yaml.org,2002:set',
17793 resolve: parseSet,
17794 createNode: createSet
17795};
17796
17797const parseSexagesimal = (sign, parts) => {
17798 const n = parts.split(':').reduce((n, p) => n * 60 + Number(p), 0);
17799 return sign === '-' ? -n : n;
17800}; // hhhh:mm:ss.sss
17801
17802
17803const stringifySexagesimal = ({
17804 value
17805}) => {
17806 if (isNaN(value) || !isFinite(value)) return resolveSeq$2.stringifyNumber(value);
17807 let sign = '';
17808
17809 if (value < 0) {
17810 sign = '-';
17811 value = Math.abs(value);
17812 }
17813
17814 const parts = [value % 60]; // seconds, including ms
17815
17816 if (value < 60) {
17817 parts.unshift(0); // at least one : is required
17818 } else {
17819 value = Math.round((value - parts[0]) / 60);
17820 parts.unshift(value % 60); // minutes
17821
17822 if (value >= 60) {
17823 value = Math.round((value - parts[0]) / 60);
17824 parts.unshift(value); // hours
17825 }
17826 }
17827
17828 return sign + parts.map(n => n < 10 ? '0' + String(n) : String(n)).join(':').replace(/000000\d*$/, '') // % 60 may introduce error
17829 ;
17830};
17831
17832const intTime = {
17833 identify: value => typeof value === 'number',
17834 default: true,
17835 tag: 'tag:yaml.org,2002:int',
17836 format: 'TIME',
17837 test: /^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+)$/,
17838 resolve: (str, sign, parts) => parseSexagesimal(sign, parts.replace(/_/g, '')),
17839 stringify: stringifySexagesimal
17840};
17841const floatTime = {
17842 identify: value => typeof value === 'number',
17843 default: true,
17844 tag: 'tag:yaml.org,2002:float',
17845 format: 'TIME',
17846 test: /^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*)$/,
17847 resolve: (str, sign, parts) => parseSexagesimal(sign, parts.replace(/_/g, '')),
17848 stringify: stringifySexagesimal
17849};
17850const timestamp = {
17851 identify: value => value instanceof Date,
17852 default: true,
17853 tag: 'tag:yaml.org,2002:timestamp',
17854 // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part
17855 // may be omitted altogether, resulting in a date format. In such a case, the time part is
17856 // assumed to be 00:00:00Z (start of day, UTC).
17857 test: RegExp('^(?:' + '([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})' + // YYYY-Mm-Dd
17858 '(?:(?:t|T|[ \\t]+)' + // t | T | whitespace
17859 '([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)' + // Hh:Mm:Ss(.ss)?
17860 '(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?' + // Z | +5 | -03:30
17861 ')?' + ')$'),
17862 resolve: (str, year, month, day, hour, minute, second, millisec, tz) => {
17863 if (millisec) millisec = (millisec + '00').substr(1, 3);
17864 let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec || 0);
17865
17866 if (tz && tz !== 'Z') {
17867 let d = parseSexagesimal(tz[0], tz.slice(1));
17868 if (Math.abs(d) < 30) d *= 60;
17869 date -= 60000 * d;
17870 }
17871
17872 return new Date(date);
17873 },
17874 stringify: ({
17875 value
17876 }) => value.toISOString().replace(/((T00:00)?:00)?\.000Z$/, '')
17877};
17878
17879/* global console, process, YAML_SILENCE_DEPRECATION_WARNINGS, YAML_SILENCE_WARNINGS */
17880function shouldWarn(deprecation) {
17881 const env = typeof process !== 'undefined' && process.env || {};
17882
17883 if (deprecation) {
17884 if (typeof YAML_SILENCE_DEPRECATION_WARNINGS !== 'undefined') return !YAML_SILENCE_DEPRECATION_WARNINGS;
17885 return !env.YAML_SILENCE_DEPRECATION_WARNINGS;
17886 }
17887
17888 if (typeof YAML_SILENCE_WARNINGS !== 'undefined') return !YAML_SILENCE_WARNINGS;
17889 return !env.YAML_SILENCE_WARNINGS;
17890}
17891
17892function warn(warning, type) {
17893 if (shouldWarn(false)) {
17894 const emit = typeof process !== 'undefined' && process.emitWarning; // This will throw in Jest if `warning` is an Error instance due to
17895 // https://github.com/facebook/jest/issues/2549
17896
17897 if (emit) emit(warning, type);else {
17898 // eslint-disable-next-line no-console
17899 console.warn(type ? `${type}: ${warning}` : warning);
17900 }
17901 }
17902}
17903function warnFileDeprecation(filename) {
17904 if (shouldWarn(true)) {
17905 const path = filename.replace(/.*yaml[/\\]/i, '').replace(/\.js$/, '').replace(/\\/g, '/');
17906 warn(`The endpoint 'yaml/${path}' will be removed in a future release.`, 'DeprecationWarning');
17907 }
17908}
17909const warned = {};
17910function warnOptionDeprecation(name, alternative) {
17911 if (!warned[name] && shouldWarn(true)) {
17912 warned[name] = true;
17913 let msg = `The option '${name}' will be removed in a future release`;
17914 msg += alternative ? `, use '${alternative}' instead.` : '.';
17915 warn(msg, 'DeprecationWarning');
17916 }
17917}
17918
17919warnings1000a372.binary = binary;
17920warnings1000a372.floatTime = floatTime;
17921warnings1000a372.intTime = intTime;
17922warnings1000a372.omap = omap;
17923warnings1000a372.pairs = pairs;
17924warnings1000a372.set = set;
17925warnings1000a372.timestamp = timestamp;
17926warnings1000a372.warn = warn;
17927warnings1000a372.warnFileDeprecation = warnFileDeprecation;
17928warnings1000a372.warnOptionDeprecation = warnOptionDeprecation;
17929
17930var PlainValue$2 = PlainValueEc8e588e;
17931var resolveSeq$1 = resolveSeqD03cb037;
17932var warnings$1 = warnings1000a372;
17933
17934function createMap(schema, obj, ctx) {
17935 const map = new resolveSeq$1.YAMLMap(schema);
17936
17937 if (obj instanceof Map) {
17938 for (const [key, value] of obj) map.items.push(schema.createPair(key, value, ctx));
17939 } else if (obj && typeof obj === 'object') {
17940 for (const key of Object.keys(obj)) map.items.push(schema.createPair(key, obj[key], ctx));
17941 }
17942
17943 if (typeof schema.sortMapEntries === 'function') {
17944 map.items.sort(schema.sortMapEntries);
17945 }
17946
17947 return map;
17948}
17949
17950const map = {
17951 createNode: createMap,
17952 default: true,
17953 nodeClass: resolveSeq$1.YAMLMap,
17954 tag: 'tag:yaml.org,2002:map',
17955 resolve: resolveSeq$1.resolveMap
17956};
17957
17958function createSeq(schema, obj, ctx) {
17959 const seq = new resolveSeq$1.YAMLSeq(schema);
17960
17961 if (obj && obj[Symbol.iterator]) {
17962 for (const it of obj) {
17963 const v = schema.createNode(it, ctx.wrapScalars, null, ctx);
17964 seq.items.push(v);
17965 }
17966 }
17967
17968 return seq;
17969}
17970
17971const seq = {
17972 createNode: createSeq,
17973 default: true,
17974 nodeClass: resolveSeq$1.YAMLSeq,
17975 tag: 'tag:yaml.org,2002:seq',
17976 resolve: resolveSeq$1.resolveSeq
17977};
17978
17979const string$2 = {
17980 identify: value => typeof value === 'string',
17981 default: true,
17982 tag: 'tag:yaml.org,2002:str',
17983 resolve: resolveSeq$1.resolveString,
17984
17985 stringify(item, ctx, onComment, onChompKeep) {
17986 ctx = Object.assign({
17987 actualString: true
17988 }, ctx);
17989 return resolveSeq$1.stringifyString(item, ctx, onComment, onChompKeep);
17990 },
17991
17992 options: resolveSeq$1.strOptions
17993};
17994
17995const failsafe = [map, seq, string$2];
17996
17997/* global BigInt */
17998
17999const intIdentify$2 = value => typeof value === 'bigint' || Number.isInteger(value);
18000
18001const intResolve$1 = (src, part, radix) => resolveSeq$1.intOptions.asBigInt ? BigInt(src) : parseInt(part, radix);
18002
18003function intStringify$1(node, radix, prefix) {
18004 const {
18005 value
18006 } = node;
18007 if (intIdentify$2(value) && value >= 0) return prefix + value.toString(radix);
18008 return resolveSeq$1.stringifyNumber(node);
18009}
18010
18011const nullObj = {
18012 identify: value => value == null,
18013 createNode: (schema, value, ctx) => ctx.wrapScalars ? new resolveSeq$1.Scalar(null) : null,
18014 default: true,
18015 tag: 'tag:yaml.org,2002:null',
18016 test: /^(?:~|[Nn]ull|NULL)?$/,
18017 resolve: () => null,
18018 options: resolveSeq$1.nullOptions,
18019 stringify: () => resolveSeq$1.nullOptions.nullStr
18020};
18021const boolObj = {
18022 identify: value => typeof value === 'boolean',
18023 default: true,
18024 tag: 'tag:yaml.org,2002:bool',
18025 test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,
18026 resolve: str => str[0] === 't' || str[0] === 'T',
18027 options: resolveSeq$1.boolOptions,
18028 stringify: ({
18029 value
18030 }) => value ? resolveSeq$1.boolOptions.trueStr : resolveSeq$1.boolOptions.falseStr
18031};
18032const octObj = {
18033 identify: value => intIdentify$2(value) && value >= 0,
18034 default: true,
18035 tag: 'tag:yaml.org,2002:int',
18036 format: 'OCT',
18037 test: /^0o([0-7]+)$/,
18038 resolve: (str, oct) => intResolve$1(str, oct, 8),
18039 options: resolveSeq$1.intOptions,
18040 stringify: node => intStringify$1(node, 8, '0o')
18041};
18042const intObj = {
18043 identify: intIdentify$2,
18044 default: true,
18045 tag: 'tag:yaml.org,2002:int',
18046 test: /^[-+]?[0-9]+$/,
18047 resolve: str => intResolve$1(str, str, 10),
18048 options: resolveSeq$1.intOptions,
18049 stringify: resolveSeq$1.stringifyNumber
18050};
18051const hexObj = {
18052 identify: value => intIdentify$2(value) && value >= 0,
18053 default: true,
18054 tag: 'tag:yaml.org,2002:int',
18055 format: 'HEX',
18056 test: /^0x([0-9a-fA-F]+)$/,
18057 resolve: (str, hex) => intResolve$1(str, hex, 16),
18058 options: resolveSeq$1.intOptions,
18059 stringify: node => intStringify$1(node, 16, '0x')
18060};
18061const nanObj = {
18062 identify: value => typeof value === 'number',
18063 default: true,
18064 tag: 'tag:yaml.org,2002:float',
18065 test: /^(?:[-+]?\.inf|(\.nan))$/i,
18066 resolve: (str, nan) => nan ? NaN : str[0] === '-' ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
18067 stringify: resolveSeq$1.stringifyNumber
18068};
18069const expObj = {
18070 identify: value => typeof value === 'number',
18071 default: true,
18072 tag: 'tag:yaml.org,2002:float',
18073 format: 'EXP',
18074 test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,
18075 resolve: str => parseFloat(str),
18076 stringify: ({
18077 value
18078 }) => Number(value).toExponential()
18079};
18080const floatObj = {
18081 identify: value => typeof value === 'number',
18082 default: true,
18083 tag: 'tag:yaml.org,2002:float',
18084 test: /^[-+]?(?:\.([0-9]+)|[0-9]+\.([0-9]*))$/,
18085
18086 resolve(str, frac1, frac2) {
18087 const frac = frac1 || frac2;
18088 const node = new resolveSeq$1.Scalar(parseFloat(str));
18089 if (frac && frac[frac.length - 1] === '0') node.minFractionDigits = frac.length;
18090 return node;
18091 },
18092
18093 stringify: resolveSeq$1.stringifyNumber
18094};
18095const core$2 = failsafe.concat([nullObj, boolObj, octObj, intObj, hexObj, nanObj, expObj, floatObj]);
18096
18097/* global BigInt */
18098
18099const intIdentify$1 = value => typeof value === 'bigint' || Number.isInteger(value);
18100
18101const stringifyJSON = ({
18102 value
18103}) => JSON.stringify(value);
18104
18105const json = [map, seq, {
18106 identify: value => typeof value === 'string',
18107 default: true,
18108 tag: 'tag:yaml.org,2002:str',
18109 resolve: resolveSeq$1.resolveString,
18110 stringify: stringifyJSON
18111}, {
18112 identify: value => value == null,
18113 createNode: (schema, value, ctx) => ctx.wrapScalars ? new resolveSeq$1.Scalar(null) : null,
18114 default: true,
18115 tag: 'tag:yaml.org,2002:null',
18116 test: /^null$/,
18117 resolve: () => null,
18118 stringify: stringifyJSON
18119}, {
18120 identify: value => typeof value === 'boolean',
18121 default: true,
18122 tag: 'tag:yaml.org,2002:bool',
18123 test: /^true|false$/,
18124 resolve: str => str === 'true',
18125 stringify: stringifyJSON
18126}, {
18127 identify: intIdentify$1,
18128 default: true,
18129 tag: 'tag:yaml.org,2002:int',
18130 test: /^-?(?:0|[1-9][0-9]*)$/,
18131 resolve: str => resolveSeq$1.intOptions.asBigInt ? BigInt(str) : parseInt(str, 10),
18132 stringify: ({
18133 value
18134 }) => intIdentify$1(value) ? value.toString() : JSON.stringify(value)
18135}, {
18136 identify: value => typeof value === 'number',
18137 default: true,
18138 tag: 'tag:yaml.org,2002:float',
18139 test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,
18140 resolve: str => parseFloat(str),
18141 stringify: stringifyJSON
18142}];
18143
18144json.scalarFallback = str => {
18145 throw new SyntaxError(`Unresolved plain scalar ${JSON.stringify(str)}`);
18146};
18147
18148/* global BigInt */
18149
18150const boolStringify = ({
18151 value
18152}) => value ? resolveSeq$1.boolOptions.trueStr : resolveSeq$1.boolOptions.falseStr;
18153
18154const intIdentify = value => typeof value === 'bigint' || Number.isInteger(value);
18155
18156function intResolve(sign, src, radix) {
18157 let str = src.replace(/_/g, '');
18158
18159 if (resolveSeq$1.intOptions.asBigInt) {
18160 switch (radix) {
18161 case 2:
18162 str = `0b${str}`;
18163 break;
18164
18165 case 8:
18166 str = `0o${str}`;
18167 break;
18168
18169 case 16:
18170 str = `0x${str}`;
18171 break;
18172 }
18173
18174 const n = BigInt(str);
18175 return sign === '-' ? BigInt(-1) * n : n;
18176 }
18177
18178 const n = parseInt(str, radix);
18179 return sign === '-' ? -1 * n : n;
18180}
18181
18182function intStringify(node, radix, prefix) {
18183 const {
18184 value
18185 } = node;
18186
18187 if (intIdentify(value)) {
18188 const str = value.toString(radix);
18189 return value < 0 ? '-' + prefix + str.substr(1) : prefix + str;
18190 }
18191
18192 return resolveSeq$1.stringifyNumber(node);
18193}
18194
18195const yaml11 = failsafe.concat([{
18196 identify: value => value == null,
18197 createNode: (schema, value, ctx) => ctx.wrapScalars ? new resolveSeq$1.Scalar(null) : null,
18198 default: true,
18199 tag: 'tag:yaml.org,2002:null',
18200 test: /^(?:~|[Nn]ull|NULL)?$/,
18201 resolve: () => null,
18202 options: resolveSeq$1.nullOptions,
18203 stringify: () => resolveSeq$1.nullOptions.nullStr
18204}, {
18205 identify: value => typeof value === 'boolean',
18206 default: true,
18207 tag: 'tag:yaml.org,2002:bool',
18208 test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,
18209 resolve: () => true,
18210 options: resolveSeq$1.boolOptions,
18211 stringify: boolStringify
18212}, {
18213 identify: value => typeof value === 'boolean',
18214 default: true,
18215 tag: 'tag:yaml.org,2002:bool',
18216 test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/i,
18217 resolve: () => false,
18218 options: resolveSeq$1.boolOptions,
18219 stringify: boolStringify
18220}, {
18221 identify: intIdentify,
18222 default: true,
18223 tag: 'tag:yaml.org,2002:int',
18224 format: 'BIN',
18225 test: /^([-+]?)0b([0-1_]+)$/,
18226 resolve: (str, sign, bin) => intResolve(sign, bin, 2),
18227 stringify: node => intStringify(node, 2, '0b')
18228}, {
18229 identify: intIdentify,
18230 default: true,
18231 tag: 'tag:yaml.org,2002:int',
18232 format: 'OCT',
18233 test: /^([-+]?)0([0-7_]+)$/,
18234 resolve: (str, sign, oct) => intResolve(sign, oct, 8),
18235 stringify: node => intStringify(node, 8, '0')
18236}, {
18237 identify: intIdentify,
18238 default: true,
18239 tag: 'tag:yaml.org,2002:int',
18240 test: /^([-+]?)([0-9][0-9_]*)$/,
18241 resolve: (str, sign, abs) => intResolve(sign, abs, 10),
18242 stringify: resolveSeq$1.stringifyNumber
18243}, {
18244 identify: intIdentify,
18245 default: true,
18246 tag: 'tag:yaml.org,2002:int',
18247 format: 'HEX',
18248 test: /^([-+]?)0x([0-9a-fA-F_]+)$/,
18249 resolve: (str, sign, hex) => intResolve(sign, hex, 16),
18250 stringify: node => intStringify(node, 16, '0x')
18251}, {
18252 identify: value => typeof value === 'number',
18253 default: true,
18254 tag: 'tag:yaml.org,2002:float',
18255 test: /^(?:[-+]?\.inf|(\.nan))$/i,
18256 resolve: (str, nan) => nan ? NaN : str[0] === '-' ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
18257 stringify: resolveSeq$1.stringifyNumber
18258}, {
18259 identify: value => typeof value === 'number',
18260 default: true,
18261 tag: 'tag:yaml.org,2002:float',
18262 format: 'EXP',
18263 test: /^[-+]?([0-9][0-9_]*)?(\.[0-9_]*)?[eE][-+]?[0-9]+$/,
18264 resolve: str => parseFloat(str.replace(/_/g, '')),
18265 stringify: ({
18266 value
18267 }) => Number(value).toExponential()
18268}, {
18269 identify: value => typeof value === 'number',
18270 default: true,
18271 tag: 'tag:yaml.org,2002:float',
18272 test: /^[-+]?(?:[0-9][0-9_]*)?\.([0-9_]*)$/,
18273
18274 resolve(str, frac) {
18275 const node = new resolveSeq$1.Scalar(parseFloat(str.replace(/_/g, '')));
18276
18277 if (frac) {
18278 const f = frac.replace(/_/g, '');
18279 if (f[f.length - 1] === '0') node.minFractionDigits = f.length;
18280 }
18281
18282 return node;
18283 },
18284
18285 stringify: resolveSeq$1.stringifyNumber
18286}], warnings$1.binary, warnings$1.omap, warnings$1.pairs, warnings$1.set, warnings$1.intTime, warnings$1.floatTime, warnings$1.timestamp);
18287
18288const schemas = {
18289 core: core$2,
18290 failsafe,
18291 json,
18292 yaml11
18293};
18294const tags = {
18295 binary: warnings$1.binary,
18296 bool: boolObj,
18297 float: floatObj,
18298 floatExp: expObj,
18299 floatNaN: nanObj,
18300 floatTime: warnings$1.floatTime,
18301 int: intObj,
18302 intHex: hexObj,
18303 intOct: octObj,
18304 intTime: warnings$1.intTime,
18305 map,
18306 null: nullObj,
18307 omap: warnings$1.omap,
18308 pairs: warnings$1.pairs,
18309 seq,
18310 set: warnings$1.set,
18311 timestamp: warnings$1.timestamp
18312};
18313
18314function findTagObject(value, tagName, tags) {
18315 if (tagName) {
18316 const match = tags.filter(t => t.tag === tagName);
18317 const tagObj = match.find(t => !t.format) || match[0];
18318 if (!tagObj) throw new Error(`Tag ${tagName} not found`);
18319 return tagObj;
18320 } // TODO: deprecate/remove class check
18321
18322
18323 return tags.find(t => (t.identify && t.identify(value) || t.class && value instanceof t.class) && !t.format);
18324}
18325
18326function createNode$1(value, tagName, ctx) {
18327 if (value instanceof resolveSeq$1.Node) return value;
18328 const {
18329 defaultPrefix,
18330 onTagObj,
18331 prevObjects,
18332 schema,
18333 wrapScalars
18334 } = ctx;
18335 if (tagName && tagName.startsWith('!!')) tagName = defaultPrefix + tagName.slice(2);
18336 let tagObj = findTagObject(value, tagName, schema.tags);
18337
18338 if (!tagObj) {
18339 if (typeof value.toJSON === 'function') value = value.toJSON();
18340 if (!value || typeof value !== 'object') return wrapScalars ? new resolveSeq$1.Scalar(value) : value;
18341 tagObj = value instanceof Map ? map : value[Symbol.iterator] ? seq : map;
18342 }
18343
18344 if (onTagObj) {
18345 onTagObj(tagObj);
18346 delete ctx.onTagObj;
18347 } // Detect duplicate references to the same object & use Alias nodes for all
18348 // after first. The `obj` wrapper allows for circular references to resolve.
18349
18350
18351 const obj = {
18352 value: undefined,
18353 node: undefined
18354 };
18355
18356 if (value && typeof value === 'object' && prevObjects) {
18357 const prev = prevObjects.get(value);
18358
18359 if (prev) {
18360 const alias = new resolveSeq$1.Alias(prev); // leaves source dirty; must be cleaned by caller
18361
18362 ctx.aliasNodes.push(alias); // defined along with prevObjects
18363
18364 return alias;
18365 }
18366
18367 obj.value = value;
18368 prevObjects.set(value, obj);
18369 }
18370
18371 obj.node = tagObj.createNode ? tagObj.createNode(ctx.schema, value, ctx) : wrapScalars ? new resolveSeq$1.Scalar(value) : value;
18372 if (tagName && obj.node instanceof resolveSeq$1.Node) obj.node.tag = tagName;
18373 return obj.node;
18374}
18375
18376function getSchemaTags(schemas, knownTags, customTags, schemaId) {
18377 let tags = schemas[schemaId.replace(/\W/g, '')]; // 'yaml-1.1' -> 'yaml11'
18378
18379 if (!tags) {
18380 const keys = Object.keys(schemas).map(key => JSON.stringify(key)).join(', ');
18381 throw new Error(`Unknown schema "${schemaId}"; use one of ${keys}`);
18382 }
18383
18384 if (Array.isArray(customTags)) {
18385 for (const tag of customTags) tags = tags.concat(tag);
18386 } else if (typeof customTags === 'function') {
18387 tags = customTags(tags.slice());
18388 }
18389
18390 for (let i = 0; i < tags.length; ++i) {
18391 const tag = tags[i];
18392
18393 if (typeof tag === 'string') {
18394 const tagObj = knownTags[tag];
18395
18396 if (!tagObj) {
18397 const keys = Object.keys(knownTags).map(key => JSON.stringify(key)).join(', ');
18398 throw new Error(`Unknown custom tag "${tag}"; use one of ${keys}`);
18399 }
18400
18401 tags[i] = tagObj;
18402 }
18403 }
18404
18405 return tags;
18406}
18407
18408const sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0;
18409
18410class Schema$2 {
18411 // TODO: remove in v2
18412 // TODO: remove in v2
18413 constructor({
18414 customTags,
18415 merge,
18416 schema,
18417 sortMapEntries,
18418 tags: deprecatedCustomTags
18419 }) {
18420 this.merge = !!merge;
18421 this.name = schema;
18422 this.sortMapEntries = sortMapEntries === true ? sortMapEntriesByKey : sortMapEntries || null;
18423 if (!customTags && deprecatedCustomTags) warnings$1.warnOptionDeprecation('tags', 'customTags');
18424 this.tags = getSchemaTags(schemas, tags, customTags || deprecatedCustomTags, schema);
18425 }
18426
18427 createNode(value, wrapScalars, tagName, ctx) {
18428 const baseCtx = {
18429 defaultPrefix: Schema$2.defaultPrefix,
18430 schema: this,
18431 wrapScalars
18432 };
18433 const createCtx = ctx ? Object.assign(ctx, baseCtx) : baseCtx;
18434 return createNode$1(value, tagName, createCtx);
18435 }
18436
18437 createPair(key, value, ctx) {
18438 if (!ctx) ctx = {
18439 wrapScalars: true
18440 };
18441 const k = this.createNode(key, ctx.wrapScalars, null, ctx);
18442 const v = this.createNode(value, ctx.wrapScalars, null, ctx);
18443 return new resolveSeq$1.Pair(k, v);
18444 }
18445
18446}
18447
18448PlainValue$2._defineProperty(Schema$2, "defaultPrefix", PlainValue$2.defaultTagPrefix);
18449
18450PlainValue$2._defineProperty(Schema$2, "defaultTags", PlainValue$2.defaultTags);
18451
18452Schema88e323a7.Schema = Schema$2;
18453
18454var PlainValue$1 = PlainValueEc8e588e;
18455var resolveSeq = resolveSeqD03cb037;
18456var Schema$1 = Schema88e323a7;
18457
18458const defaultOptions$1 = {
18459 anchorPrefix: 'a',
18460 customTags: null,
18461 indent: 2,
18462 indentSeq: true,
18463 keepCstNodes: false,
18464 keepNodeTypes: true,
18465 keepBlobsInJSON: true,
18466 mapAsMap: false,
18467 maxAliasCount: 100,
18468 prettyErrors: false,
18469 // TODO Set true in v2
18470 simpleKeys: false,
18471 version: '1.2'
18472};
18473const scalarOptions = {
18474 get binary() {
18475 return resolveSeq.binaryOptions;
18476 },
18477
18478 set binary(opt) {
18479 Object.assign(resolveSeq.binaryOptions, opt);
18480 },
18481
18482 get bool() {
18483 return resolveSeq.boolOptions;
18484 },
18485
18486 set bool(opt) {
18487 Object.assign(resolveSeq.boolOptions, opt);
18488 },
18489
18490 get int() {
18491 return resolveSeq.intOptions;
18492 },
18493
18494 set int(opt) {
18495 Object.assign(resolveSeq.intOptions, opt);
18496 },
18497
18498 get null() {
18499 return resolveSeq.nullOptions;
18500 },
18501
18502 set null(opt) {
18503 Object.assign(resolveSeq.nullOptions, opt);
18504 },
18505
18506 get str() {
18507 return resolveSeq.strOptions;
18508 },
18509
18510 set str(opt) {
18511 Object.assign(resolveSeq.strOptions, opt);
18512 }
18513
18514};
18515const documentOptions = {
18516 '1.0': {
18517 schema: 'yaml-1.1',
18518 merge: true,
18519 tagPrefixes: [{
18520 handle: '!',
18521 prefix: PlainValue$1.defaultTagPrefix
18522 }, {
18523 handle: '!!',
18524 prefix: 'tag:private.yaml.org,2002:'
18525 }]
18526 },
18527 1.1: {
18528 schema: 'yaml-1.1',
18529 merge: true,
18530 tagPrefixes: [{
18531 handle: '!',
18532 prefix: '!'
18533 }, {
18534 handle: '!!',
18535 prefix: PlainValue$1.defaultTagPrefix
18536 }]
18537 },
18538 1.2: {
18539 schema: 'core',
18540 merge: false,
18541 tagPrefixes: [{
18542 handle: '!',
18543 prefix: '!'
18544 }, {
18545 handle: '!!',
18546 prefix: PlainValue$1.defaultTagPrefix
18547 }]
18548 }
18549};
18550
18551function stringifyTag(doc, tag) {
18552 if ((doc.version || doc.options.version) === '1.0') {
18553 const priv = tag.match(/^tag:private\.yaml\.org,2002:([^:/]+)$/);
18554 if (priv) return '!' + priv[1];
18555 const vocab = tag.match(/^tag:([a-zA-Z0-9-]+)\.yaml\.org,2002:(.*)/);
18556 return vocab ? `!${vocab[1]}/${vocab[2]}` : `!${tag.replace(/^tag:/, '')}`;
18557 }
18558
18559 let p = doc.tagPrefixes.find(p => tag.indexOf(p.prefix) === 0);
18560
18561 if (!p) {
18562 const dtp = doc.getDefaults().tagPrefixes;
18563 p = dtp && dtp.find(p => tag.indexOf(p.prefix) === 0);
18564 }
18565
18566 if (!p) return tag[0] === '!' ? tag : `!<${tag}>`;
18567 const suffix = tag.substr(p.prefix.length).replace(/[!,[\]{}]/g, ch => ({
18568 '!': '%21',
18569 ',': '%2C',
18570 '[': '%5B',
18571 ']': '%5D',
18572 '{': '%7B',
18573 '}': '%7D'
18574 })[ch]);
18575 return p.handle + suffix;
18576}
18577
18578function getTagObject(tags, item) {
18579 if (item instanceof resolveSeq.Alias) return resolveSeq.Alias;
18580
18581 if (item.tag) {
18582 const match = tags.filter(t => t.tag === item.tag);
18583 if (match.length > 0) return match.find(t => t.format === item.format) || match[0];
18584 }
18585
18586 let tagObj, obj;
18587
18588 if (item instanceof resolveSeq.Scalar) {
18589 obj = item.value; // TODO: deprecate/remove class check
18590
18591 const match = tags.filter(t => t.identify && t.identify(obj) || t.class && obj instanceof t.class);
18592 tagObj = match.find(t => t.format === item.format) || match.find(t => !t.format);
18593 } else {
18594 obj = item;
18595 tagObj = tags.find(t => t.nodeClass && obj instanceof t.nodeClass);
18596 }
18597
18598 if (!tagObj) {
18599 const name = obj && obj.constructor ? obj.constructor.name : typeof obj;
18600 throw new Error(`Tag not resolved for ${name} value`);
18601 }
18602
18603 return tagObj;
18604} // needs to be called before value stringifier to allow for circular anchor refs
18605
18606
18607function stringifyProps(node, tagObj, {
18608 anchors,
18609 doc
18610}) {
18611 const props = [];
18612 const anchor = doc.anchors.getName(node);
18613
18614 if (anchor) {
18615 anchors[anchor] = node;
18616 props.push(`&${anchor}`);
18617 }
18618
18619 if (node.tag) {
18620 props.push(stringifyTag(doc, node.tag));
18621 } else if (!tagObj.default) {
18622 props.push(stringifyTag(doc, tagObj.tag));
18623 }
18624
18625 return props.join(' ');
18626}
18627
18628function stringify$2(item, ctx, onComment, onChompKeep) {
18629 const {
18630 anchors,
18631 schema
18632 } = ctx.doc;
18633 let tagObj;
18634
18635 if (!(item instanceof resolveSeq.Node)) {
18636 const createCtx = {
18637 aliasNodes: [],
18638 onTagObj: o => tagObj = o,
18639 prevObjects: new Map()
18640 };
18641 item = schema.createNode(item, true, null, createCtx);
18642
18643 for (const alias of createCtx.aliasNodes) {
18644 alias.source = alias.source.node;
18645 let name = anchors.getName(alias.source);
18646
18647 if (!name) {
18648 name = anchors.newName();
18649 anchors.map[name] = alias.source;
18650 }
18651 }
18652 }
18653
18654 if (item instanceof resolveSeq.Pair) return item.toString(ctx, onComment, onChompKeep);
18655 if (!tagObj) tagObj = getTagObject(schema.tags, item);
18656 const props = stringifyProps(item, tagObj, ctx);
18657 if (props.length > 0) ctx.indentAtStart = (ctx.indentAtStart || 0) + props.length + 1;
18658 const str = typeof tagObj.stringify === 'function' ? tagObj.stringify(item, ctx, onComment, onChompKeep) : item instanceof resolveSeq.Scalar ? resolveSeq.stringifyString(item, ctx, onComment, onChompKeep) : item.toString(ctx, onComment, onChompKeep);
18659 if (!props) return str;
18660 return item instanceof resolveSeq.Scalar || str[0] === '{' || str[0] === '[' ? `${props} ${str}` : `${props}\n${ctx.indent}${str}`;
18661}
18662
18663class Anchors {
18664 static validAnchorNode(node) {
18665 return node instanceof resolveSeq.Scalar || node instanceof resolveSeq.YAMLSeq || node instanceof resolveSeq.YAMLMap;
18666 }
18667
18668 constructor(prefix) {
18669 PlainValue$1._defineProperty(this, "map", Object.create(null));
18670
18671 this.prefix = prefix;
18672 }
18673
18674 createAlias(node, name) {
18675 this.setAnchor(node, name);
18676 return new resolveSeq.Alias(node);
18677 }
18678
18679 createMergePair(...sources) {
18680 const merge = new resolveSeq.Merge();
18681 merge.value.items = sources.map(s => {
18682 if (s instanceof resolveSeq.Alias) {
18683 if (s.source instanceof resolveSeq.YAMLMap) return s;
18684 } else if (s instanceof resolveSeq.YAMLMap) {
18685 return this.createAlias(s);
18686 }
18687
18688 throw new Error('Merge sources must be Map nodes or their Aliases');
18689 });
18690 return merge;
18691 }
18692
18693 getName(node) {
18694 const {
18695 map
18696 } = this;
18697 return Object.keys(map).find(a => map[a] === node);
18698 }
18699
18700 getNames() {
18701 return Object.keys(this.map);
18702 }
18703
18704 getNode(name) {
18705 return this.map[name];
18706 }
18707
18708 newName(prefix) {
18709 if (!prefix) prefix = this.prefix;
18710 const names = Object.keys(this.map);
18711
18712 for (let i = 1; true; ++i) {
18713 const name = `${prefix}${i}`;
18714 if (!names.includes(name)) return name;
18715 }
18716 } // During parsing, map & aliases contain CST nodes
18717
18718
18719 resolveNodes() {
18720 const {
18721 map,
18722 _cstAliases
18723 } = this;
18724 Object.keys(map).forEach(a => {
18725 map[a] = map[a].resolved;
18726 });
18727
18728 _cstAliases.forEach(a => {
18729 a.source = a.source.resolved;
18730 });
18731
18732 delete this._cstAliases;
18733 }
18734
18735 setAnchor(node, name) {
18736 if (node != null && !Anchors.validAnchorNode(node)) {
18737 throw new Error('Anchors may only be set for Scalar, Seq and Map nodes');
18738 }
18739
18740 if (name && /[\x00-\x19\s,[\]{}]/.test(name)) {
18741 throw new Error('Anchor names must not contain whitespace or control characters');
18742 }
18743
18744 const {
18745 map
18746 } = this;
18747 const prev = node && Object.keys(map).find(a => map[a] === node);
18748
18749 if (prev) {
18750 if (!name) {
18751 return prev;
18752 } else if (prev !== name) {
18753 delete map[prev];
18754 map[name] = node;
18755 }
18756 } else {
18757 if (!name) {
18758 if (!node) return null;
18759 name = this.newName();
18760 }
18761
18762 map[name] = node;
18763 }
18764
18765 return name;
18766 }
18767
18768}
18769
18770const visit$1 = (node, tags) => {
18771 if (node && typeof node === 'object') {
18772 const {
18773 tag
18774 } = node;
18775
18776 if (node instanceof resolveSeq.Collection) {
18777 if (tag) tags[tag] = true;
18778 node.items.forEach(n => visit$1(n, tags));
18779 } else if (node instanceof resolveSeq.Pair) {
18780 visit$1(node.key, tags);
18781 visit$1(node.value, tags);
18782 } else if (node instanceof resolveSeq.Scalar) {
18783 if (tag) tags[tag] = true;
18784 }
18785 }
18786
18787 return tags;
18788};
18789
18790const listTagNames = node => Object.keys(visit$1(node, {}));
18791
18792function parseContents(doc, contents) {
18793 const comments = {
18794 before: [],
18795 after: []
18796 };
18797 let body = undefined;
18798 let spaceBefore = false;
18799
18800 for (const node of contents) {
18801 if (node.valueRange) {
18802 if (body !== undefined) {
18803 const msg = 'Document contains trailing content not separated by a ... or --- line';
18804 doc.errors.push(new PlainValue$1.YAMLSyntaxError(node, msg));
18805 break;
18806 }
18807
18808 const res = resolveSeq.resolveNode(doc, node);
18809
18810 if (spaceBefore) {
18811 res.spaceBefore = true;
18812 spaceBefore = false;
18813 }
18814
18815 body = res;
18816 } else if (node.comment !== null) {
18817 const cc = body === undefined ? comments.before : comments.after;
18818 cc.push(node.comment);
18819 } else if (node.type === PlainValue$1.Type.BLANK_LINE) {
18820 spaceBefore = true;
18821
18822 if (body === undefined && comments.before.length > 0 && !doc.commentBefore) {
18823 // space-separated comments at start are parsed as document comments
18824 doc.commentBefore = comments.before.join('\n');
18825 comments.before = [];
18826 }
18827 }
18828 }
18829
18830 doc.contents = body || null;
18831
18832 if (!body) {
18833 doc.comment = comments.before.concat(comments.after).join('\n') || null;
18834 } else {
18835 const cb = comments.before.join('\n');
18836
18837 if (cb) {
18838 const cbNode = body instanceof resolveSeq.Collection && body.items[0] ? body.items[0] : body;
18839 cbNode.commentBefore = cbNode.commentBefore ? `${cb}\n${cbNode.commentBefore}` : cb;
18840 }
18841
18842 doc.comment = comments.after.join('\n') || null;
18843 }
18844}
18845
18846function resolveTagDirective({
18847 tagPrefixes
18848}, directive) {
18849 const [handle, prefix] = directive.parameters;
18850
18851 if (!handle || !prefix) {
18852 const msg = 'Insufficient parameters given for %TAG directive';
18853 throw new PlainValue$1.YAMLSemanticError(directive, msg);
18854 }
18855
18856 if (tagPrefixes.some(p => p.handle === handle)) {
18857 const msg = 'The %TAG directive must only be given at most once per handle in the same document.';
18858 throw new PlainValue$1.YAMLSemanticError(directive, msg);
18859 }
18860
18861 return {
18862 handle,
18863 prefix
18864 };
18865}
18866
18867function resolveYamlDirective(doc, directive) {
18868 let [version] = directive.parameters;
18869 if (directive.name === 'YAML:1.0') version = '1.0';
18870
18871 if (!version) {
18872 const msg = 'Insufficient parameters given for %YAML directive';
18873 throw new PlainValue$1.YAMLSemanticError(directive, msg);
18874 }
18875
18876 if (!documentOptions[version]) {
18877 const v0 = doc.version || doc.options.version;
18878 const msg = `Document will be parsed as YAML ${v0} rather than YAML ${version}`;
18879 doc.warnings.push(new PlainValue$1.YAMLWarning(directive, msg));
18880 }
18881
18882 return version;
18883}
18884
18885function parseDirectives(doc, directives, prevDoc) {
18886 const directiveComments = [];
18887 let hasDirectives = false;
18888
18889 for (const directive of directives) {
18890 const {
18891 comment,
18892 name
18893 } = directive;
18894
18895 switch (name) {
18896 case 'TAG':
18897 try {
18898 doc.tagPrefixes.push(resolveTagDirective(doc, directive));
18899 } catch (error) {
18900 doc.errors.push(error);
18901 }
18902
18903 hasDirectives = true;
18904 break;
18905
18906 case 'YAML':
18907 case 'YAML:1.0':
18908 if (doc.version) {
18909 const msg = 'The %YAML directive must only be given at most once per document.';
18910 doc.errors.push(new PlainValue$1.YAMLSemanticError(directive, msg));
18911 }
18912
18913 try {
18914 doc.version = resolveYamlDirective(doc, directive);
18915 } catch (error) {
18916 doc.errors.push(error);
18917 }
18918
18919 hasDirectives = true;
18920 break;
18921
18922 default:
18923 if (name) {
18924 const msg = `YAML only supports %TAG and %YAML directives, and not %${name}`;
18925 doc.warnings.push(new PlainValue$1.YAMLWarning(directive, msg));
18926 }
18927
18928 }
18929
18930 if (comment) directiveComments.push(comment);
18931 }
18932
18933 if (prevDoc && !hasDirectives && '1.1' === (doc.version || prevDoc.version || doc.options.version)) {
18934 const copyTagPrefix = ({
18935 handle,
18936 prefix
18937 }) => ({
18938 handle,
18939 prefix
18940 });
18941
18942 doc.tagPrefixes = prevDoc.tagPrefixes.map(copyTagPrefix);
18943 doc.version = prevDoc.version;
18944 }
18945
18946 doc.commentBefore = directiveComments.join('\n') || null;
18947}
18948
18949function assertCollection(contents) {
18950 if (contents instanceof resolveSeq.Collection) return true;
18951 throw new Error('Expected a YAML collection as document contents');
18952}
18953
18954class Document$2 {
18955 constructor(options) {
18956 this.anchors = new Anchors(options.anchorPrefix);
18957 this.commentBefore = null;
18958 this.comment = null;
18959 this.contents = null;
18960 this.directivesEndMarker = null;
18961 this.errors = [];
18962 this.options = options;
18963 this.schema = null;
18964 this.tagPrefixes = [];
18965 this.version = null;
18966 this.warnings = [];
18967 }
18968
18969 add(value) {
18970 assertCollection(this.contents);
18971 return this.contents.add(value);
18972 }
18973
18974 addIn(path, value) {
18975 assertCollection(this.contents);
18976 this.contents.addIn(path, value);
18977 }
18978
18979 delete(key) {
18980 assertCollection(this.contents);
18981 return this.contents.delete(key);
18982 }
18983
18984 deleteIn(path) {
18985 if (resolveSeq.isEmptyPath(path)) {
18986 if (this.contents == null) return false;
18987 this.contents = null;
18988 return true;
18989 }
18990
18991 assertCollection(this.contents);
18992 return this.contents.deleteIn(path);
18993 }
18994
18995 getDefaults() {
18996 return Document$2.defaults[this.version] || Document$2.defaults[this.options.version] || {};
18997 }
18998
18999 get(key, keepScalar) {
19000 return this.contents instanceof resolveSeq.Collection ? this.contents.get(key, keepScalar) : undefined;
19001 }
19002
19003 getIn(path, keepScalar) {
19004 if (resolveSeq.isEmptyPath(path)) return !keepScalar && this.contents instanceof resolveSeq.Scalar ? this.contents.value : this.contents;
19005 return this.contents instanceof resolveSeq.Collection ? this.contents.getIn(path, keepScalar) : undefined;
19006 }
19007
19008 has(key) {
19009 return this.contents instanceof resolveSeq.Collection ? this.contents.has(key) : false;
19010 }
19011
19012 hasIn(path) {
19013 if (resolveSeq.isEmptyPath(path)) return this.contents !== undefined;
19014 return this.contents instanceof resolveSeq.Collection ? this.contents.hasIn(path) : false;
19015 }
19016
19017 set(key, value) {
19018 assertCollection(this.contents);
19019 this.contents.set(key, value);
19020 }
19021
19022 setIn(path, value) {
19023 if (resolveSeq.isEmptyPath(path)) this.contents = value;else {
19024 assertCollection(this.contents);
19025 this.contents.setIn(path, value);
19026 }
19027 }
19028
19029 setSchema(id, customTags) {
19030 if (!id && !customTags && this.schema) return;
19031 if (typeof id === 'number') id = id.toFixed(1);
19032
19033 if (id === '1.0' || id === '1.1' || id === '1.2') {
19034 if (this.version) this.version = id;else this.options.version = id;
19035 delete this.options.schema;
19036 } else if (id && typeof id === 'string') {
19037 this.options.schema = id;
19038 }
19039
19040 if (Array.isArray(customTags)) this.options.customTags = customTags;
19041 const opt = Object.assign({}, this.getDefaults(), this.options);
19042 this.schema = new Schema$1.Schema(opt);
19043 }
19044
19045 parse(node, prevDoc) {
19046 if (this.options.keepCstNodes) this.cstNode = node;
19047 if (this.options.keepNodeTypes) this.type = 'DOCUMENT';
19048 const {
19049 directives = [],
19050 contents = [],
19051 directivesEndMarker,
19052 error,
19053 valueRange
19054 } = node;
19055
19056 if (error) {
19057 if (!error.source) error.source = this;
19058 this.errors.push(error);
19059 }
19060
19061 parseDirectives(this, directives, prevDoc);
19062 if (directivesEndMarker) this.directivesEndMarker = true;
19063 this.range = valueRange ? [valueRange.start, valueRange.end] : null;
19064 this.setSchema();
19065 this.anchors._cstAliases = [];
19066 parseContents(this, contents);
19067 this.anchors.resolveNodes();
19068
19069 if (this.options.prettyErrors) {
19070 for (const error of this.errors) if (error instanceof PlainValue$1.YAMLError) error.makePretty();
19071
19072 for (const warn of this.warnings) if (warn instanceof PlainValue$1.YAMLError) warn.makePretty();
19073 }
19074
19075 return this;
19076 }
19077
19078 listNonDefaultTags() {
19079 return listTagNames(this.contents).filter(t => t.indexOf(Schema$1.Schema.defaultPrefix) !== 0);
19080 }
19081
19082 setTagPrefix(handle, prefix) {
19083 if (handle[0] !== '!' || handle[handle.length - 1] !== '!') throw new Error('Handle must start and end with !');
19084
19085 if (prefix) {
19086 const prev = this.tagPrefixes.find(p => p.handle === handle);
19087 if (prev) prev.prefix = prefix;else this.tagPrefixes.push({
19088 handle,
19089 prefix
19090 });
19091 } else {
19092 this.tagPrefixes = this.tagPrefixes.filter(p => p.handle !== handle);
19093 }
19094 }
19095
19096 toJSON(arg, onAnchor) {
19097 const {
19098 keepBlobsInJSON,
19099 mapAsMap,
19100 maxAliasCount
19101 } = this.options;
19102 const keep = keepBlobsInJSON && (typeof arg !== 'string' || !(this.contents instanceof resolveSeq.Scalar));
19103 const ctx = {
19104 doc: this,
19105 indentStep: ' ',
19106 keep,
19107 mapAsMap: keep && !!mapAsMap,
19108 maxAliasCount,
19109 stringify: stringify$2 // Requiring directly in Pair would create circular dependencies
19110
19111 };
19112 const anchorNames = Object.keys(this.anchors.map);
19113 if (anchorNames.length > 0) ctx.anchors = new Map(anchorNames.map(name => [this.anchors.map[name], {
19114 alias: [],
19115 aliasCount: 0,
19116 count: 1
19117 }]));
19118 const res = resolveSeq.toJSON(this.contents, arg, ctx);
19119 if (typeof onAnchor === 'function' && ctx.anchors) for (const {
19120 count,
19121 res
19122 } of ctx.anchors.values()) onAnchor(res, count);
19123 return res;
19124 }
19125
19126 toString() {
19127 if (this.errors.length > 0) throw new Error('Document with errors cannot be stringified');
19128 const indentSize = this.options.indent;
19129
19130 if (!Number.isInteger(indentSize) || indentSize <= 0) {
19131 const s = JSON.stringify(indentSize);
19132 throw new Error(`"indent" option must be a positive integer, not ${s}`);
19133 }
19134
19135 this.setSchema();
19136 const lines = [];
19137 let hasDirectives = false;
19138
19139 if (this.version) {
19140 let vd = '%YAML 1.2';
19141
19142 if (this.schema.name === 'yaml-1.1') {
19143 if (this.version === '1.0') vd = '%YAML:1.0';else if (this.version === '1.1') vd = '%YAML 1.1';
19144 }
19145
19146 lines.push(vd);
19147 hasDirectives = true;
19148 }
19149
19150 const tagNames = this.listNonDefaultTags();
19151 this.tagPrefixes.forEach(({
19152 handle,
19153 prefix
19154 }) => {
19155 if (tagNames.some(t => t.indexOf(prefix) === 0)) {
19156 lines.push(`%TAG ${handle} ${prefix}`);
19157 hasDirectives = true;
19158 }
19159 });
19160 if (hasDirectives || this.directivesEndMarker) lines.push('---');
19161
19162 if (this.commentBefore) {
19163 if (hasDirectives || !this.directivesEndMarker) lines.unshift('');
19164 lines.unshift(this.commentBefore.replace(/^/gm, '#'));
19165 }
19166
19167 const ctx = {
19168 anchors: Object.create(null),
19169 doc: this,
19170 indent: '',
19171 indentStep: ' '.repeat(indentSize),
19172 stringify: stringify$2 // Requiring directly in nodes would create circular dependencies
19173
19174 };
19175 let chompKeep = false;
19176 let contentComment = null;
19177
19178 if (this.contents) {
19179 if (this.contents instanceof resolveSeq.Node) {
19180 if (this.contents.spaceBefore && (hasDirectives || this.directivesEndMarker)) lines.push('');
19181 if (this.contents.commentBefore) lines.push(this.contents.commentBefore.replace(/^/gm, '#')); // top-level block scalars need to be indented if followed by a comment
19182
19183 ctx.forceBlockIndent = !!this.comment;
19184 contentComment = this.contents.comment;
19185 }
19186
19187 const onChompKeep = contentComment ? null : () => chompKeep = true;
19188 const body = stringify$2(this.contents, ctx, () => contentComment = null, onChompKeep);
19189 lines.push(resolveSeq.addComment(body, '', contentComment));
19190 } else if (this.contents !== undefined) {
19191 lines.push(stringify$2(this.contents, ctx));
19192 }
19193
19194 if (this.comment) {
19195 if ((!chompKeep || contentComment) && lines[lines.length - 1] !== '') lines.push('');
19196 lines.push(this.comment.replace(/^/gm, '#'));
19197 }
19198
19199 return lines.join('\n') + '\n';
19200 }
19201
19202}
19203
19204PlainValue$1._defineProperty(Document$2, "defaults", documentOptions);
19205
19206Document9b4560a1.Document = Document$2;
19207Document9b4560a1.defaultOptions = defaultOptions$1;
19208Document9b4560a1.scalarOptions = scalarOptions;
19209
19210var parseCst = parseCst$1;
19211var Document$1 = Document9b4560a1;
19212var Schema = Schema88e323a7;
19213var PlainValue = PlainValueEc8e588e;
19214var warnings = warnings1000a372;
19215
19216
19217function createNode(value, wrapScalars = true, tag) {
19218 if (tag === undefined && typeof wrapScalars === 'string') {
19219 tag = wrapScalars;
19220 wrapScalars = true;
19221 }
19222
19223 const options = Object.assign({}, Document$1.Document.defaults[Document$1.defaultOptions.version], Document$1.defaultOptions);
19224 const schema = new Schema.Schema(options);
19225 return schema.createNode(value, wrapScalars, tag);
19226}
19227
19228class Document extends Document$1.Document {
19229 constructor(options) {
19230 super(Object.assign({}, Document$1.defaultOptions, options));
19231 }
19232
19233}
19234
19235function parseAllDocuments(src, options) {
19236 const stream = [];
19237 let prev;
19238
19239 for (const cstDoc of parseCst.parse(src)) {
19240 const doc = new Document(options);
19241 doc.parse(cstDoc, prev);
19242 stream.push(doc);
19243 prev = doc;
19244 }
19245
19246 return stream;
19247}
19248
19249function parseDocument(src, options) {
19250 const cst = parseCst.parse(src);
19251 const doc = new Document(options).parse(cst[0]);
19252
19253 if (cst.length > 1) {
19254 const errMsg = 'Source contains multiple documents; please use YAML.parseAllDocuments()';
19255 doc.errors.unshift(new PlainValue.YAMLSemanticError(cst[1], errMsg));
19256 }
19257
19258 return doc;
19259}
19260
19261function parse$g(src, options) {
19262 const doc = parseDocument(src, options);
19263 doc.warnings.forEach(warning => warnings.warn(warning));
19264 if (doc.errors.length > 0) throw doc.errors[0];
19265 return doc.toJSON();
19266}
19267
19268function stringify$1(value, options) {
19269 const doc = new Document(options);
19270 doc.contents = value;
19271 return String(doc);
19272}
19273
19274const YAML = {
19275 createNode,
19276 defaultOptions: Document$1.defaultOptions,
19277 Document,
19278 parse: parse$g,
19279 parseAllDocuments,
19280 parseCST: parseCst.parse,
19281 parseDocument,
19282 scalarOptions: Document$1.scalarOptions,
19283 stringify: stringify$1
19284};
19285
19286dist$2.YAML = YAML;
19287
19288var yaml$1 = dist$2.YAML;
19289
19290var importCwd = {exports: {}};
19291
19292var importFrom$1 = {exports: {}};
19293
19294var resolveFrom$2 = {exports: {}};
19295
19296const path$p = path__default;
19297const Module = require$$0__default$5;
19298const fs$n = fs__default;
19299
19300const resolveFrom$1 = (fromDirectory, moduleId, silent) => {
19301 if (typeof fromDirectory !== 'string') {
19302 throw new TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof fromDirectory}\``);
19303 }
19304
19305 if (typeof moduleId !== 'string') {
19306 throw new TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof moduleId}\``);
19307 }
19308
19309 try {
19310 fromDirectory = fs$n.realpathSync(fromDirectory);
19311 } catch (error) {
19312 if (error.code === 'ENOENT') {
19313 fromDirectory = path$p.resolve(fromDirectory);
19314 } else if (silent) {
19315 return;
19316 } else {
19317 throw error;
19318 }
19319 }
19320
19321 const fromFile = path$p.join(fromDirectory, 'noop.js');
19322
19323 const resolveFileName = () => Module._resolveFilename(moduleId, {
19324 id: fromFile,
19325 filename: fromFile,
19326 paths: Module._nodeModulePaths(fromDirectory)
19327 });
19328
19329 if (silent) {
19330 try {
19331 return resolveFileName();
19332 } catch (error) {
19333 return;
19334 }
19335 }
19336
19337 return resolveFileName();
19338};
19339
19340resolveFrom$2.exports = (fromDirectory, moduleId) => resolveFrom$1(fromDirectory, moduleId);
19341resolveFrom$2.exports.silent = (fromDirectory, moduleId) => resolveFrom$1(fromDirectory, moduleId, true);
19342
19343const resolveFrom = resolveFrom$2.exports;
19344
19345importFrom$1.exports = (fromDirectory, moduleId) => eval('require')(resolveFrom(fromDirectory, moduleId));
19346
19347importFrom$1.exports.silent = (fromDirectory, moduleId) => {
19348 try {
19349 return eval('require')(resolveFrom(fromDirectory, moduleId));
19350 } catch (_) {}
19351};
19352
19353const importFrom = importFrom$1.exports;
19354
19355importCwd.exports = moduleId => importFrom(process.cwd(), moduleId);
19356importCwd.exports.silent = moduleId => importFrom.silent(process.cwd(), moduleId);
19357
19358const req$1 = importCwd.exports;
19359
19360/**
19361 * Load Options
19362 *
19363 * @private
19364 * @method options
19365 *
19366 * @param {Object} config PostCSS Config
19367 *
19368 * @return {Object} options PostCSS Options
19369 */
19370const options = (config, file) => {
19371 if (config.parser && typeof config.parser === 'string') {
19372 try {
19373 config.parser = req$1(config.parser);
19374 } catch (err) {
19375 throw new Error(`Loading PostCSS Parser failed: ${err.message}\n\n(@${file})`)
19376 }
19377 }
19378
19379 if (config.syntax && typeof config.syntax === 'string') {
19380 try {
19381 config.syntax = req$1(config.syntax);
19382 } catch (err) {
19383 throw new Error(`Loading PostCSS Syntax failed: ${err.message}\n\n(@${file})`)
19384 }
19385 }
19386
19387 if (config.stringifier && typeof config.stringifier === 'string') {
19388 try {
19389 config.stringifier = req$1(config.stringifier);
19390 } catch (err) {
19391 throw new Error(`Loading PostCSS Stringifier failed: ${err.message}\n\n(@${file})`)
19392 }
19393 }
19394
19395 if (config.plugins) {
19396 delete config.plugins;
19397 }
19398
19399 return config
19400};
19401
19402var options_1 = options;
19403
19404const req = importCwd.exports;
19405
19406/**
19407 * Plugin Loader
19408 *
19409 * @private
19410 * @method load
19411 *
19412 * @param {String} plugin PostCSS Plugin Name
19413 * @param {Object} options PostCSS Plugin Options
19414 *
19415 * @return {Function} PostCSS Plugin
19416 */
19417const load$1 = (plugin, options, file) => {
19418 try {
19419 if (
19420 options === null ||
19421 options === undefined ||
19422 Object.keys(options).length === 0
19423 ) {
19424 return req(plugin)
19425 } else {
19426 return req(plugin)(options)
19427 }
19428 } catch (err) {
19429 throw new Error(`Loading PostCSS Plugin failed: ${err.message}\n\n(@${file})`)
19430 }
19431};
19432
19433/**
19434 * Load Plugins
19435 *
19436 * @private
19437 * @method plugins
19438 *
19439 * @param {Object} config PostCSS Config Plugins
19440 *
19441 * @return {Array} plugins PostCSS Plugins
19442 */
19443const plugins = (config, file) => {
19444 let plugins = [];
19445
19446 if (Array.isArray(config.plugins)) {
19447 plugins = config.plugins.filter(Boolean);
19448 } else {
19449 plugins = Object.keys(config.plugins)
19450 .filter((plugin) => {
19451 return config.plugins[plugin] !== false ? plugin : ''
19452 })
19453 .map((plugin) => {
19454 return load$1(plugin, config.plugins[plugin], file)
19455 });
19456 }
19457
19458 if (plugins.length && plugins.length > 0) {
19459 plugins.forEach((plugin, i) => {
19460 if (plugin.default) {
19461 plugin = plugin.default;
19462 }
19463
19464 if (plugin.postcss === true) {
19465 plugin = plugin();
19466 } else if (plugin.postcss) {
19467 plugin = plugin.postcss;
19468 }
19469
19470 if (
19471 // eslint-disable-next-line
19472 !(
19473 (typeof plugin === 'object' && Array.isArray(plugin.plugins)) ||
19474 (typeof plugin === 'object' && plugin.postcssPlugin) ||
19475 (typeof plugin === 'function')
19476 )
19477 ) {
19478 throw new TypeError(`Invalid PostCSS Plugin found at: plugins[${i}]\n\n(@${file})`)
19479 }
19480 });
19481 }
19482
19483 return plugins
19484};
19485
19486var plugins_1 = plugins;
19487
19488var dist$1 = {};
19489
19490var sourceMapSupport = {exports: {}};
19491
19492var sourceMap = {};
19493
19494var sourceMapGenerator = {};
19495
19496var base64Vlq = {};
19497
19498var base64$1 = {};
19499
19500/* -*- Mode: js; js-indent-level: 2; -*- */
19501
19502/*
19503 * Copyright 2011 Mozilla Foundation and contributors
19504 * Licensed under the New BSD license. See LICENSE or:
19505 * http://opensource.org/licenses/BSD-3-Clause
19506 */
19507
19508var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
19509
19510/**
19511 * Encode an integer in the range of 0 to 63 to a single base 64 digit.
19512 */
19513base64$1.encode = function (number) {
19514 if (0 <= number && number < intToCharMap.length) {
19515 return intToCharMap[number];
19516 }
19517 throw new TypeError("Must be between 0 and 63: " + number);
19518};
19519
19520/**
19521 * Decode a single base 64 character code digit to an integer. Returns -1 on
19522 * failure.
19523 */
19524base64$1.decode = function (charCode) {
19525 var bigA = 65; // 'A'
19526 var bigZ = 90; // 'Z'
19527
19528 var littleA = 97; // 'a'
19529 var littleZ = 122; // 'z'
19530
19531 var zero = 48; // '0'
19532 var nine = 57; // '9'
19533
19534 var plus = 43; // '+'
19535 var slash = 47; // '/'
19536
19537 var littleOffset = 26;
19538 var numberOffset = 52;
19539
19540 // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
19541 if (bigA <= charCode && charCode <= bigZ) {
19542 return (charCode - bigA);
19543 }
19544
19545 // 26 - 51: abcdefghijklmnopqrstuvwxyz
19546 if (littleA <= charCode && charCode <= littleZ) {
19547 return (charCode - littleA + littleOffset);
19548 }
19549
19550 // 52 - 61: 0123456789
19551 if (zero <= charCode && charCode <= nine) {
19552 return (charCode - zero + numberOffset);
19553 }
19554
19555 // 62: +
19556 if (charCode == plus) {
19557 return 62;
19558 }
19559
19560 // 63: /
19561 if (charCode == slash) {
19562 return 63;
19563 }
19564
19565 // Invalid base64 digit.
19566 return -1;
19567};
19568
19569/* -*- Mode: js; js-indent-level: 2; -*- */
19570
19571/*
19572 * Copyright 2011 Mozilla Foundation and contributors
19573 * Licensed under the New BSD license. See LICENSE or:
19574 * http://opensource.org/licenses/BSD-3-Clause
19575 *
19576 * Based on the Base 64 VLQ implementation in Closure Compiler:
19577 * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
19578 *
19579 * Copyright 2011 The Closure Compiler Authors. All rights reserved.
19580 * Redistribution and use in source and binary forms, with or without
19581 * modification, are permitted provided that the following conditions are
19582 * met:
19583 *
19584 * * Redistributions of source code must retain the above copyright
19585 * notice, this list of conditions and the following disclaimer.
19586 * * Redistributions in binary form must reproduce the above
19587 * copyright notice, this list of conditions and the following
19588 * disclaimer in the documentation and/or other materials provided
19589 * with the distribution.
19590 * * Neither the name of Google Inc. nor the names of its
19591 * contributors may be used to endorse or promote products derived
19592 * from this software without specific prior written permission.
19593 *
19594 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19595 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19596 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19597 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
19598 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
19599 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
19600 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
19601 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
19602 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
19603 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
19604 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
19605 */
19606
19607var base64 = base64$1;
19608
19609// A single base 64 digit can contain 6 bits of data. For the base 64 variable
19610// length quantities we use in the source map spec, the first bit is the sign,
19611// the next four bits are the actual value, and the 6th bit is the
19612// continuation bit. The continuation bit tells us whether there are more
19613// digits in this value following this digit.
19614//
19615// Continuation
19616// | Sign
19617// | |
19618// V V
19619// 101011
19620
19621var VLQ_BASE_SHIFT = 5;
19622
19623// binary: 100000
19624var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
19625
19626// binary: 011111
19627var VLQ_BASE_MASK = VLQ_BASE - 1;
19628
19629// binary: 100000
19630var VLQ_CONTINUATION_BIT = VLQ_BASE;
19631
19632/**
19633 * Converts from a two-complement value to a value where the sign bit is
19634 * placed in the least significant bit. For example, as decimals:
19635 * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
19636 * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
19637 */
19638function toVLQSigned(aValue) {
19639 return aValue < 0
19640 ? ((-aValue) << 1) + 1
19641 : (aValue << 1) + 0;
19642}
19643
19644/**
19645 * Converts to a two-complement value from a value where the sign bit is
19646 * placed in the least significant bit. For example, as decimals:
19647 * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
19648 * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
19649 */
19650function fromVLQSigned(aValue) {
19651 var isNegative = (aValue & 1) === 1;
19652 var shifted = aValue >> 1;
19653 return isNegative
19654 ? -shifted
19655 : shifted;
19656}
19657
19658/**
19659 * Returns the base 64 VLQ encoded value.
19660 */
19661base64Vlq.encode = function base64VLQ_encode(aValue) {
19662 var encoded = "";
19663 var digit;
19664
19665 var vlq = toVLQSigned(aValue);
19666
19667 do {
19668 digit = vlq & VLQ_BASE_MASK;
19669 vlq >>>= VLQ_BASE_SHIFT;
19670 if (vlq > 0) {
19671 // There are still more digits in this value, so we must make sure the
19672 // continuation bit is marked.
19673 digit |= VLQ_CONTINUATION_BIT;
19674 }
19675 encoded += base64.encode(digit);
19676 } while (vlq > 0);
19677
19678 return encoded;
19679};
19680
19681/**
19682 * Decodes the next base 64 VLQ value from the given string and returns the
19683 * value and the rest of the string via the out parameter.
19684 */
19685base64Vlq.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
19686 var strLen = aStr.length;
19687 var result = 0;
19688 var shift = 0;
19689 var continuation, digit;
19690
19691 do {
19692 if (aIndex >= strLen) {
19693 throw new Error("Expected more digits in base 64 VLQ value.");
19694 }
19695
19696 digit = base64.decode(aStr.charCodeAt(aIndex++));
19697 if (digit === -1) {
19698 throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
19699 }
19700
19701 continuation = !!(digit & VLQ_CONTINUATION_BIT);
19702 digit &= VLQ_BASE_MASK;
19703 result = result + (digit << shift);
19704 shift += VLQ_BASE_SHIFT;
19705 } while (continuation);
19706
19707 aOutParam.value = fromVLQSigned(result);
19708 aOutParam.rest = aIndex;
19709};
19710
19711var util$7 = {};
19712
19713/* -*- Mode: js; js-indent-level: 2; -*- */
19714
19715(function (exports) {
19716/*
19717 * Copyright 2011 Mozilla Foundation and contributors
19718 * Licensed under the New BSD license. See LICENSE or:
19719 * http://opensource.org/licenses/BSD-3-Clause
19720 */
19721
19722/**
19723 * This is a helper function for getting values from parameter/options
19724 * objects.
19725 *
19726 * @param args The object we are extracting values from
19727 * @param name The name of the property we are getting.
19728 * @param defaultValue An optional value to return if the property is missing
19729 * from the object. If this is not specified and the property is missing, an
19730 * error will be thrown.
19731 */
19732function getArg(aArgs, aName, aDefaultValue) {
19733 if (aName in aArgs) {
19734 return aArgs[aName];
19735 } else if (arguments.length === 3) {
19736 return aDefaultValue;
19737 } else {
19738 throw new Error('"' + aName + '" is a required argument.');
19739 }
19740}
19741exports.getArg = getArg;
19742
19743var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
19744var dataUrlRegexp = /^data:.+\,.+$/;
19745
19746function urlParse(aUrl) {
19747 var match = aUrl.match(urlRegexp);
19748 if (!match) {
19749 return null;
19750 }
19751 return {
19752 scheme: match[1],
19753 auth: match[2],
19754 host: match[3],
19755 port: match[4],
19756 path: match[5]
19757 };
19758}
19759exports.urlParse = urlParse;
19760
19761function urlGenerate(aParsedUrl) {
19762 var url = '';
19763 if (aParsedUrl.scheme) {
19764 url += aParsedUrl.scheme + ':';
19765 }
19766 url += '//';
19767 if (aParsedUrl.auth) {
19768 url += aParsedUrl.auth + '@';
19769 }
19770 if (aParsedUrl.host) {
19771 url += aParsedUrl.host;
19772 }
19773 if (aParsedUrl.port) {
19774 url += ":" + aParsedUrl.port;
19775 }
19776 if (aParsedUrl.path) {
19777 url += aParsedUrl.path;
19778 }
19779 return url;
19780}
19781exports.urlGenerate = urlGenerate;
19782
19783/**
19784 * Normalizes a path, or the path portion of a URL:
19785 *
19786 * - Replaces consecutive slashes with one slash.
19787 * - Removes unnecessary '.' parts.
19788 * - Removes unnecessary '<dir>/..' parts.
19789 *
19790 * Based on code in the Node.js 'path' core module.
19791 *
19792 * @param aPath The path or url to normalize.
19793 */
19794function normalize(aPath) {
19795 var path = aPath;
19796 var url = urlParse(aPath);
19797 if (url) {
19798 if (!url.path) {
19799 return aPath;
19800 }
19801 path = url.path;
19802 }
19803 var isAbsolute = exports.isAbsolute(path);
19804
19805 var parts = path.split(/\/+/);
19806 for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
19807 part = parts[i];
19808 if (part === '.') {
19809 parts.splice(i, 1);
19810 } else if (part === '..') {
19811 up++;
19812 } else if (up > 0) {
19813 if (part === '') {
19814 // The first part is blank if the path is absolute. Trying to go
19815 // above the root is a no-op. Therefore we can remove all '..' parts
19816 // directly after the root.
19817 parts.splice(i + 1, up);
19818 up = 0;
19819 } else {
19820 parts.splice(i, 2);
19821 up--;
19822 }
19823 }
19824 }
19825 path = parts.join('/');
19826
19827 if (path === '') {
19828 path = isAbsolute ? '/' : '.';
19829 }
19830
19831 if (url) {
19832 url.path = path;
19833 return urlGenerate(url);
19834 }
19835 return path;
19836}
19837exports.normalize = normalize;
19838
19839/**
19840 * Joins two paths/URLs.
19841 *
19842 * @param aRoot The root path or URL.
19843 * @param aPath The path or URL to be joined with the root.
19844 *
19845 * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
19846 * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
19847 * first.
19848 * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
19849 * is updated with the result and aRoot is returned. Otherwise the result
19850 * is returned.
19851 * - If aPath is absolute, the result is aPath.
19852 * - Otherwise the two paths are joined with a slash.
19853 * - Joining for example 'http://' and 'www.example.com' is also supported.
19854 */
19855function join(aRoot, aPath) {
19856 if (aRoot === "") {
19857 aRoot = ".";
19858 }
19859 if (aPath === "") {
19860 aPath = ".";
19861 }
19862 var aPathUrl = urlParse(aPath);
19863 var aRootUrl = urlParse(aRoot);
19864 if (aRootUrl) {
19865 aRoot = aRootUrl.path || '/';
19866 }
19867
19868 // `join(foo, '//www.example.org')`
19869 if (aPathUrl && !aPathUrl.scheme) {
19870 if (aRootUrl) {
19871 aPathUrl.scheme = aRootUrl.scheme;
19872 }
19873 return urlGenerate(aPathUrl);
19874 }
19875
19876 if (aPathUrl || aPath.match(dataUrlRegexp)) {
19877 return aPath;
19878 }
19879
19880 // `join('http://', 'www.example.com')`
19881 if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
19882 aRootUrl.host = aPath;
19883 return urlGenerate(aRootUrl);
19884 }
19885
19886 var joined = aPath.charAt(0) === '/'
19887 ? aPath
19888 : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
19889
19890 if (aRootUrl) {
19891 aRootUrl.path = joined;
19892 return urlGenerate(aRootUrl);
19893 }
19894 return joined;
19895}
19896exports.join = join;
19897
19898exports.isAbsolute = function (aPath) {
19899 return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
19900};
19901
19902/**
19903 * Make a path relative to a URL or another path.
19904 *
19905 * @param aRoot The root path or URL.
19906 * @param aPath The path or URL to be made relative to aRoot.
19907 */
19908function relative(aRoot, aPath) {
19909 if (aRoot === "") {
19910 aRoot = ".";
19911 }
19912
19913 aRoot = aRoot.replace(/\/$/, '');
19914
19915 // It is possible for the path to be above the root. In this case, simply
19916 // checking whether the root is a prefix of the path won't work. Instead, we
19917 // need to remove components from the root one by one, until either we find
19918 // a prefix that fits, or we run out of components to remove.
19919 var level = 0;
19920 while (aPath.indexOf(aRoot + '/') !== 0) {
19921 var index = aRoot.lastIndexOf("/");
19922 if (index < 0) {
19923 return aPath;
19924 }
19925
19926 // If the only part of the root that is left is the scheme (i.e. http://,
19927 // file:///, etc.), one or more slashes (/), or simply nothing at all, we
19928 // have exhausted all components, so the path is not relative to the root.
19929 aRoot = aRoot.slice(0, index);
19930 if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
19931 return aPath;
19932 }
19933
19934 ++level;
19935 }
19936
19937 // Make sure we add a "../" for each component we removed from the root.
19938 return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
19939}
19940exports.relative = relative;
19941
19942var supportsNullProto = (function () {
19943 var obj = Object.create(null);
19944 return !('__proto__' in obj);
19945}());
19946
19947function identity (s) {
19948 return s;
19949}
19950
19951/**
19952 * Because behavior goes wacky when you set `__proto__` on objects, we
19953 * have to prefix all the strings in our set with an arbitrary character.
19954 *
19955 * See https://github.com/mozilla/source-map/pull/31 and
19956 * https://github.com/mozilla/source-map/issues/30
19957 *
19958 * @param String aStr
19959 */
19960function toSetString(aStr) {
19961 if (isProtoString(aStr)) {
19962 return '$' + aStr;
19963 }
19964
19965 return aStr;
19966}
19967exports.toSetString = supportsNullProto ? identity : toSetString;
19968
19969function fromSetString(aStr) {
19970 if (isProtoString(aStr)) {
19971 return aStr.slice(1);
19972 }
19973
19974 return aStr;
19975}
19976exports.fromSetString = supportsNullProto ? identity : fromSetString;
19977
19978function isProtoString(s) {
19979 if (!s) {
19980 return false;
19981 }
19982
19983 var length = s.length;
19984
19985 if (length < 9 /* "__proto__".length */) {
19986 return false;
19987 }
19988
19989 if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
19990 s.charCodeAt(length - 2) !== 95 /* '_' */ ||
19991 s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
19992 s.charCodeAt(length - 4) !== 116 /* 't' */ ||
19993 s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
19994 s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
19995 s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
19996 s.charCodeAt(length - 8) !== 95 /* '_' */ ||
19997 s.charCodeAt(length - 9) !== 95 /* '_' */) {
19998 return false;
19999 }
20000
20001 for (var i = length - 10; i >= 0; i--) {
20002 if (s.charCodeAt(i) !== 36 /* '$' */) {
20003 return false;
20004 }
20005 }
20006
20007 return true;
20008}
20009
20010/**
20011 * Comparator between two mappings where the original positions are compared.
20012 *
20013 * Optionally pass in `true` as `onlyCompareGenerated` to consider two
20014 * mappings with the same original source/line/column, but different generated
20015 * line and column the same. Useful when searching for a mapping with a
20016 * stubbed out mapping.
20017 */
20018function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
20019 var cmp = strcmp(mappingA.source, mappingB.source);
20020 if (cmp !== 0) {
20021 return cmp;
20022 }
20023
20024 cmp = mappingA.originalLine - mappingB.originalLine;
20025 if (cmp !== 0) {
20026 return cmp;
20027 }
20028
20029 cmp = mappingA.originalColumn - mappingB.originalColumn;
20030 if (cmp !== 0 || onlyCompareOriginal) {
20031 return cmp;
20032 }
20033
20034 cmp = mappingA.generatedColumn - mappingB.generatedColumn;
20035 if (cmp !== 0) {
20036 return cmp;
20037 }
20038
20039 cmp = mappingA.generatedLine - mappingB.generatedLine;
20040 if (cmp !== 0) {
20041 return cmp;
20042 }
20043
20044 return strcmp(mappingA.name, mappingB.name);
20045}
20046exports.compareByOriginalPositions = compareByOriginalPositions;
20047
20048/**
20049 * Comparator between two mappings with deflated source and name indices where
20050 * the generated positions are compared.
20051 *
20052 * Optionally pass in `true` as `onlyCompareGenerated` to consider two
20053 * mappings with the same generated line and column, but different
20054 * source/name/original line and column the same. Useful when searching for a
20055 * mapping with a stubbed out mapping.
20056 */
20057function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
20058 var cmp = mappingA.generatedLine - mappingB.generatedLine;
20059 if (cmp !== 0) {
20060 return cmp;
20061 }
20062
20063 cmp = mappingA.generatedColumn - mappingB.generatedColumn;
20064 if (cmp !== 0 || onlyCompareGenerated) {
20065 return cmp;
20066 }
20067
20068 cmp = strcmp(mappingA.source, mappingB.source);
20069 if (cmp !== 0) {
20070 return cmp;
20071 }
20072
20073 cmp = mappingA.originalLine - mappingB.originalLine;
20074 if (cmp !== 0) {
20075 return cmp;
20076 }
20077
20078 cmp = mappingA.originalColumn - mappingB.originalColumn;
20079 if (cmp !== 0) {
20080 return cmp;
20081 }
20082
20083 return strcmp(mappingA.name, mappingB.name);
20084}
20085exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
20086
20087function strcmp(aStr1, aStr2) {
20088 if (aStr1 === aStr2) {
20089 return 0;
20090 }
20091
20092 if (aStr1 === null) {
20093 return 1; // aStr2 !== null
20094 }
20095
20096 if (aStr2 === null) {
20097 return -1; // aStr1 !== null
20098 }
20099
20100 if (aStr1 > aStr2) {
20101 return 1;
20102 }
20103
20104 return -1;
20105}
20106
20107/**
20108 * Comparator between two mappings with inflated source and name strings where
20109 * the generated positions are compared.
20110 */
20111function compareByGeneratedPositionsInflated(mappingA, mappingB) {
20112 var cmp = mappingA.generatedLine - mappingB.generatedLine;
20113 if (cmp !== 0) {
20114 return cmp;
20115 }
20116
20117 cmp = mappingA.generatedColumn - mappingB.generatedColumn;
20118 if (cmp !== 0) {
20119 return cmp;
20120 }
20121
20122 cmp = strcmp(mappingA.source, mappingB.source);
20123 if (cmp !== 0) {
20124 return cmp;
20125 }
20126
20127 cmp = mappingA.originalLine - mappingB.originalLine;
20128 if (cmp !== 0) {
20129 return cmp;
20130 }
20131
20132 cmp = mappingA.originalColumn - mappingB.originalColumn;
20133 if (cmp !== 0) {
20134 return cmp;
20135 }
20136
20137 return strcmp(mappingA.name, mappingB.name);
20138}
20139exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
20140
20141/**
20142 * Strip any JSON XSSI avoidance prefix from the string (as documented
20143 * in the source maps specification), and then parse the string as
20144 * JSON.
20145 */
20146function parseSourceMapInput(str) {
20147 return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
20148}
20149exports.parseSourceMapInput = parseSourceMapInput;
20150
20151/**
20152 * Compute the URL of a source given the the source root, the source's
20153 * URL, and the source map's URL.
20154 */
20155function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
20156 sourceURL = sourceURL || '';
20157
20158 if (sourceRoot) {
20159 // This follows what Chrome does.
20160 if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
20161 sourceRoot += '/';
20162 }
20163 // The spec says:
20164 // Line 4: An optional source root, useful for relocating source
20165 // files on a server or removing repeated values in the
20166 // “sources” entry. This value is prepended to the individual
20167 // entries in the “source” field.
20168 sourceURL = sourceRoot + sourceURL;
20169 }
20170
20171 // Historically, SourceMapConsumer did not take the sourceMapURL as
20172 // a parameter. This mode is still somewhat supported, which is why
20173 // this code block is conditional. However, it's preferable to pass
20174 // the source map URL to SourceMapConsumer, so that this function
20175 // can implement the source URL resolution algorithm as outlined in
20176 // the spec. This block is basically the equivalent of:
20177 // new URL(sourceURL, sourceMapURL).toString()
20178 // ... except it avoids using URL, which wasn't available in the
20179 // older releases of node still supported by this library.
20180 //
20181 // The spec says:
20182 // If the sources are not absolute URLs after prepending of the
20183 // “sourceRoot”, the sources are resolved relative to the
20184 // SourceMap (like resolving script src in a html document).
20185 if (sourceMapURL) {
20186 var parsed = urlParse(sourceMapURL);
20187 if (!parsed) {
20188 throw new Error("sourceMapURL could not be parsed");
20189 }
20190 if (parsed.path) {
20191 // Strip the last path component, but keep the "/".
20192 var index = parsed.path.lastIndexOf('/');
20193 if (index >= 0) {
20194 parsed.path = parsed.path.substring(0, index + 1);
20195 }
20196 }
20197 sourceURL = join(urlGenerate(parsed), sourceURL);
20198 }
20199
20200 return normalize(sourceURL);
20201}
20202exports.computeSourceURL = computeSourceURL;
20203}(util$7));
20204
20205var arraySet = {};
20206
20207/* -*- Mode: js; js-indent-level: 2; -*- */
20208
20209/*
20210 * Copyright 2011 Mozilla Foundation and contributors
20211 * Licensed under the New BSD license. See LICENSE or:
20212 * http://opensource.org/licenses/BSD-3-Clause
20213 */
20214
20215var util$6 = util$7;
20216var has$1 = Object.prototype.hasOwnProperty;
20217var hasNativeMap = typeof Map !== "undefined";
20218
20219/**
20220 * A data structure which is a combination of an array and a set. Adding a new
20221 * member is O(1), testing for membership is O(1), and finding the index of an
20222 * element is O(1). Removing elements from the set is not supported. Only
20223 * strings are supported for membership.
20224 */
20225function ArraySet$2() {
20226 this._array = [];
20227 this._set = hasNativeMap ? new Map() : Object.create(null);
20228}
20229
20230/**
20231 * Static method for creating ArraySet instances from an existing array.
20232 */
20233ArraySet$2.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
20234 var set = new ArraySet$2();
20235 for (var i = 0, len = aArray.length; i < len; i++) {
20236 set.add(aArray[i], aAllowDuplicates);
20237 }
20238 return set;
20239};
20240
20241/**
20242 * Return how many unique items are in this ArraySet. If duplicates have been
20243 * added, than those do not count towards the size.
20244 *
20245 * @returns Number
20246 */
20247ArraySet$2.prototype.size = function ArraySet_size() {
20248 return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
20249};
20250
20251/**
20252 * Add the given string to this set.
20253 *
20254 * @param String aStr
20255 */
20256ArraySet$2.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
20257 var sStr = hasNativeMap ? aStr : util$6.toSetString(aStr);
20258 var isDuplicate = hasNativeMap ? this.has(aStr) : has$1.call(this._set, sStr);
20259 var idx = this._array.length;
20260 if (!isDuplicate || aAllowDuplicates) {
20261 this._array.push(aStr);
20262 }
20263 if (!isDuplicate) {
20264 if (hasNativeMap) {
20265 this._set.set(aStr, idx);
20266 } else {
20267 this._set[sStr] = idx;
20268 }
20269 }
20270};
20271
20272/**
20273 * Is the given string a member of this set?
20274 *
20275 * @param String aStr
20276 */
20277ArraySet$2.prototype.has = function ArraySet_has(aStr) {
20278 if (hasNativeMap) {
20279 return this._set.has(aStr);
20280 } else {
20281 var sStr = util$6.toSetString(aStr);
20282 return has$1.call(this._set, sStr);
20283 }
20284};
20285
20286/**
20287 * What is the index of the given string in the array?
20288 *
20289 * @param String aStr
20290 */
20291ArraySet$2.prototype.indexOf = function ArraySet_indexOf(aStr) {
20292 if (hasNativeMap) {
20293 var idx = this._set.get(aStr);
20294 if (idx >= 0) {
20295 return idx;
20296 }
20297 } else {
20298 var sStr = util$6.toSetString(aStr);
20299 if (has$1.call(this._set, sStr)) {
20300 return this._set[sStr];
20301 }
20302 }
20303
20304 throw new Error('"' + aStr + '" is not in the set.');
20305};
20306
20307/**
20308 * What is the element at the given index?
20309 *
20310 * @param Number aIdx
20311 */
20312ArraySet$2.prototype.at = function ArraySet_at(aIdx) {
20313 if (aIdx >= 0 && aIdx < this._array.length) {
20314 return this._array[aIdx];
20315 }
20316 throw new Error('No element indexed by ' + aIdx);
20317};
20318
20319/**
20320 * Returns the array representation of this set (which has the proper indices
20321 * indicated by indexOf). Note that this is a copy of the internal array used
20322 * for storing the members so that no one can mess with internal state.
20323 */
20324ArraySet$2.prototype.toArray = function ArraySet_toArray() {
20325 return this._array.slice();
20326};
20327
20328arraySet.ArraySet = ArraySet$2;
20329
20330var mappingList = {};
20331
20332/* -*- Mode: js; js-indent-level: 2; -*- */
20333
20334/*
20335 * Copyright 2014 Mozilla Foundation and contributors
20336 * Licensed under the New BSD license. See LICENSE or:
20337 * http://opensource.org/licenses/BSD-3-Clause
20338 */
20339
20340var util$5 = util$7;
20341
20342/**
20343 * Determine whether mappingB is after mappingA with respect to generated
20344 * position.
20345 */
20346function generatedPositionAfter(mappingA, mappingB) {
20347 // Optimized for most common case
20348 var lineA = mappingA.generatedLine;
20349 var lineB = mappingB.generatedLine;
20350 var columnA = mappingA.generatedColumn;
20351 var columnB = mappingB.generatedColumn;
20352 return lineB > lineA || lineB == lineA && columnB >= columnA ||
20353 util$5.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
20354}
20355
20356/**
20357 * A data structure to provide a sorted view of accumulated mappings in a
20358 * performance conscious manner. It trades a neglibable overhead in general
20359 * case for a large speedup in case of mappings being added in order.
20360 */
20361function MappingList$1() {
20362 this._array = [];
20363 this._sorted = true;
20364 // Serves as infimum
20365 this._last = {generatedLine: -1, generatedColumn: 0};
20366}
20367
20368/**
20369 * Iterate through internal items. This method takes the same arguments that
20370 * `Array.prototype.forEach` takes.
20371 *
20372 * NOTE: The order of the mappings is NOT guaranteed.
20373 */
20374MappingList$1.prototype.unsortedForEach =
20375 function MappingList_forEach(aCallback, aThisArg) {
20376 this._array.forEach(aCallback, aThisArg);
20377 };
20378
20379/**
20380 * Add the given source mapping.
20381 *
20382 * @param Object aMapping
20383 */
20384MappingList$1.prototype.add = function MappingList_add(aMapping) {
20385 if (generatedPositionAfter(this._last, aMapping)) {
20386 this._last = aMapping;
20387 this._array.push(aMapping);
20388 } else {
20389 this._sorted = false;
20390 this._array.push(aMapping);
20391 }
20392};
20393
20394/**
20395 * Returns the flat, sorted array of mappings. The mappings are sorted by
20396 * generated position.
20397 *
20398 * WARNING: This method returns internal data without copying, for
20399 * performance. The return value must NOT be mutated, and should be treated as
20400 * an immutable borrow. If you want to take ownership, you must make your own
20401 * copy.
20402 */
20403MappingList$1.prototype.toArray = function MappingList_toArray() {
20404 if (!this._sorted) {
20405 this._array.sort(util$5.compareByGeneratedPositionsInflated);
20406 this._sorted = true;
20407 }
20408 return this._array;
20409};
20410
20411mappingList.MappingList = MappingList$1;
20412
20413/* -*- Mode: js; js-indent-level: 2; -*- */
20414
20415/*
20416 * Copyright 2011 Mozilla Foundation and contributors
20417 * Licensed under the New BSD license. See LICENSE or:
20418 * http://opensource.org/licenses/BSD-3-Clause
20419 */
20420
20421var base64VLQ$1 = base64Vlq;
20422var util$4 = util$7;
20423var ArraySet$1 = arraySet.ArraySet;
20424var MappingList = mappingList.MappingList;
20425
20426/**
20427 * An instance of the SourceMapGenerator represents a source map which is
20428 * being built incrementally. You may pass an object with the following
20429 * properties:
20430 *
20431 * - file: The filename of the generated source.
20432 * - sourceRoot: A root for all relative URLs in this source map.
20433 */
20434function SourceMapGenerator$1(aArgs) {
20435 if (!aArgs) {
20436 aArgs = {};
20437 }
20438 this._file = util$4.getArg(aArgs, 'file', null);
20439 this._sourceRoot = util$4.getArg(aArgs, 'sourceRoot', null);
20440 this._skipValidation = util$4.getArg(aArgs, 'skipValidation', false);
20441 this._sources = new ArraySet$1();
20442 this._names = new ArraySet$1();
20443 this._mappings = new MappingList();
20444 this._sourcesContents = null;
20445}
20446
20447SourceMapGenerator$1.prototype._version = 3;
20448
20449/**
20450 * Creates a new SourceMapGenerator based on a SourceMapConsumer
20451 *
20452 * @param aSourceMapConsumer The SourceMap.
20453 */
20454SourceMapGenerator$1.fromSourceMap =
20455 function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
20456 var sourceRoot = aSourceMapConsumer.sourceRoot;
20457 var generator = new SourceMapGenerator$1({
20458 file: aSourceMapConsumer.file,
20459 sourceRoot: sourceRoot
20460 });
20461 aSourceMapConsumer.eachMapping(function (mapping) {
20462 var newMapping = {
20463 generated: {
20464 line: mapping.generatedLine,
20465 column: mapping.generatedColumn
20466 }
20467 };
20468
20469 if (mapping.source != null) {
20470 newMapping.source = mapping.source;
20471 if (sourceRoot != null) {
20472 newMapping.source = util$4.relative(sourceRoot, newMapping.source);
20473 }
20474
20475 newMapping.original = {
20476 line: mapping.originalLine,
20477 column: mapping.originalColumn
20478 };
20479
20480 if (mapping.name != null) {
20481 newMapping.name = mapping.name;
20482 }
20483 }
20484
20485 generator.addMapping(newMapping);
20486 });
20487 aSourceMapConsumer.sources.forEach(function (sourceFile) {
20488 var sourceRelative = sourceFile;
20489 if (sourceRoot !== null) {
20490 sourceRelative = util$4.relative(sourceRoot, sourceFile);
20491 }
20492
20493 if (!generator._sources.has(sourceRelative)) {
20494 generator._sources.add(sourceRelative);
20495 }
20496
20497 var content = aSourceMapConsumer.sourceContentFor(sourceFile);
20498 if (content != null) {
20499 generator.setSourceContent(sourceFile, content);
20500 }
20501 });
20502 return generator;
20503 };
20504
20505/**
20506 * Add a single mapping from original source line and column to the generated
20507 * source's line and column for this source map being created. The mapping
20508 * object should have the following properties:
20509 *
20510 * - generated: An object with the generated line and column positions.
20511 * - original: An object with the original line and column positions.
20512 * - source: The original source file (relative to the sourceRoot).
20513 * - name: An optional original token name for this mapping.
20514 */
20515SourceMapGenerator$1.prototype.addMapping =
20516 function SourceMapGenerator_addMapping(aArgs) {
20517 var generated = util$4.getArg(aArgs, 'generated');
20518 var original = util$4.getArg(aArgs, 'original', null);
20519 var source = util$4.getArg(aArgs, 'source', null);
20520 var name = util$4.getArg(aArgs, 'name', null);
20521
20522 if (!this._skipValidation) {
20523 this._validateMapping(generated, original, source, name);
20524 }
20525
20526 if (source != null) {
20527 source = String(source);
20528 if (!this._sources.has(source)) {
20529 this._sources.add(source);
20530 }
20531 }
20532
20533 if (name != null) {
20534 name = String(name);
20535 if (!this._names.has(name)) {
20536 this._names.add(name);
20537 }
20538 }
20539
20540 this._mappings.add({
20541 generatedLine: generated.line,
20542 generatedColumn: generated.column,
20543 originalLine: original != null && original.line,
20544 originalColumn: original != null && original.column,
20545 source: source,
20546 name: name
20547 });
20548 };
20549
20550/**
20551 * Set the source content for a source file.
20552 */
20553SourceMapGenerator$1.prototype.setSourceContent =
20554 function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
20555 var source = aSourceFile;
20556 if (this._sourceRoot != null) {
20557 source = util$4.relative(this._sourceRoot, source);
20558 }
20559
20560 if (aSourceContent != null) {
20561 // Add the source content to the _sourcesContents map.
20562 // Create a new _sourcesContents map if the property is null.
20563 if (!this._sourcesContents) {
20564 this._sourcesContents = Object.create(null);
20565 }
20566 this._sourcesContents[util$4.toSetString(source)] = aSourceContent;
20567 } else if (this._sourcesContents) {
20568 // Remove the source file from the _sourcesContents map.
20569 // If the _sourcesContents map is empty, set the property to null.
20570 delete this._sourcesContents[util$4.toSetString(source)];
20571 if (Object.keys(this._sourcesContents).length === 0) {
20572 this._sourcesContents = null;
20573 }
20574 }
20575 };
20576
20577/**
20578 * Applies the mappings of a sub-source-map for a specific source file to the
20579 * source map being generated. Each mapping to the supplied source file is
20580 * rewritten using the supplied source map. Note: The resolution for the
20581 * resulting mappings is the minimium of this map and the supplied map.
20582 *
20583 * @param aSourceMapConsumer The source map to be applied.
20584 * @param aSourceFile Optional. The filename of the source file.
20585 * If omitted, SourceMapConsumer's file property will be used.
20586 * @param aSourceMapPath Optional. The dirname of the path to the source map
20587 * to be applied. If relative, it is relative to the SourceMapConsumer.
20588 * This parameter is needed when the two source maps aren't in the same
20589 * directory, and the source map to be applied contains relative source
20590 * paths. If so, those relative source paths need to be rewritten
20591 * relative to the SourceMapGenerator.
20592 */
20593SourceMapGenerator$1.prototype.applySourceMap =
20594 function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
20595 var sourceFile = aSourceFile;
20596 // If aSourceFile is omitted, we will use the file property of the SourceMap
20597 if (aSourceFile == null) {
20598 if (aSourceMapConsumer.file == null) {
20599 throw new Error(
20600 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
20601 'or the source map\'s "file" property. Both were omitted.'
20602 );
20603 }
20604 sourceFile = aSourceMapConsumer.file;
20605 }
20606 var sourceRoot = this._sourceRoot;
20607 // Make "sourceFile" relative if an absolute Url is passed.
20608 if (sourceRoot != null) {
20609 sourceFile = util$4.relative(sourceRoot, sourceFile);
20610 }
20611 // Applying the SourceMap can add and remove items from the sources and
20612 // the names array.
20613 var newSources = new ArraySet$1();
20614 var newNames = new ArraySet$1();
20615
20616 // Find mappings for the "sourceFile"
20617 this._mappings.unsortedForEach(function (mapping) {
20618 if (mapping.source === sourceFile && mapping.originalLine != null) {
20619 // Check if it can be mapped by the source map, then update the mapping.
20620 var original = aSourceMapConsumer.originalPositionFor({
20621 line: mapping.originalLine,
20622 column: mapping.originalColumn
20623 });
20624 if (original.source != null) {
20625 // Copy mapping
20626 mapping.source = original.source;
20627 if (aSourceMapPath != null) {
20628 mapping.source = util$4.join(aSourceMapPath, mapping.source);
20629 }
20630 if (sourceRoot != null) {
20631 mapping.source = util$4.relative(sourceRoot, mapping.source);
20632 }
20633 mapping.originalLine = original.line;
20634 mapping.originalColumn = original.column;
20635 if (original.name != null) {
20636 mapping.name = original.name;
20637 }
20638 }
20639 }
20640
20641 var source = mapping.source;
20642 if (source != null && !newSources.has(source)) {
20643 newSources.add(source);
20644 }
20645
20646 var name = mapping.name;
20647 if (name != null && !newNames.has(name)) {
20648 newNames.add(name);
20649 }
20650
20651 }, this);
20652 this._sources = newSources;
20653 this._names = newNames;
20654
20655 // Copy sourcesContents of applied map.
20656 aSourceMapConsumer.sources.forEach(function (sourceFile) {
20657 var content = aSourceMapConsumer.sourceContentFor(sourceFile);
20658 if (content != null) {
20659 if (aSourceMapPath != null) {
20660 sourceFile = util$4.join(aSourceMapPath, sourceFile);
20661 }
20662 if (sourceRoot != null) {
20663 sourceFile = util$4.relative(sourceRoot, sourceFile);
20664 }
20665 this.setSourceContent(sourceFile, content);
20666 }
20667 }, this);
20668 };
20669
20670/**
20671 * A mapping can have one of the three levels of data:
20672 *
20673 * 1. Just the generated position.
20674 * 2. The Generated position, original position, and original source.
20675 * 3. Generated and original position, original source, as well as a name
20676 * token.
20677 *
20678 * To maintain consistency, we validate that any new mapping being added falls
20679 * in to one of these categories.
20680 */
20681SourceMapGenerator$1.prototype._validateMapping =
20682 function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
20683 aName) {
20684 // When aOriginal is truthy but has empty values for .line and .column,
20685 // it is most likely a programmer error. In this case we throw a very
20686 // specific error message to try to guide them the right way.
20687 // For example: https://github.com/Polymer/polymer-bundler/pull/519
20688 if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
20689 throw new Error(
20690 'original.line and original.column are not numbers -- you probably meant to omit ' +
20691 'the original mapping entirely and only map the generated position. If so, pass ' +
20692 'null for the original mapping instead of an object with empty or null values.'
20693 );
20694 }
20695
20696 if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
20697 && aGenerated.line > 0 && aGenerated.column >= 0
20698 && !aOriginal && !aSource && !aName) {
20699 // Case 1.
20700 return;
20701 }
20702 else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
20703 && aOriginal && 'line' in aOriginal && 'column' in aOriginal
20704 && aGenerated.line > 0 && aGenerated.column >= 0
20705 && aOriginal.line > 0 && aOriginal.column >= 0
20706 && aSource) {
20707 // Cases 2 and 3.
20708 return;
20709 }
20710 else {
20711 throw new Error('Invalid mapping: ' + JSON.stringify({
20712 generated: aGenerated,
20713 source: aSource,
20714 original: aOriginal,
20715 name: aName
20716 }));
20717 }
20718 };
20719
20720/**
20721 * Serialize the accumulated mappings in to the stream of base 64 VLQs
20722 * specified by the source map format.
20723 */
20724SourceMapGenerator$1.prototype._serializeMappings =
20725 function SourceMapGenerator_serializeMappings() {
20726 var previousGeneratedColumn = 0;
20727 var previousGeneratedLine = 1;
20728 var previousOriginalColumn = 0;
20729 var previousOriginalLine = 0;
20730 var previousName = 0;
20731 var previousSource = 0;
20732 var result = '';
20733 var next;
20734 var mapping;
20735 var nameIdx;
20736 var sourceIdx;
20737
20738 var mappings = this._mappings.toArray();
20739 for (var i = 0, len = mappings.length; i < len; i++) {
20740 mapping = mappings[i];
20741 next = '';
20742
20743 if (mapping.generatedLine !== previousGeneratedLine) {
20744 previousGeneratedColumn = 0;
20745 while (mapping.generatedLine !== previousGeneratedLine) {
20746 next += ';';
20747 previousGeneratedLine++;
20748 }
20749 }
20750 else {
20751 if (i > 0) {
20752 if (!util$4.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
20753 continue;
20754 }
20755 next += ',';
20756 }
20757 }
20758
20759 next += base64VLQ$1.encode(mapping.generatedColumn
20760 - previousGeneratedColumn);
20761 previousGeneratedColumn = mapping.generatedColumn;
20762
20763 if (mapping.source != null) {
20764 sourceIdx = this._sources.indexOf(mapping.source);
20765 next += base64VLQ$1.encode(sourceIdx - previousSource);
20766 previousSource = sourceIdx;
20767
20768 // lines are stored 0-based in SourceMap spec version 3
20769 next += base64VLQ$1.encode(mapping.originalLine - 1
20770 - previousOriginalLine);
20771 previousOriginalLine = mapping.originalLine - 1;
20772
20773 next += base64VLQ$1.encode(mapping.originalColumn
20774 - previousOriginalColumn);
20775 previousOriginalColumn = mapping.originalColumn;
20776
20777 if (mapping.name != null) {
20778 nameIdx = this._names.indexOf(mapping.name);
20779 next += base64VLQ$1.encode(nameIdx - previousName);
20780 previousName = nameIdx;
20781 }
20782 }
20783
20784 result += next;
20785 }
20786
20787 return result;
20788 };
20789
20790SourceMapGenerator$1.prototype._generateSourcesContent =
20791 function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
20792 return aSources.map(function (source) {
20793 if (!this._sourcesContents) {
20794 return null;
20795 }
20796 if (aSourceRoot != null) {
20797 source = util$4.relative(aSourceRoot, source);
20798 }
20799 var key = util$4.toSetString(source);
20800 return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
20801 ? this._sourcesContents[key]
20802 : null;
20803 }, this);
20804 };
20805
20806/**
20807 * Externalize the source map.
20808 */
20809SourceMapGenerator$1.prototype.toJSON =
20810 function SourceMapGenerator_toJSON() {
20811 var map = {
20812 version: this._version,
20813 sources: this._sources.toArray(),
20814 names: this._names.toArray(),
20815 mappings: this._serializeMappings()
20816 };
20817 if (this._file != null) {
20818 map.file = this._file;
20819 }
20820 if (this._sourceRoot != null) {
20821 map.sourceRoot = this._sourceRoot;
20822 }
20823 if (this._sourcesContents) {
20824 map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
20825 }
20826
20827 return map;
20828 };
20829
20830/**
20831 * Render the source map being generated to a string.
20832 */
20833SourceMapGenerator$1.prototype.toString =
20834 function SourceMapGenerator_toString() {
20835 return JSON.stringify(this.toJSON());
20836 };
20837
20838sourceMapGenerator.SourceMapGenerator = SourceMapGenerator$1;
20839
20840var sourceMapConsumer = {};
20841
20842var binarySearch$1 = {};
20843
20844/* -*- Mode: js; js-indent-level: 2; -*- */
20845
20846(function (exports) {
20847/*
20848 * Copyright 2011 Mozilla Foundation and contributors
20849 * Licensed under the New BSD license. See LICENSE or:
20850 * http://opensource.org/licenses/BSD-3-Clause
20851 */
20852
20853exports.GREATEST_LOWER_BOUND = 1;
20854exports.LEAST_UPPER_BOUND = 2;
20855
20856/**
20857 * Recursive implementation of binary search.
20858 *
20859 * @param aLow Indices here and lower do not contain the needle.
20860 * @param aHigh Indices here and higher do not contain the needle.
20861 * @param aNeedle The element being searched for.
20862 * @param aHaystack The non-empty array being searched.
20863 * @param aCompare Function which takes two elements and returns -1, 0, or 1.
20864 * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
20865 * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
20866 * closest element that is smaller than or greater than the one we are
20867 * searching for, respectively, if the exact element cannot be found.
20868 */
20869function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
20870 // This function terminates when one of the following is true:
20871 //
20872 // 1. We find the exact element we are looking for.
20873 //
20874 // 2. We did not find the exact element, but we can return the index of
20875 // the next-closest element.
20876 //
20877 // 3. We did not find the exact element, and there is no next-closest
20878 // element than the one we are searching for, so we return -1.
20879 var mid = Math.floor((aHigh - aLow) / 2) + aLow;
20880 var cmp = aCompare(aNeedle, aHaystack[mid], true);
20881 if (cmp === 0) {
20882 // Found the element we are looking for.
20883 return mid;
20884 }
20885 else if (cmp > 0) {
20886 // Our needle is greater than aHaystack[mid].
20887 if (aHigh - mid > 1) {
20888 // The element is in the upper half.
20889 return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
20890 }
20891
20892 // The exact needle element was not found in this haystack. Determine if
20893 // we are in termination case (3) or (2) and return the appropriate thing.
20894 if (aBias == exports.LEAST_UPPER_BOUND) {
20895 return aHigh < aHaystack.length ? aHigh : -1;
20896 } else {
20897 return mid;
20898 }
20899 }
20900 else {
20901 // Our needle is less than aHaystack[mid].
20902 if (mid - aLow > 1) {
20903 // The element is in the lower half.
20904 return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
20905 }
20906
20907 // we are in termination case (3) or (2) and return the appropriate thing.
20908 if (aBias == exports.LEAST_UPPER_BOUND) {
20909 return mid;
20910 } else {
20911 return aLow < 0 ? -1 : aLow;
20912 }
20913 }
20914}
20915
20916/**
20917 * This is an implementation of binary search which will always try and return
20918 * the index of the closest element if there is no exact hit. This is because
20919 * mappings between original and generated line/col pairs are single points,
20920 * and there is an implicit region between each of them, so a miss just means
20921 * that you aren't on the very start of a region.
20922 *
20923 * @param aNeedle The element you are looking for.
20924 * @param aHaystack The array that is being searched.
20925 * @param aCompare A function which takes the needle and an element in the
20926 * array and returns -1, 0, or 1 depending on whether the needle is less
20927 * than, equal to, or greater than the element, respectively.
20928 * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
20929 * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
20930 * closest element that is smaller than or greater than the one we are
20931 * searching for, respectively, if the exact element cannot be found.
20932 * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
20933 */
20934exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
20935 if (aHaystack.length === 0) {
20936 return -1;
20937 }
20938
20939 var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
20940 aCompare, aBias || exports.GREATEST_LOWER_BOUND);
20941 if (index < 0) {
20942 return -1;
20943 }
20944
20945 // We have found either the exact element, or the next-closest element than
20946 // the one we are searching for. However, there may be more than one such
20947 // element. Make sure we always return the smallest of these.
20948 while (index - 1 >= 0) {
20949 if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
20950 break;
20951 }
20952 --index;
20953 }
20954
20955 return index;
20956};
20957}(binarySearch$1));
20958
20959var quickSort$1 = {};
20960
20961/* -*- Mode: js; js-indent-level: 2; -*- */
20962
20963/*
20964 * Copyright 2011 Mozilla Foundation and contributors
20965 * Licensed under the New BSD license. See LICENSE or:
20966 * http://opensource.org/licenses/BSD-3-Clause
20967 */
20968
20969// It turns out that some (most?) JavaScript engines don't self-host
20970// `Array.prototype.sort`. This makes sense because C++ will likely remain
20971// faster than JS when doing raw CPU-intensive sorting. However, when using a
20972// custom comparator function, calling back and forth between the VM's C++ and
20973// JIT'd JS is rather slow *and* loses JIT type information, resulting in
20974// worse generated code for the comparator function than would be optimal. In
20975// fact, when sorting with a comparator, these costs outweigh the benefits of
20976// sorting in C++. By using our own JS-implemented Quick Sort (below), we get
20977// a ~3500ms mean speed-up in `bench/bench.html`.
20978
20979/**
20980 * Swap the elements indexed by `x` and `y` in the array `ary`.
20981 *
20982 * @param {Array} ary
20983 * The array.
20984 * @param {Number} x
20985 * The index of the first item.
20986 * @param {Number} y
20987 * The index of the second item.
20988 */
20989function swap(ary, x, y) {
20990 var temp = ary[x];
20991 ary[x] = ary[y];
20992 ary[y] = temp;
20993}
20994
20995/**
20996 * Returns a random integer within the range `low .. high` inclusive.
20997 *
20998 * @param {Number} low
20999 * The lower bound on the range.
21000 * @param {Number} high
21001 * The upper bound on the range.
21002 */
21003function randomIntInRange(low, high) {
21004 return Math.round(low + (Math.random() * (high - low)));
21005}
21006
21007/**
21008 * The Quick Sort algorithm.
21009 *
21010 * @param {Array} ary
21011 * An array to sort.
21012 * @param {function} comparator
21013 * Function to use to compare two items.
21014 * @param {Number} p
21015 * Start index of the array
21016 * @param {Number} r
21017 * End index of the array
21018 */
21019function doQuickSort(ary, comparator, p, r) {
21020 // If our lower bound is less than our upper bound, we (1) partition the
21021 // array into two pieces and (2) recurse on each half. If it is not, this is
21022 // the empty array and our base case.
21023
21024 if (p < r) {
21025 // (1) Partitioning.
21026 //
21027 // The partitioning chooses a pivot between `p` and `r` and moves all
21028 // elements that are less than or equal to the pivot to the before it, and
21029 // all the elements that are greater than it after it. The effect is that
21030 // once partition is done, the pivot is in the exact place it will be when
21031 // the array is put in sorted order, and it will not need to be moved
21032 // again. This runs in O(n) time.
21033
21034 // Always choose a random pivot so that an input array which is reverse
21035 // sorted does not cause O(n^2) running time.
21036 var pivotIndex = randomIntInRange(p, r);
21037 var i = p - 1;
21038
21039 swap(ary, pivotIndex, r);
21040 var pivot = ary[r];
21041
21042 // Immediately after `j` is incremented in this loop, the following hold
21043 // true:
21044 //
21045 // * Every element in `ary[p .. i]` is less than or equal to the pivot.
21046 //
21047 // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
21048 for (var j = p; j < r; j++) {
21049 if (comparator(ary[j], pivot) <= 0) {
21050 i += 1;
21051 swap(ary, i, j);
21052 }
21053 }
21054
21055 swap(ary, i + 1, j);
21056 var q = i + 1;
21057
21058 // (2) Recurse on each half.
21059
21060 doQuickSort(ary, comparator, p, q - 1);
21061 doQuickSort(ary, comparator, q + 1, r);
21062 }
21063}
21064
21065/**
21066 * Sort the given array in-place with the given comparator function.
21067 *
21068 * @param {Array} ary
21069 * An array to sort.
21070 * @param {function} comparator
21071 * Function to use to compare two items.
21072 */
21073quickSort$1.quickSort = function (ary, comparator) {
21074 doQuickSort(ary, comparator, 0, ary.length - 1);
21075};
21076
21077/* -*- Mode: js; js-indent-level: 2; -*- */
21078
21079/*
21080 * Copyright 2011 Mozilla Foundation and contributors
21081 * Licensed under the New BSD license. See LICENSE or:
21082 * http://opensource.org/licenses/BSD-3-Clause
21083 */
21084
21085var util$3 = util$7;
21086var binarySearch = binarySearch$1;
21087var ArraySet = arraySet.ArraySet;
21088var base64VLQ = base64Vlq;
21089var quickSort = quickSort$1.quickSort;
21090
21091function SourceMapConsumer$1(aSourceMap, aSourceMapURL) {
21092 var sourceMap = aSourceMap;
21093 if (typeof aSourceMap === 'string') {
21094 sourceMap = util$3.parseSourceMapInput(aSourceMap);
21095 }
21096
21097 return sourceMap.sections != null
21098 ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
21099 : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
21100}
21101
21102SourceMapConsumer$1.fromSourceMap = function(aSourceMap, aSourceMapURL) {
21103 return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
21104};
21105
21106/**
21107 * The version of the source mapping spec that we are consuming.
21108 */
21109SourceMapConsumer$1.prototype._version = 3;
21110
21111// `__generatedMappings` and `__originalMappings` are arrays that hold the
21112// parsed mapping coordinates from the source map's "mappings" attribute. They
21113// are lazily instantiated, accessed via the `_generatedMappings` and
21114// `_originalMappings` getters respectively, and we only parse the mappings
21115// and create these arrays once queried for a source location. We jump through
21116// these hoops because there can be many thousands of mappings, and parsing
21117// them is expensive, so we only want to do it if we must.
21118//
21119// Each object in the arrays is of the form:
21120//
21121// {
21122// generatedLine: The line number in the generated code,
21123// generatedColumn: The column number in the generated code,
21124// source: The path to the original source file that generated this
21125// chunk of code,
21126// originalLine: The line number in the original source that
21127// corresponds to this chunk of generated code,
21128// originalColumn: The column number in the original source that
21129// corresponds to this chunk of generated code,
21130// name: The name of the original symbol which generated this chunk of
21131// code.
21132// }
21133//
21134// All properties except for `generatedLine` and `generatedColumn` can be
21135// `null`.
21136//
21137// `_generatedMappings` is ordered by the generated positions.
21138//
21139// `_originalMappings` is ordered by the original positions.
21140
21141SourceMapConsumer$1.prototype.__generatedMappings = null;
21142Object.defineProperty(SourceMapConsumer$1.prototype, '_generatedMappings', {
21143 configurable: true,
21144 enumerable: true,
21145 get: function () {
21146 if (!this.__generatedMappings) {
21147 this._parseMappings(this._mappings, this.sourceRoot);
21148 }
21149
21150 return this.__generatedMappings;
21151 }
21152});
21153
21154SourceMapConsumer$1.prototype.__originalMappings = null;
21155Object.defineProperty(SourceMapConsumer$1.prototype, '_originalMappings', {
21156 configurable: true,
21157 enumerable: true,
21158 get: function () {
21159 if (!this.__originalMappings) {
21160 this._parseMappings(this._mappings, this.sourceRoot);
21161 }
21162
21163 return this.__originalMappings;
21164 }
21165});
21166
21167SourceMapConsumer$1.prototype._charIsMappingSeparator =
21168 function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
21169 var c = aStr.charAt(index);
21170 return c === ";" || c === ",";
21171 };
21172
21173/**
21174 * Parse the mappings in a string in to a data structure which we can easily
21175 * query (the ordered arrays in the `this.__generatedMappings` and
21176 * `this.__originalMappings` properties).
21177 */
21178SourceMapConsumer$1.prototype._parseMappings =
21179 function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
21180 throw new Error("Subclasses must implement _parseMappings");
21181 };
21182
21183SourceMapConsumer$1.GENERATED_ORDER = 1;
21184SourceMapConsumer$1.ORIGINAL_ORDER = 2;
21185
21186SourceMapConsumer$1.GREATEST_LOWER_BOUND = 1;
21187SourceMapConsumer$1.LEAST_UPPER_BOUND = 2;
21188
21189/**
21190 * Iterate over each mapping between an original source/line/column and a
21191 * generated line/column in this source map.
21192 *
21193 * @param Function aCallback
21194 * The function that is called with each mapping.
21195 * @param Object aContext
21196 * Optional. If specified, this object will be the value of `this` every
21197 * time that `aCallback` is called.
21198 * @param aOrder
21199 * Either `SourceMapConsumer.GENERATED_ORDER` or
21200 * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
21201 * iterate over the mappings sorted by the generated file's line/column
21202 * order or the original's source/line/column order, respectively. Defaults to
21203 * `SourceMapConsumer.GENERATED_ORDER`.
21204 */
21205SourceMapConsumer$1.prototype.eachMapping =
21206 function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
21207 var context = aContext || null;
21208 var order = aOrder || SourceMapConsumer$1.GENERATED_ORDER;
21209
21210 var mappings;
21211 switch (order) {
21212 case SourceMapConsumer$1.GENERATED_ORDER:
21213 mappings = this._generatedMappings;
21214 break;
21215 case SourceMapConsumer$1.ORIGINAL_ORDER:
21216 mappings = this._originalMappings;
21217 break;
21218 default:
21219 throw new Error("Unknown order of iteration.");
21220 }
21221
21222 var sourceRoot = this.sourceRoot;
21223 mappings.map(function (mapping) {
21224 var source = mapping.source === null ? null : this._sources.at(mapping.source);
21225 source = util$3.computeSourceURL(sourceRoot, source, this._sourceMapURL);
21226 return {
21227 source: source,
21228 generatedLine: mapping.generatedLine,
21229 generatedColumn: mapping.generatedColumn,
21230 originalLine: mapping.originalLine,
21231 originalColumn: mapping.originalColumn,
21232 name: mapping.name === null ? null : this._names.at(mapping.name)
21233 };
21234 }, this).forEach(aCallback, context);
21235 };
21236
21237/**
21238 * Returns all generated line and column information for the original source,
21239 * line, and column provided. If no column is provided, returns all mappings
21240 * corresponding to a either the line we are searching for or the next
21241 * closest line that has any mappings. Otherwise, returns all mappings
21242 * corresponding to the given line and either the column we are searching for
21243 * or the next closest column that has any offsets.
21244 *
21245 * The only argument is an object with the following properties:
21246 *
21247 * - source: The filename of the original source.
21248 * - line: The line number in the original source. The line number is 1-based.
21249 * - column: Optional. the column number in the original source.
21250 * The column number is 0-based.
21251 *
21252 * and an array of objects is returned, each with the following properties:
21253 *
21254 * - line: The line number in the generated source, or null. The
21255 * line number is 1-based.
21256 * - column: The column number in the generated source, or null.
21257 * The column number is 0-based.
21258 */
21259SourceMapConsumer$1.prototype.allGeneratedPositionsFor =
21260 function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
21261 var line = util$3.getArg(aArgs, 'line');
21262
21263 // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
21264 // returns the index of the closest mapping less than the needle. By
21265 // setting needle.originalColumn to 0, we thus find the last mapping for
21266 // the given line, provided such a mapping exists.
21267 var needle = {
21268 source: util$3.getArg(aArgs, 'source'),
21269 originalLine: line,
21270 originalColumn: util$3.getArg(aArgs, 'column', 0)
21271 };
21272
21273 needle.source = this._findSourceIndex(needle.source);
21274 if (needle.source < 0) {
21275 return [];
21276 }
21277
21278 var mappings = [];
21279
21280 var index = this._findMapping(needle,
21281 this._originalMappings,
21282 "originalLine",
21283 "originalColumn",
21284 util$3.compareByOriginalPositions,
21285 binarySearch.LEAST_UPPER_BOUND);
21286 if (index >= 0) {
21287 var mapping = this._originalMappings[index];
21288
21289 if (aArgs.column === undefined) {
21290 var originalLine = mapping.originalLine;
21291
21292 // Iterate until either we run out of mappings, or we run into
21293 // a mapping for a different line than the one we found. Since
21294 // mappings are sorted, this is guaranteed to find all mappings for
21295 // the line we found.
21296 while (mapping && mapping.originalLine === originalLine) {
21297 mappings.push({
21298 line: util$3.getArg(mapping, 'generatedLine', null),
21299 column: util$3.getArg(mapping, 'generatedColumn', null),
21300 lastColumn: util$3.getArg(mapping, 'lastGeneratedColumn', null)
21301 });
21302
21303 mapping = this._originalMappings[++index];
21304 }
21305 } else {
21306 var originalColumn = mapping.originalColumn;
21307
21308 // Iterate until either we run out of mappings, or we run into
21309 // a mapping for a different line than the one we were searching for.
21310 // Since mappings are sorted, this is guaranteed to find all mappings for
21311 // the line we are searching for.
21312 while (mapping &&
21313 mapping.originalLine === line &&
21314 mapping.originalColumn == originalColumn) {
21315 mappings.push({
21316 line: util$3.getArg(mapping, 'generatedLine', null),
21317 column: util$3.getArg(mapping, 'generatedColumn', null),
21318 lastColumn: util$3.getArg(mapping, 'lastGeneratedColumn', null)
21319 });
21320
21321 mapping = this._originalMappings[++index];
21322 }
21323 }
21324 }
21325
21326 return mappings;
21327 };
21328
21329sourceMapConsumer.SourceMapConsumer = SourceMapConsumer$1;
21330
21331/**
21332 * A BasicSourceMapConsumer instance represents a parsed source map which we can
21333 * query for information about the original file positions by giving it a file
21334 * position in the generated source.
21335 *
21336 * The first parameter is the raw source map (either as a JSON string, or
21337 * already parsed to an object). According to the spec, source maps have the
21338 * following attributes:
21339 *
21340 * - version: Which version of the source map spec this map is following.
21341 * - sources: An array of URLs to the original source files.
21342 * - names: An array of identifiers which can be referrenced by individual mappings.
21343 * - sourceRoot: Optional. The URL root from which all sources are relative.
21344 * - sourcesContent: Optional. An array of contents of the original source files.
21345 * - mappings: A string of base64 VLQs which contain the actual mappings.
21346 * - file: Optional. The generated file this source map is associated with.
21347 *
21348 * Here is an example source map, taken from the source map spec[0]:
21349 *
21350 * {
21351 * version : 3,
21352 * file: "out.js",
21353 * sourceRoot : "",
21354 * sources: ["foo.js", "bar.js"],
21355 * names: ["src", "maps", "are", "fun"],
21356 * mappings: "AA,AB;;ABCDE;"
21357 * }
21358 *
21359 * The second parameter, if given, is a string whose value is the URL
21360 * at which the source map was found. This URL is used to compute the
21361 * sources array.
21362 *
21363 * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
21364 */
21365function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
21366 var sourceMap = aSourceMap;
21367 if (typeof aSourceMap === 'string') {
21368 sourceMap = util$3.parseSourceMapInput(aSourceMap);
21369 }
21370
21371 var version = util$3.getArg(sourceMap, 'version');
21372 var sources = util$3.getArg(sourceMap, 'sources');
21373 // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
21374 // requires the array) to play nice here.
21375 var names = util$3.getArg(sourceMap, 'names', []);
21376 var sourceRoot = util$3.getArg(sourceMap, 'sourceRoot', null);
21377 var sourcesContent = util$3.getArg(sourceMap, 'sourcesContent', null);
21378 var mappings = util$3.getArg(sourceMap, 'mappings');
21379 var file = util$3.getArg(sourceMap, 'file', null);
21380
21381 // Once again, Sass deviates from the spec and supplies the version as a
21382 // string rather than a number, so we use loose equality checking here.
21383 if (version != this._version) {
21384 throw new Error('Unsupported version: ' + version);
21385 }
21386
21387 if (sourceRoot) {
21388 sourceRoot = util$3.normalize(sourceRoot);
21389 }
21390
21391 sources = sources
21392 .map(String)
21393 // Some source maps produce relative source paths like "./foo.js" instead of
21394 // "foo.js". Normalize these first so that future comparisons will succeed.
21395 // See bugzil.la/1090768.
21396 .map(util$3.normalize)
21397 // Always ensure that absolute sources are internally stored relative to
21398 // the source root, if the source root is absolute. Not doing this would
21399 // be particularly problematic when the source root is a prefix of the
21400 // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
21401 .map(function (source) {
21402 return sourceRoot && util$3.isAbsolute(sourceRoot) && util$3.isAbsolute(source)
21403 ? util$3.relative(sourceRoot, source)
21404 : source;
21405 });
21406
21407 // Pass `true` below to allow duplicate names and sources. While source maps
21408 // are intended to be compressed and deduplicated, the TypeScript compiler
21409 // sometimes generates source maps with duplicates in them. See Github issue
21410 // #72 and bugzil.la/889492.
21411 this._names = ArraySet.fromArray(names.map(String), true);
21412 this._sources = ArraySet.fromArray(sources, true);
21413
21414 this._absoluteSources = this._sources.toArray().map(function (s) {
21415 return util$3.computeSourceURL(sourceRoot, s, aSourceMapURL);
21416 });
21417
21418 this.sourceRoot = sourceRoot;
21419 this.sourcesContent = sourcesContent;
21420 this._mappings = mappings;
21421 this._sourceMapURL = aSourceMapURL;
21422 this.file = file;
21423}
21424
21425BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer$1.prototype);
21426BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer$1;
21427
21428/**
21429 * Utility function to find the index of a source. Returns -1 if not
21430 * found.
21431 */
21432BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
21433 var relativeSource = aSource;
21434 if (this.sourceRoot != null) {
21435 relativeSource = util$3.relative(this.sourceRoot, relativeSource);
21436 }
21437
21438 if (this._sources.has(relativeSource)) {
21439 return this._sources.indexOf(relativeSource);
21440 }
21441
21442 // Maybe aSource is an absolute URL as returned by |sources|. In
21443 // this case we can't simply undo the transform.
21444 var i;
21445 for (i = 0; i < this._absoluteSources.length; ++i) {
21446 if (this._absoluteSources[i] == aSource) {
21447 return i;
21448 }
21449 }
21450
21451 return -1;
21452};
21453
21454/**
21455 * Create a BasicSourceMapConsumer from a SourceMapGenerator.
21456 *
21457 * @param SourceMapGenerator aSourceMap
21458 * The source map that will be consumed.
21459 * @param String aSourceMapURL
21460 * The URL at which the source map can be found (optional)
21461 * @returns BasicSourceMapConsumer
21462 */
21463BasicSourceMapConsumer.fromSourceMap =
21464 function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
21465 var smc = Object.create(BasicSourceMapConsumer.prototype);
21466
21467 var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
21468 var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
21469 smc.sourceRoot = aSourceMap._sourceRoot;
21470 smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
21471 smc.sourceRoot);
21472 smc.file = aSourceMap._file;
21473 smc._sourceMapURL = aSourceMapURL;
21474 smc._absoluteSources = smc._sources.toArray().map(function (s) {
21475 return util$3.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
21476 });
21477
21478 // Because we are modifying the entries (by converting string sources and
21479 // names to indices into the sources and names ArraySets), we have to make
21480 // a copy of the entry or else bad things happen. Shared mutable state
21481 // strikes again! See github issue #191.
21482
21483 var generatedMappings = aSourceMap._mappings.toArray().slice();
21484 var destGeneratedMappings = smc.__generatedMappings = [];
21485 var destOriginalMappings = smc.__originalMappings = [];
21486
21487 for (var i = 0, length = generatedMappings.length; i < length; i++) {
21488 var srcMapping = generatedMappings[i];
21489 var destMapping = new Mapping;
21490 destMapping.generatedLine = srcMapping.generatedLine;
21491 destMapping.generatedColumn = srcMapping.generatedColumn;
21492
21493 if (srcMapping.source) {
21494 destMapping.source = sources.indexOf(srcMapping.source);
21495 destMapping.originalLine = srcMapping.originalLine;
21496 destMapping.originalColumn = srcMapping.originalColumn;
21497
21498 if (srcMapping.name) {
21499 destMapping.name = names.indexOf(srcMapping.name);
21500 }
21501
21502 destOriginalMappings.push(destMapping);
21503 }
21504
21505 destGeneratedMappings.push(destMapping);
21506 }
21507
21508 quickSort(smc.__originalMappings, util$3.compareByOriginalPositions);
21509
21510 return smc;
21511 };
21512
21513/**
21514 * The version of the source mapping spec that we are consuming.
21515 */
21516BasicSourceMapConsumer.prototype._version = 3;
21517
21518/**
21519 * The list of original sources.
21520 */
21521Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
21522 get: function () {
21523 return this._absoluteSources.slice();
21524 }
21525});
21526
21527/**
21528 * Provide the JIT with a nice shape / hidden class.
21529 */
21530function Mapping() {
21531 this.generatedLine = 0;
21532 this.generatedColumn = 0;
21533 this.source = null;
21534 this.originalLine = null;
21535 this.originalColumn = null;
21536 this.name = null;
21537}
21538
21539/**
21540 * Parse the mappings in a string in to a data structure which we can easily
21541 * query (the ordered arrays in the `this.__generatedMappings` and
21542 * `this.__originalMappings` properties).
21543 */
21544BasicSourceMapConsumer.prototype._parseMappings =
21545 function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
21546 var generatedLine = 1;
21547 var previousGeneratedColumn = 0;
21548 var previousOriginalLine = 0;
21549 var previousOriginalColumn = 0;
21550 var previousSource = 0;
21551 var previousName = 0;
21552 var length = aStr.length;
21553 var index = 0;
21554 var cachedSegments = {};
21555 var temp = {};
21556 var originalMappings = [];
21557 var generatedMappings = [];
21558 var mapping, str, segment, end, value;
21559
21560 while (index < length) {
21561 if (aStr.charAt(index) === ';') {
21562 generatedLine++;
21563 index++;
21564 previousGeneratedColumn = 0;
21565 }
21566 else if (aStr.charAt(index) === ',') {
21567 index++;
21568 }
21569 else {
21570 mapping = new Mapping();
21571 mapping.generatedLine = generatedLine;
21572
21573 // Because each offset is encoded relative to the previous one,
21574 // many segments often have the same encoding. We can exploit this
21575 // fact by caching the parsed variable length fields of each segment,
21576 // allowing us to avoid a second parse if we encounter the same
21577 // segment again.
21578 for (end = index; end < length; end++) {
21579 if (this._charIsMappingSeparator(aStr, end)) {
21580 break;
21581 }
21582 }
21583 str = aStr.slice(index, end);
21584
21585 segment = cachedSegments[str];
21586 if (segment) {
21587 index += str.length;
21588 } else {
21589 segment = [];
21590 while (index < end) {
21591 base64VLQ.decode(aStr, index, temp);
21592 value = temp.value;
21593 index = temp.rest;
21594 segment.push(value);
21595 }
21596
21597 if (segment.length === 2) {
21598 throw new Error('Found a source, but no line and column');
21599 }
21600
21601 if (segment.length === 3) {
21602 throw new Error('Found a source and line, but no column');
21603 }
21604
21605 cachedSegments[str] = segment;
21606 }
21607
21608 // Generated column.
21609 mapping.generatedColumn = previousGeneratedColumn + segment[0];
21610 previousGeneratedColumn = mapping.generatedColumn;
21611
21612 if (segment.length > 1) {
21613 // Original source.
21614 mapping.source = previousSource + segment[1];
21615 previousSource += segment[1];
21616
21617 // Original line.
21618 mapping.originalLine = previousOriginalLine + segment[2];
21619 previousOriginalLine = mapping.originalLine;
21620 // Lines are stored 0-based
21621 mapping.originalLine += 1;
21622
21623 // Original column.
21624 mapping.originalColumn = previousOriginalColumn + segment[3];
21625 previousOriginalColumn = mapping.originalColumn;
21626
21627 if (segment.length > 4) {
21628 // Original name.
21629 mapping.name = previousName + segment[4];
21630 previousName += segment[4];
21631 }
21632 }
21633
21634 generatedMappings.push(mapping);
21635 if (typeof mapping.originalLine === 'number') {
21636 originalMappings.push(mapping);
21637 }
21638 }
21639 }
21640
21641 quickSort(generatedMappings, util$3.compareByGeneratedPositionsDeflated);
21642 this.__generatedMappings = generatedMappings;
21643
21644 quickSort(originalMappings, util$3.compareByOriginalPositions);
21645 this.__originalMappings = originalMappings;
21646 };
21647
21648/**
21649 * Find the mapping that best matches the hypothetical "needle" mapping that
21650 * we are searching for in the given "haystack" of mappings.
21651 */
21652BasicSourceMapConsumer.prototype._findMapping =
21653 function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
21654 aColumnName, aComparator, aBias) {
21655 // To return the position we are searching for, we must first find the
21656 // mapping for the given position and then return the opposite position it
21657 // points to. Because the mappings are sorted, we can use binary search to
21658 // find the best mapping.
21659
21660 if (aNeedle[aLineName] <= 0) {
21661 throw new TypeError('Line must be greater than or equal to 1, got '
21662 + aNeedle[aLineName]);
21663 }
21664 if (aNeedle[aColumnName] < 0) {
21665 throw new TypeError('Column must be greater than or equal to 0, got '
21666 + aNeedle[aColumnName]);
21667 }
21668
21669 return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
21670 };
21671
21672/**
21673 * Compute the last column for each generated mapping. The last column is
21674 * inclusive.
21675 */
21676BasicSourceMapConsumer.prototype.computeColumnSpans =
21677 function SourceMapConsumer_computeColumnSpans() {
21678 for (var index = 0; index < this._generatedMappings.length; ++index) {
21679 var mapping = this._generatedMappings[index];
21680
21681 // Mappings do not contain a field for the last generated columnt. We
21682 // can come up with an optimistic estimate, however, by assuming that
21683 // mappings are contiguous (i.e. given two consecutive mappings, the
21684 // first mapping ends where the second one starts).
21685 if (index + 1 < this._generatedMappings.length) {
21686 var nextMapping = this._generatedMappings[index + 1];
21687
21688 if (mapping.generatedLine === nextMapping.generatedLine) {
21689 mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
21690 continue;
21691 }
21692 }
21693
21694 // The last mapping for each line spans the entire line.
21695 mapping.lastGeneratedColumn = Infinity;
21696 }
21697 };
21698
21699/**
21700 * Returns the original source, line, and column information for the generated
21701 * source's line and column positions provided. The only argument is an object
21702 * with the following properties:
21703 *
21704 * - line: The line number in the generated source. The line number
21705 * is 1-based.
21706 * - column: The column number in the generated source. The column
21707 * number is 0-based.
21708 * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
21709 * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
21710 * closest element that is smaller than or greater than the one we are
21711 * searching for, respectively, if the exact element cannot be found.
21712 * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
21713 *
21714 * and an object is returned with the following properties:
21715 *
21716 * - source: The original source file, or null.
21717 * - line: The line number in the original source, or null. The
21718 * line number is 1-based.
21719 * - column: The column number in the original source, or null. The
21720 * column number is 0-based.
21721 * - name: The original identifier, or null.
21722 */
21723BasicSourceMapConsumer.prototype.originalPositionFor =
21724 function SourceMapConsumer_originalPositionFor(aArgs) {
21725 var needle = {
21726 generatedLine: util$3.getArg(aArgs, 'line'),
21727 generatedColumn: util$3.getArg(aArgs, 'column')
21728 };
21729
21730 var index = this._findMapping(
21731 needle,
21732 this._generatedMappings,
21733 "generatedLine",
21734 "generatedColumn",
21735 util$3.compareByGeneratedPositionsDeflated,
21736 util$3.getArg(aArgs, 'bias', SourceMapConsumer$1.GREATEST_LOWER_BOUND)
21737 );
21738
21739 if (index >= 0) {
21740 var mapping = this._generatedMappings[index];
21741
21742 if (mapping.generatedLine === needle.generatedLine) {
21743 var source = util$3.getArg(mapping, 'source', null);
21744 if (source !== null) {
21745 source = this._sources.at(source);
21746 source = util$3.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
21747 }
21748 var name = util$3.getArg(mapping, 'name', null);
21749 if (name !== null) {
21750 name = this._names.at(name);
21751 }
21752 return {
21753 source: source,
21754 line: util$3.getArg(mapping, 'originalLine', null),
21755 column: util$3.getArg(mapping, 'originalColumn', null),
21756 name: name
21757 };
21758 }
21759 }
21760
21761 return {
21762 source: null,
21763 line: null,
21764 column: null,
21765 name: null
21766 };
21767 };
21768
21769/**
21770 * Return true if we have the source content for every source in the source
21771 * map, false otherwise.
21772 */
21773BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
21774 function BasicSourceMapConsumer_hasContentsOfAllSources() {
21775 if (!this.sourcesContent) {
21776 return false;
21777 }
21778 return this.sourcesContent.length >= this._sources.size() &&
21779 !this.sourcesContent.some(function (sc) { return sc == null; });
21780 };
21781
21782/**
21783 * Returns the original source content. The only argument is the url of the
21784 * original source file. Returns null if no original source content is
21785 * available.
21786 */
21787BasicSourceMapConsumer.prototype.sourceContentFor =
21788 function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
21789 if (!this.sourcesContent) {
21790 return null;
21791 }
21792
21793 var index = this._findSourceIndex(aSource);
21794 if (index >= 0) {
21795 return this.sourcesContent[index];
21796 }
21797
21798 var relativeSource = aSource;
21799 if (this.sourceRoot != null) {
21800 relativeSource = util$3.relative(this.sourceRoot, relativeSource);
21801 }
21802
21803 var url;
21804 if (this.sourceRoot != null
21805 && (url = util$3.urlParse(this.sourceRoot))) {
21806 // XXX: file:// URIs and absolute paths lead to unexpected behavior for
21807 // many users. We can help them out when they expect file:// URIs to
21808 // behave like it would if they were running a local HTTP server. See
21809 // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
21810 var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
21811 if (url.scheme == "file"
21812 && this._sources.has(fileUriAbsPath)) {
21813 return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
21814 }
21815
21816 if ((!url.path || url.path == "/")
21817 && this._sources.has("/" + relativeSource)) {
21818 return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
21819 }
21820 }
21821
21822 // This function is used recursively from
21823 // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
21824 // don't want to throw if we can't find the source - we just want to
21825 // return null, so we provide a flag to exit gracefully.
21826 if (nullOnMissing) {
21827 return null;
21828 }
21829 else {
21830 throw new Error('"' + relativeSource + '" is not in the SourceMap.');
21831 }
21832 };
21833
21834/**
21835 * Returns the generated line and column information for the original source,
21836 * line, and column positions provided. The only argument is an object with
21837 * the following properties:
21838 *
21839 * - source: The filename of the original source.
21840 * - line: The line number in the original source. The line number
21841 * is 1-based.
21842 * - column: The column number in the original source. The column
21843 * number is 0-based.
21844 * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
21845 * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
21846 * closest element that is smaller than or greater than the one we are
21847 * searching for, respectively, if the exact element cannot be found.
21848 * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
21849 *
21850 * and an object is returned with the following properties:
21851 *
21852 * - line: The line number in the generated source, or null. The
21853 * line number is 1-based.
21854 * - column: The column number in the generated source, or null.
21855 * The column number is 0-based.
21856 */
21857BasicSourceMapConsumer.prototype.generatedPositionFor =
21858 function SourceMapConsumer_generatedPositionFor(aArgs) {
21859 var source = util$3.getArg(aArgs, 'source');
21860 source = this._findSourceIndex(source);
21861 if (source < 0) {
21862 return {
21863 line: null,
21864 column: null,
21865 lastColumn: null
21866 };
21867 }
21868
21869 var needle = {
21870 source: source,
21871 originalLine: util$3.getArg(aArgs, 'line'),
21872 originalColumn: util$3.getArg(aArgs, 'column')
21873 };
21874
21875 var index = this._findMapping(
21876 needle,
21877 this._originalMappings,
21878 "originalLine",
21879 "originalColumn",
21880 util$3.compareByOriginalPositions,
21881 util$3.getArg(aArgs, 'bias', SourceMapConsumer$1.GREATEST_LOWER_BOUND)
21882 );
21883
21884 if (index >= 0) {
21885 var mapping = this._originalMappings[index];
21886
21887 if (mapping.source === needle.source) {
21888 return {
21889 line: util$3.getArg(mapping, 'generatedLine', null),
21890 column: util$3.getArg(mapping, 'generatedColumn', null),
21891 lastColumn: util$3.getArg(mapping, 'lastGeneratedColumn', null)
21892 };
21893 }
21894 }
21895
21896 return {
21897 line: null,
21898 column: null,
21899 lastColumn: null
21900 };
21901 };
21902
21903sourceMapConsumer.BasicSourceMapConsumer = BasicSourceMapConsumer;
21904
21905/**
21906 * An IndexedSourceMapConsumer instance represents a parsed source map which
21907 * we can query for information. It differs from BasicSourceMapConsumer in
21908 * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
21909 * input.
21910 *
21911 * The first parameter is a raw source map (either as a JSON string, or already
21912 * parsed to an object). According to the spec for indexed source maps, they
21913 * have the following attributes:
21914 *
21915 * - version: Which version of the source map spec this map is following.
21916 * - file: Optional. The generated file this source map is associated with.
21917 * - sections: A list of section definitions.
21918 *
21919 * Each value under the "sections" field has two fields:
21920 * - offset: The offset into the original specified at which this section
21921 * begins to apply, defined as an object with a "line" and "column"
21922 * field.
21923 * - map: A source map definition. This source map could also be indexed,
21924 * but doesn't have to be.
21925 *
21926 * Instead of the "map" field, it's also possible to have a "url" field
21927 * specifying a URL to retrieve a source map from, but that's currently
21928 * unsupported.
21929 *
21930 * Here's an example source map, taken from the source map spec[0], but
21931 * modified to omit a section which uses the "url" field.
21932 *
21933 * {
21934 * version : 3,
21935 * file: "app.js",
21936 * sections: [{
21937 * offset: {line:100, column:10},
21938 * map: {
21939 * version : 3,
21940 * file: "section.js",
21941 * sources: ["foo.js", "bar.js"],
21942 * names: ["src", "maps", "are", "fun"],
21943 * mappings: "AAAA,E;;ABCDE;"
21944 * }
21945 * }],
21946 * }
21947 *
21948 * The second parameter, if given, is a string whose value is the URL
21949 * at which the source map was found. This URL is used to compute the
21950 * sources array.
21951 *
21952 * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
21953 */
21954function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
21955 var sourceMap = aSourceMap;
21956 if (typeof aSourceMap === 'string') {
21957 sourceMap = util$3.parseSourceMapInput(aSourceMap);
21958 }
21959
21960 var version = util$3.getArg(sourceMap, 'version');
21961 var sections = util$3.getArg(sourceMap, 'sections');
21962
21963 if (version != this._version) {
21964 throw new Error('Unsupported version: ' + version);
21965 }
21966
21967 this._sources = new ArraySet();
21968 this._names = new ArraySet();
21969
21970 var lastOffset = {
21971 line: -1,
21972 column: 0
21973 };
21974 this._sections = sections.map(function (s) {
21975 if (s.url) {
21976 // The url field will require support for asynchronicity.
21977 // See https://github.com/mozilla/source-map/issues/16
21978 throw new Error('Support for url field in sections not implemented.');
21979 }
21980 var offset = util$3.getArg(s, 'offset');
21981 var offsetLine = util$3.getArg(offset, 'line');
21982 var offsetColumn = util$3.getArg(offset, 'column');
21983
21984 if (offsetLine < lastOffset.line ||
21985 (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
21986 throw new Error('Section offsets must be ordered and non-overlapping.');
21987 }
21988 lastOffset = offset;
21989
21990 return {
21991 generatedOffset: {
21992 // The offset fields are 0-based, but we use 1-based indices when
21993 // encoding/decoding from VLQ.
21994 generatedLine: offsetLine + 1,
21995 generatedColumn: offsetColumn + 1
21996 },
21997 consumer: new SourceMapConsumer$1(util$3.getArg(s, 'map'), aSourceMapURL)
21998 }
21999 });
22000}
22001
22002IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer$1.prototype);
22003IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer$1;
22004
22005/**
22006 * The version of the source mapping spec that we are consuming.
22007 */
22008IndexedSourceMapConsumer.prototype._version = 3;
22009
22010/**
22011 * The list of original sources.
22012 */
22013Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
22014 get: function () {
22015 var sources = [];
22016 for (var i = 0; i < this._sections.length; i++) {
22017 for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
22018 sources.push(this._sections[i].consumer.sources[j]);
22019 }
22020 }
22021 return sources;
22022 }
22023});
22024
22025/**
22026 * Returns the original source, line, and column information for the generated
22027 * source's line and column positions provided. The only argument is an object
22028 * with the following properties:
22029 *
22030 * - line: The line number in the generated source. The line number
22031 * is 1-based.
22032 * - column: The column number in the generated source. The column
22033 * number is 0-based.
22034 *
22035 * and an object is returned with the following properties:
22036 *
22037 * - source: The original source file, or null.
22038 * - line: The line number in the original source, or null. The
22039 * line number is 1-based.
22040 * - column: The column number in the original source, or null. The
22041 * column number is 0-based.
22042 * - name: The original identifier, or null.
22043 */
22044IndexedSourceMapConsumer.prototype.originalPositionFor =
22045 function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
22046 var needle = {
22047 generatedLine: util$3.getArg(aArgs, 'line'),
22048 generatedColumn: util$3.getArg(aArgs, 'column')
22049 };
22050
22051 // Find the section containing the generated position we're trying to map
22052 // to an original position.
22053 var sectionIndex = binarySearch.search(needle, this._sections,
22054 function(needle, section) {
22055 var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
22056 if (cmp) {
22057 return cmp;
22058 }
22059
22060 return (needle.generatedColumn -
22061 section.generatedOffset.generatedColumn);
22062 });
22063 var section = this._sections[sectionIndex];
22064
22065 if (!section) {
22066 return {
22067 source: null,
22068 line: null,
22069 column: null,
22070 name: null
22071 };
22072 }
22073
22074 return section.consumer.originalPositionFor({
22075 line: needle.generatedLine -
22076 (section.generatedOffset.generatedLine - 1),
22077 column: needle.generatedColumn -
22078 (section.generatedOffset.generatedLine === needle.generatedLine
22079 ? section.generatedOffset.generatedColumn - 1
22080 : 0),
22081 bias: aArgs.bias
22082 });
22083 };
22084
22085/**
22086 * Return true if we have the source content for every source in the source
22087 * map, false otherwise.
22088 */
22089IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
22090 function IndexedSourceMapConsumer_hasContentsOfAllSources() {
22091 return this._sections.every(function (s) {
22092 return s.consumer.hasContentsOfAllSources();
22093 });
22094 };
22095
22096/**
22097 * Returns the original source content. The only argument is the url of the
22098 * original source file. Returns null if no original source content is
22099 * available.
22100 */
22101IndexedSourceMapConsumer.prototype.sourceContentFor =
22102 function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
22103 for (var i = 0; i < this._sections.length; i++) {
22104 var section = this._sections[i];
22105
22106 var content = section.consumer.sourceContentFor(aSource, true);
22107 if (content) {
22108 return content;
22109 }
22110 }
22111 if (nullOnMissing) {
22112 return null;
22113 }
22114 else {
22115 throw new Error('"' + aSource + '" is not in the SourceMap.');
22116 }
22117 };
22118
22119/**
22120 * Returns the generated line and column information for the original source,
22121 * line, and column positions provided. The only argument is an object with
22122 * the following properties:
22123 *
22124 * - source: The filename of the original source.
22125 * - line: The line number in the original source. The line number
22126 * is 1-based.
22127 * - column: The column number in the original source. The column
22128 * number is 0-based.
22129 *
22130 * and an object is returned with the following properties:
22131 *
22132 * - line: The line number in the generated source, or null. The
22133 * line number is 1-based.
22134 * - column: The column number in the generated source, or null.
22135 * The column number is 0-based.
22136 */
22137IndexedSourceMapConsumer.prototype.generatedPositionFor =
22138 function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
22139 for (var i = 0; i < this._sections.length; i++) {
22140 var section = this._sections[i];
22141
22142 // Only consider this section if the requested source is in the list of
22143 // sources of the consumer.
22144 if (section.consumer._findSourceIndex(util$3.getArg(aArgs, 'source')) === -1) {
22145 continue;
22146 }
22147 var generatedPosition = section.consumer.generatedPositionFor(aArgs);
22148 if (generatedPosition) {
22149 var ret = {
22150 line: generatedPosition.line +
22151 (section.generatedOffset.generatedLine - 1),
22152 column: generatedPosition.column +
22153 (section.generatedOffset.generatedLine === generatedPosition.line
22154 ? section.generatedOffset.generatedColumn - 1
22155 : 0)
22156 };
22157 return ret;
22158 }
22159 }
22160
22161 return {
22162 line: null,
22163 column: null
22164 };
22165 };
22166
22167/**
22168 * Parse the mappings in a string in to a data structure which we can easily
22169 * query (the ordered arrays in the `this.__generatedMappings` and
22170 * `this.__originalMappings` properties).
22171 */
22172IndexedSourceMapConsumer.prototype._parseMappings =
22173 function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
22174 this.__generatedMappings = [];
22175 this.__originalMappings = [];
22176 for (var i = 0; i < this._sections.length; i++) {
22177 var section = this._sections[i];
22178 var sectionMappings = section.consumer._generatedMappings;
22179 for (var j = 0; j < sectionMappings.length; j++) {
22180 var mapping = sectionMappings[j];
22181
22182 var source = section.consumer._sources.at(mapping.source);
22183 source = util$3.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
22184 this._sources.add(source);
22185 source = this._sources.indexOf(source);
22186
22187 var name = null;
22188 if (mapping.name) {
22189 name = section.consumer._names.at(mapping.name);
22190 this._names.add(name);
22191 name = this._names.indexOf(name);
22192 }
22193
22194 // The mappings coming from the consumer for the section have
22195 // generated positions relative to the start of the section, so we
22196 // need to offset them to be relative to the start of the concatenated
22197 // generated file.
22198 var adjustedMapping = {
22199 source: source,
22200 generatedLine: mapping.generatedLine +
22201 (section.generatedOffset.generatedLine - 1),
22202 generatedColumn: mapping.generatedColumn +
22203 (section.generatedOffset.generatedLine === mapping.generatedLine
22204 ? section.generatedOffset.generatedColumn - 1
22205 : 0),
22206 originalLine: mapping.originalLine,
22207 originalColumn: mapping.originalColumn,
22208 name: name
22209 };
22210
22211 this.__generatedMappings.push(adjustedMapping);
22212 if (typeof adjustedMapping.originalLine === 'number') {
22213 this.__originalMappings.push(adjustedMapping);
22214 }
22215 }
22216 }
22217
22218 quickSort(this.__generatedMappings, util$3.compareByGeneratedPositionsDeflated);
22219 quickSort(this.__originalMappings, util$3.compareByOriginalPositions);
22220 };
22221
22222sourceMapConsumer.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
22223
22224var sourceNode = {};
22225
22226/* -*- Mode: js; js-indent-level: 2; -*- */
22227
22228/*
22229 * Copyright 2011 Mozilla Foundation and contributors
22230 * Licensed under the New BSD license. See LICENSE or:
22231 * http://opensource.org/licenses/BSD-3-Clause
22232 */
22233
22234var SourceMapGenerator = sourceMapGenerator.SourceMapGenerator;
22235var util$2 = util$7;
22236
22237// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
22238// operating systems these days (capturing the result).
22239var REGEX_NEWLINE = /(\r?\n)/;
22240
22241// Newline character code for charCodeAt() comparisons
22242var NEWLINE_CODE = 10;
22243
22244// Private symbol for identifying `SourceNode`s when multiple versions of
22245// the source-map library are loaded. This MUST NOT CHANGE across
22246// versions!
22247var isSourceNode = "$$$isSourceNode$$$";
22248
22249/**
22250 * SourceNodes provide a way to abstract over interpolating/concatenating
22251 * snippets of generated JavaScript source code while maintaining the line and
22252 * column information associated with the original source code.
22253 *
22254 * @param aLine The original line number.
22255 * @param aColumn The original column number.
22256 * @param aSource The original source's filename.
22257 * @param aChunks Optional. An array of strings which are snippets of
22258 * generated JS, or other SourceNodes.
22259 * @param aName The original identifier.
22260 */
22261function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
22262 this.children = [];
22263 this.sourceContents = {};
22264 this.line = aLine == null ? null : aLine;
22265 this.column = aColumn == null ? null : aColumn;
22266 this.source = aSource == null ? null : aSource;
22267 this.name = aName == null ? null : aName;
22268 this[isSourceNode] = true;
22269 if (aChunks != null) this.add(aChunks);
22270}
22271
22272/**
22273 * Creates a SourceNode from generated code and a SourceMapConsumer.
22274 *
22275 * @param aGeneratedCode The generated code
22276 * @param aSourceMapConsumer The SourceMap for the generated code
22277 * @param aRelativePath Optional. The path that relative sources in the
22278 * SourceMapConsumer should be relative to.
22279 */
22280SourceNode.fromStringWithSourceMap =
22281 function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
22282 // The SourceNode we want to fill with the generated code
22283 // and the SourceMap
22284 var node = new SourceNode();
22285
22286 // All even indices of this array are one line of the generated code,
22287 // while all odd indices are the newlines between two adjacent lines
22288 // (since `REGEX_NEWLINE` captures its match).
22289 // Processed fragments are accessed by calling `shiftNextLine`.
22290 var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
22291 var remainingLinesIndex = 0;
22292 var shiftNextLine = function() {
22293 var lineContents = getNextLine();
22294 // The last line of a file might not have a newline.
22295 var newLine = getNextLine() || "";
22296 return lineContents + newLine;
22297
22298 function getNextLine() {
22299 return remainingLinesIndex < remainingLines.length ?
22300 remainingLines[remainingLinesIndex++] : undefined;
22301 }
22302 };
22303
22304 // We need to remember the position of "remainingLines"
22305 var lastGeneratedLine = 1, lastGeneratedColumn = 0;
22306
22307 // The generate SourceNodes we need a code range.
22308 // To extract it current and last mapping is used.
22309 // Here we store the last mapping.
22310 var lastMapping = null;
22311
22312 aSourceMapConsumer.eachMapping(function (mapping) {
22313 if (lastMapping !== null) {
22314 // We add the code from "lastMapping" to "mapping":
22315 // First check if there is a new line in between.
22316 if (lastGeneratedLine < mapping.generatedLine) {
22317 // Associate first line with "lastMapping"
22318 addMappingWithCode(lastMapping, shiftNextLine());
22319 lastGeneratedLine++;
22320 lastGeneratedColumn = 0;
22321 // The remaining code is added without mapping
22322 } else {
22323 // There is no new line in between.
22324 // Associate the code between "lastGeneratedColumn" and
22325 // "mapping.generatedColumn" with "lastMapping"
22326 var nextLine = remainingLines[remainingLinesIndex] || '';
22327 var code = nextLine.substr(0, mapping.generatedColumn -
22328 lastGeneratedColumn);
22329 remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
22330 lastGeneratedColumn);
22331 lastGeneratedColumn = mapping.generatedColumn;
22332 addMappingWithCode(lastMapping, code);
22333 // No more remaining code, continue
22334 lastMapping = mapping;
22335 return;
22336 }
22337 }
22338 // We add the generated code until the first mapping
22339 // to the SourceNode without any mapping.
22340 // Each line is added as separate string.
22341 while (lastGeneratedLine < mapping.generatedLine) {
22342 node.add(shiftNextLine());
22343 lastGeneratedLine++;
22344 }
22345 if (lastGeneratedColumn < mapping.generatedColumn) {
22346 var nextLine = remainingLines[remainingLinesIndex] || '';
22347 node.add(nextLine.substr(0, mapping.generatedColumn));
22348 remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
22349 lastGeneratedColumn = mapping.generatedColumn;
22350 }
22351 lastMapping = mapping;
22352 }, this);
22353 // We have processed all mappings.
22354 if (remainingLinesIndex < remainingLines.length) {
22355 if (lastMapping) {
22356 // Associate the remaining code in the current line with "lastMapping"
22357 addMappingWithCode(lastMapping, shiftNextLine());
22358 }
22359 // and add the remaining lines without any mapping
22360 node.add(remainingLines.splice(remainingLinesIndex).join(""));
22361 }
22362
22363 // Copy sourcesContent into SourceNode
22364 aSourceMapConsumer.sources.forEach(function (sourceFile) {
22365 var content = aSourceMapConsumer.sourceContentFor(sourceFile);
22366 if (content != null) {
22367 if (aRelativePath != null) {
22368 sourceFile = util$2.join(aRelativePath, sourceFile);
22369 }
22370 node.setSourceContent(sourceFile, content);
22371 }
22372 });
22373
22374 return node;
22375
22376 function addMappingWithCode(mapping, code) {
22377 if (mapping === null || mapping.source === undefined) {
22378 node.add(code);
22379 } else {
22380 var source = aRelativePath
22381 ? util$2.join(aRelativePath, mapping.source)
22382 : mapping.source;
22383 node.add(new SourceNode(mapping.originalLine,
22384 mapping.originalColumn,
22385 source,
22386 code,
22387 mapping.name));
22388 }
22389 }
22390 };
22391
22392/**
22393 * Add a chunk of generated JS to this source node.
22394 *
22395 * @param aChunk A string snippet of generated JS code, another instance of
22396 * SourceNode, or an array where each member is one of those things.
22397 */
22398SourceNode.prototype.add = function SourceNode_add(aChunk) {
22399 if (Array.isArray(aChunk)) {
22400 aChunk.forEach(function (chunk) {
22401 this.add(chunk);
22402 }, this);
22403 }
22404 else if (aChunk[isSourceNode] || typeof aChunk === "string") {
22405 if (aChunk) {
22406 this.children.push(aChunk);
22407 }
22408 }
22409 else {
22410 throw new TypeError(
22411 "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
22412 );
22413 }
22414 return this;
22415};
22416
22417/**
22418 * Add a chunk of generated JS to the beginning of this source node.
22419 *
22420 * @param aChunk A string snippet of generated JS code, another instance of
22421 * SourceNode, or an array where each member is one of those things.
22422 */
22423SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
22424 if (Array.isArray(aChunk)) {
22425 for (var i = aChunk.length-1; i >= 0; i--) {
22426 this.prepend(aChunk[i]);
22427 }
22428 }
22429 else if (aChunk[isSourceNode] || typeof aChunk === "string") {
22430 this.children.unshift(aChunk);
22431 }
22432 else {
22433 throw new TypeError(
22434 "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
22435 );
22436 }
22437 return this;
22438};
22439
22440/**
22441 * Walk over the tree of JS snippets in this node and its children. The
22442 * walking function is called once for each snippet of JS and is passed that
22443 * snippet and the its original associated source's line/column location.
22444 *
22445 * @param aFn The traversal function.
22446 */
22447SourceNode.prototype.walk = function SourceNode_walk(aFn) {
22448 var chunk;
22449 for (var i = 0, len = this.children.length; i < len; i++) {
22450 chunk = this.children[i];
22451 if (chunk[isSourceNode]) {
22452 chunk.walk(aFn);
22453 }
22454 else {
22455 if (chunk !== '') {
22456 aFn(chunk, { source: this.source,
22457 line: this.line,
22458 column: this.column,
22459 name: this.name });
22460 }
22461 }
22462 }
22463};
22464
22465/**
22466 * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
22467 * each of `this.children`.
22468 *
22469 * @param aSep The separator.
22470 */
22471SourceNode.prototype.join = function SourceNode_join(aSep) {
22472 var newChildren;
22473 var i;
22474 var len = this.children.length;
22475 if (len > 0) {
22476 newChildren = [];
22477 for (i = 0; i < len-1; i++) {
22478 newChildren.push(this.children[i]);
22479 newChildren.push(aSep);
22480 }
22481 newChildren.push(this.children[i]);
22482 this.children = newChildren;
22483 }
22484 return this;
22485};
22486
22487/**
22488 * Call String.prototype.replace on the very right-most source snippet. Useful
22489 * for trimming whitespace from the end of a source node, etc.
22490 *
22491 * @param aPattern The pattern to replace.
22492 * @param aReplacement The thing to replace the pattern with.
22493 */
22494SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
22495 var lastChild = this.children[this.children.length - 1];
22496 if (lastChild[isSourceNode]) {
22497 lastChild.replaceRight(aPattern, aReplacement);
22498 }
22499 else if (typeof lastChild === 'string') {
22500 this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
22501 }
22502 else {
22503 this.children.push(''.replace(aPattern, aReplacement));
22504 }
22505 return this;
22506};
22507
22508/**
22509 * Set the source content for a source file. This will be added to the SourceMapGenerator
22510 * in the sourcesContent field.
22511 *
22512 * @param aSourceFile The filename of the source file
22513 * @param aSourceContent The content of the source file
22514 */
22515SourceNode.prototype.setSourceContent =
22516 function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
22517 this.sourceContents[util$2.toSetString(aSourceFile)] = aSourceContent;
22518 };
22519
22520/**
22521 * Walk over the tree of SourceNodes. The walking function is called for each
22522 * source file content and is passed the filename and source content.
22523 *
22524 * @param aFn The traversal function.
22525 */
22526SourceNode.prototype.walkSourceContents =
22527 function SourceNode_walkSourceContents(aFn) {
22528 for (var i = 0, len = this.children.length; i < len; i++) {
22529 if (this.children[i][isSourceNode]) {
22530 this.children[i].walkSourceContents(aFn);
22531 }
22532 }
22533
22534 var sources = Object.keys(this.sourceContents);
22535 for (var i = 0, len = sources.length; i < len; i++) {
22536 aFn(util$2.fromSetString(sources[i]), this.sourceContents[sources[i]]);
22537 }
22538 };
22539
22540/**
22541 * Return the string representation of this source node. Walks over the tree
22542 * and concatenates all the various snippets together to one string.
22543 */
22544SourceNode.prototype.toString = function SourceNode_toString() {
22545 var str = "";
22546 this.walk(function (chunk) {
22547 str += chunk;
22548 });
22549 return str;
22550};
22551
22552/**
22553 * Returns the string representation of this source node along with a source
22554 * map.
22555 */
22556SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
22557 var generated = {
22558 code: "",
22559 line: 1,
22560 column: 0
22561 };
22562 var map = new SourceMapGenerator(aArgs);
22563 var sourceMappingActive = false;
22564 var lastOriginalSource = null;
22565 var lastOriginalLine = null;
22566 var lastOriginalColumn = null;
22567 var lastOriginalName = null;
22568 this.walk(function (chunk, original) {
22569 generated.code += chunk;
22570 if (original.source !== null
22571 && original.line !== null
22572 && original.column !== null) {
22573 if(lastOriginalSource !== original.source
22574 || lastOriginalLine !== original.line
22575 || lastOriginalColumn !== original.column
22576 || lastOriginalName !== original.name) {
22577 map.addMapping({
22578 source: original.source,
22579 original: {
22580 line: original.line,
22581 column: original.column
22582 },
22583 generated: {
22584 line: generated.line,
22585 column: generated.column
22586 },
22587 name: original.name
22588 });
22589 }
22590 lastOriginalSource = original.source;
22591 lastOriginalLine = original.line;
22592 lastOriginalColumn = original.column;
22593 lastOriginalName = original.name;
22594 sourceMappingActive = true;
22595 } else if (sourceMappingActive) {
22596 map.addMapping({
22597 generated: {
22598 line: generated.line,
22599 column: generated.column
22600 }
22601 });
22602 lastOriginalSource = null;
22603 sourceMappingActive = false;
22604 }
22605 for (var idx = 0, length = chunk.length; idx < length; idx++) {
22606 if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
22607 generated.line++;
22608 generated.column = 0;
22609 // Mappings end at eol
22610 if (idx + 1 === length) {
22611 lastOriginalSource = null;
22612 sourceMappingActive = false;
22613 } else if (sourceMappingActive) {
22614 map.addMapping({
22615 source: original.source,
22616 original: {
22617 line: original.line,
22618 column: original.column
22619 },
22620 generated: {
22621 line: generated.line,
22622 column: generated.column
22623 },
22624 name: original.name
22625 });
22626 }
22627 } else {
22628 generated.column++;
22629 }
22630 }
22631 });
22632 this.walkSourceContents(function (sourceFile, sourceContent) {
22633 map.setSourceContent(sourceFile, sourceContent);
22634 });
22635
22636 return { code: generated.code, map: map };
22637};
22638
22639sourceNode.SourceNode = SourceNode;
22640
22641/*
22642 * Copyright 2009-2011 Mozilla Foundation and contributors
22643 * Licensed under the New BSD license. See LICENSE.txt or:
22644 * http://opensource.org/licenses/BSD-3-Clause
22645 */
22646
22647sourceMap.SourceMapGenerator = sourceMapGenerator.SourceMapGenerator;
22648var SourceMapConsumer = sourceMap.SourceMapConsumer = sourceMapConsumer.SourceMapConsumer;
22649sourceMap.SourceNode = sourceNode.SourceNode;
22650
22651var toString$2 = Object.prototype.toString;
22652
22653var isModern = (
22654 typeof Buffer.alloc === 'function' &&
22655 typeof Buffer.allocUnsafe === 'function' &&
22656 typeof Buffer.from === 'function'
22657);
22658
22659function isArrayBuffer (input) {
22660 return toString$2.call(input).slice(8, -1) === 'ArrayBuffer'
22661}
22662
22663function fromArrayBuffer (obj, byteOffset, length) {
22664 byteOffset >>>= 0;
22665
22666 var maxLength = obj.byteLength - byteOffset;
22667
22668 if (maxLength < 0) {
22669 throw new RangeError("'offset' is out of bounds")
22670 }
22671
22672 if (length === undefined) {
22673 length = maxLength;
22674 } else {
22675 length >>>= 0;
22676
22677 if (length > maxLength) {
22678 throw new RangeError("'length' is out of bounds")
22679 }
22680 }
22681
22682 return isModern
22683 ? Buffer.from(obj.slice(byteOffset, byteOffset + length))
22684 : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length)))
22685}
22686
22687function fromString (string, encoding) {
22688 if (typeof encoding !== 'string' || encoding === '') {
22689 encoding = 'utf8';
22690 }
22691
22692 if (!Buffer.isEncoding(encoding)) {
22693 throw new TypeError('"encoding" must be a valid string encoding')
22694 }
22695
22696 return isModern
22697 ? Buffer.from(string, encoding)
22698 : new Buffer(string, encoding)
22699}
22700
22701function bufferFrom (value, encodingOrOffset, length) {
22702 if (typeof value === 'number') {
22703 throw new TypeError('"value" argument must not be a number')
22704 }
22705
22706 if (isArrayBuffer(value)) {
22707 return fromArrayBuffer(value, encodingOrOffset, length)
22708 }
22709
22710 if (typeof value === 'string') {
22711 return fromString(value, encodingOrOffset)
22712 }
22713
22714 return isModern
22715 ? Buffer.from(value)
22716 : new Buffer(value)
22717}
22718
22719var bufferFrom_1 = bufferFrom;
22720
22721(function (module, exports) {
22722var SourceMapConsumer = sourceMap.SourceMapConsumer;
22723var path = path__default;
22724
22725var fs;
22726try {
22727 fs = fs__default;
22728 if (!fs.existsSync || !fs.readFileSync) {
22729 // fs doesn't have all methods we need
22730 fs = null;
22731 }
22732} catch (err) {
22733 /* nop */
22734}
22735
22736var bufferFrom = bufferFrom_1;
22737
22738/**
22739 * Requires a module which is protected against bundler minification.
22740 *
22741 * @param {NodeModule} mod
22742 * @param {string} request
22743 */
22744function dynamicRequire(mod, request) {
22745 return mod.require(request);
22746}
22747
22748// Only install once if called multiple times
22749var errorFormatterInstalled = false;
22750var uncaughtShimInstalled = false;
22751
22752// If true, the caches are reset before a stack trace formatting operation
22753var emptyCacheBetweenOperations = false;
22754
22755// Supports {browser, node, auto}
22756var environment = "auto";
22757
22758// Maps a file path to a string containing the file contents
22759var fileContentsCache = {};
22760
22761// Maps a file path to a source map for that file
22762var sourceMapCache = {};
22763
22764// Regex for detecting source maps
22765var reSourceMap = /^data:application\/json[^,]+base64,/;
22766
22767// Priority list of retrieve handlers
22768var retrieveFileHandlers = [];
22769var retrieveMapHandlers = [];
22770
22771function isInBrowser() {
22772 if (environment === "browser")
22773 return true;
22774 if (environment === "node")
22775 return false;
22776 return ((typeof window !== 'undefined') && (typeof XMLHttpRequest === 'function') && !(window.require && window.module && window.process && window.process.type === "renderer"));
22777}
22778
22779function hasGlobalProcessEventEmitter() {
22780 return ((typeof process === 'object') && (process !== null) && (typeof process.on === 'function'));
22781}
22782
22783function handlerExec(list) {
22784 return function(arg) {
22785 for (var i = 0; i < list.length; i++) {
22786 var ret = list[i](arg);
22787 if (ret) {
22788 return ret;
22789 }
22790 }
22791 return null;
22792 };
22793}
22794
22795var retrieveFile = handlerExec(retrieveFileHandlers);
22796
22797retrieveFileHandlers.push(function(path) {
22798 // Trim the path to make sure there is no extra whitespace.
22799 path = path.trim();
22800 if (/^file:/.test(path)) {
22801 // existsSync/readFileSync can't handle file protocol, but once stripped, it works
22802 path = path.replace(/file:\/\/\/(\w:)?/, function(protocol, drive) {
22803 return drive ?
22804 '' : // file:///C:/dir/file -> C:/dir/file
22805 '/'; // file:///root-dir/file -> /root-dir/file
22806 });
22807 }
22808 if (path in fileContentsCache) {
22809 return fileContentsCache[path];
22810 }
22811
22812 var contents = '';
22813 try {
22814 if (!fs) {
22815 // Use SJAX if we are in the browser
22816 var xhr = new XMLHttpRequest();
22817 xhr.open('GET', path, /** async */ false);
22818 xhr.send(null);
22819 if (xhr.readyState === 4 && xhr.status === 200) {
22820 contents = xhr.responseText;
22821 }
22822 } else if (fs.existsSync(path)) {
22823 // Otherwise, use the filesystem
22824 contents = fs.readFileSync(path, 'utf8');
22825 }
22826 } catch (er) {
22827 /* ignore any errors */
22828 }
22829
22830 return fileContentsCache[path] = contents;
22831});
22832
22833// Support URLs relative to a directory, but be careful about a protocol prefix
22834// in case we are in the browser (i.e. directories may start with "http://" or "file:///")
22835function supportRelativeURL(file, url) {
22836 if (!file) return url;
22837 var dir = path.dirname(file);
22838 var match = /^\w+:\/\/[^\/]*/.exec(dir);
22839 var protocol = match ? match[0] : '';
22840 var startPath = dir.slice(protocol.length);
22841 if (protocol && /^\/\w\:/.test(startPath)) {
22842 // handle file:///C:/ paths
22843 protocol += '/';
22844 return protocol + path.resolve(dir.slice(protocol.length), url).replace(/\\/g, '/');
22845 }
22846 return protocol + path.resolve(dir.slice(protocol.length), url);
22847}
22848
22849function retrieveSourceMapURL(source) {
22850 var fileData;
22851
22852 if (isInBrowser()) {
22853 try {
22854 var xhr = new XMLHttpRequest();
22855 xhr.open('GET', source, false);
22856 xhr.send(null);
22857 fileData = xhr.readyState === 4 ? xhr.responseText : null;
22858
22859 // Support providing a sourceMappingURL via the SourceMap header
22860 var sourceMapHeader = xhr.getResponseHeader("SourceMap") ||
22861 xhr.getResponseHeader("X-SourceMap");
22862 if (sourceMapHeader) {
22863 return sourceMapHeader;
22864 }
22865 } catch (e) {
22866 }
22867 }
22868
22869 // Get the URL of the source map
22870 fileData = retrieveFile(source);
22871 var re = /(?:\/\/[@#][\s]*sourceMappingURL=([^\s'"]+)[\s]*$)|(?:\/\*[@#][\s]*sourceMappingURL=([^\s*'"]+)[\s]*(?:\*\/)[\s]*$)/mg;
22872 // Keep executing the search to find the *last* sourceMappingURL to avoid
22873 // picking up sourceMappingURLs from comments, strings, etc.
22874 var lastMatch, match;
22875 while (match = re.exec(fileData)) lastMatch = match;
22876 if (!lastMatch) return null;
22877 return lastMatch[1];
22878}
22879// Can be overridden by the retrieveSourceMap option to install. Takes a
22880// generated source filename; returns a {map, optional url} object, or null if
22881// there is no source map. The map field may be either a string or the parsed
22882// JSON object (ie, it must be a valid argument to the SourceMapConsumer
22883// constructor).
22884var retrieveSourceMap = handlerExec(retrieveMapHandlers);
22885retrieveMapHandlers.push(function(source) {
22886 var sourceMappingURL = retrieveSourceMapURL(source);
22887 if (!sourceMappingURL) return null;
22888
22889 // Read the contents of the source map
22890 var sourceMapData;
22891 if (reSourceMap.test(sourceMappingURL)) {
22892 // Support source map URL as a data url
22893 var rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(',') + 1);
22894 sourceMapData = bufferFrom(rawData, "base64").toString();
22895 sourceMappingURL = source;
22896 } else {
22897 // Support source map URLs relative to the source URL
22898 sourceMappingURL = supportRelativeURL(source, sourceMappingURL);
22899 sourceMapData = retrieveFile(sourceMappingURL);
22900 }
22901
22902 if (!sourceMapData) {
22903 return null;
22904 }
22905
22906 return {
22907 url: sourceMappingURL,
22908 map: sourceMapData
22909 };
22910});
22911
22912function mapSourcePosition(position) {
22913 var sourceMap = sourceMapCache[position.source];
22914 if (!sourceMap) {
22915 // Call the (overrideable) retrieveSourceMap function to get the source map.
22916 var urlAndMap = retrieveSourceMap(position.source);
22917 if (urlAndMap) {
22918 sourceMap = sourceMapCache[position.source] = {
22919 url: urlAndMap.url,
22920 map: new SourceMapConsumer(urlAndMap.map)
22921 };
22922
22923 // Load all sources stored inline with the source map into the file cache
22924 // to pretend like they are already loaded. They may not exist on disk.
22925 if (sourceMap.map.sourcesContent) {
22926 sourceMap.map.sources.forEach(function(source, i) {
22927 var contents = sourceMap.map.sourcesContent[i];
22928 if (contents) {
22929 var url = supportRelativeURL(sourceMap.url, source);
22930 fileContentsCache[url] = contents;
22931 }
22932 });
22933 }
22934 } else {
22935 sourceMap = sourceMapCache[position.source] = {
22936 url: null,
22937 map: null
22938 };
22939 }
22940 }
22941
22942 // Resolve the source URL relative to the URL of the source map
22943 if (sourceMap && sourceMap.map && typeof sourceMap.map.originalPositionFor === 'function') {
22944 var originalPosition = sourceMap.map.originalPositionFor(position);
22945
22946 // Only return the original position if a matching line was found. If no
22947 // matching line is found then we return position instead, which will cause
22948 // the stack trace to print the path and line for the compiled file. It is
22949 // better to give a precise location in the compiled file than a vague
22950 // location in the original file.
22951 if (originalPosition.source !== null) {
22952 originalPosition.source = supportRelativeURL(
22953 sourceMap.url, originalPosition.source);
22954 return originalPosition;
22955 }
22956 }
22957
22958 return position;
22959}
22960
22961// Parses code generated by FormatEvalOrigin(), a function inside V8:
22962// https://code.google.com/p/v8/source/browse/trunk/src/messages.js
22963function mapEvalOrigin(origin) {
22964 // Most eval() calls are in this format
22965 var match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin);
22966 if (match) {
22967 var position = mapSourcePosition({
22968 source: match[2],
22969 line: +match[3],
22970 column: match[4] - 1
22971 });
22972 return 'eval at ' + match[1] + ' (' + position.source + ':' +
22973 position.line + ':' + (position.column + 1) + ')';
22974 }
22975
22976 // Parse nested eval() calls using recursion
22977 match = /^eval at ([^(]+) \((.+)\)$/.exec(origin);
22978 if (match) {
22979 return 'eval at ' + match[1] + ' (' + mapEvalOrigin(match[2]) + ')';
22980 }
22981
22982 // Make sure we still return useful information if we didn't find anything
22983 return origin;
22984}
22985
22986// This is copied almost verbatim from the V8 source code at
22987// https://code.google.com/p/v8/source/browse/trunk/src/messages.js. The
22988// implementation of wrapCallSite() used to just forward to the actual source
22989// code of CallSite.prototype.toString but unfortunately a new release of V8
22990// did something to the prototype chain and broke the shim. The only fix I
22991// could find was copy/paste.
22992function CallSiteToString() {
22993 var fileName;
22994 var fileLocation = "";
22995 if (this.isNative()) {
22996 fileLocation = "native";
22997 } else {
22998 fileName = this.getScriptNameOrSourceURL();
22999 if (!fileName && this.isEval()) {
23000 fileLocation = this.getEvalOrigin();
23001 fileLocation += ", "; // Expecting source position to follow.
23002 }
23003
23004 if (fileName) {
23005 fileLocation += fileName;
23006 } else {
23007 // Source code does not originate from a file and is not native, but we
23008 // can still get the source position inside the source string, e.g. in
23009 // an eval string.
23010 fileLocation += "<anonymous>";
23011 }
23012 var lineNumber = this.getLineNumber();
23013 if (lineNumber != null) {
23014 fileLocation += ":" + lineNumber;
23015 var columnNumber = this.getColumnNumber();
23016 if (columnNumber) {
23017 fileLocation += ":" + columnNumber;
23018 }
23019 }
23020 }
23021
23022 var line = "";
23023 var functionName = this.getFunctionName();
23024 var addSuffix = true;
23025 var isConstructor = this.isConstructor();
23026 var isMethodCall = !(this.isToplevel() || isConstructor);
23027 if (isMethodCall) {
23028 var typeName = this.getTypeName();
23029 // Fixes shim to be backward compatable with Node v0 to v4
23030 if (typeName === "[object Object]") {
23031 typeName = "null";
23032 }
23033 var methodName = this.getMethodName();
23034 if (functionName) {
23035 if (typeName && functionName.indexOf(typeName) != 0) {
23036 line += typeName + ".";
23037 }
23038 line += functionName;
23039 if (methodName && functionName.indexOf("." + methodName) != functionName.length - methodName.length - 1) {
23040 line += " [as " + methodName + "]";
23041 }
23042 } else {
23043 line += typeName + "." + (methodName || "<anonymous>");
23044 }
23045 } else if (isConstructor) {
23046 line += "new " + (functionName || "<anonymous>");
23047 } else if (functionName) {
23048 line += functionName;
23049 } else {
23050 line += fileLocation;
23051 addSuffix = false;
23052 }
23053 if (addSuffix) {
23054 line += " (" + fileLocation + ")";
23055 }
23056 return line;
23057}
23058
23059function cloneCallSite(frame) {
23060 var object = {};
23061 Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) {
23062 object[name] = /^(?:is|get)/.test(name) ? function() { return frame[name].call(frame); } : frame[name];
23063 });
23064 object.toString = CallSiteToString;
23065 return object;
23066}
23067
23068function wrapCallSite(frame, state) {
23069 // provides interface backward compatibility
23070 if (state === undefined) {
23071 state = { nextPosition: null, curPosition: null };
23072 }
23073 if(frame.isNative()) {
23074 state.curPosition = null;
23075 return frame;
23076 }
23077
23078 // Most call sites will return the source file from getFileName(), but code
23079 // passed to eval() ending in "//# sourceURL=..." will return the source file
23080 // from getScriptNameOrSourceURL() instead
23081 var source = frame.getFileName() || frame.getScriptNameOrSourceURL();
23082 if (source) {
23083 var line = frame.getLineNumber();
23084 var column = frame.getColumnNumber() - 1;
23085
23086 // Fix position in Node where some (internal) code is prepended.
23087 // See https://github.com/evanw/node-source-map-support/issues/36
23088 // Header removed in node at ^10.16 || >=11.11.0
23089 // v11 is not an LTS candidate, we can just test the one version with it.
23090 // Test node versions for: 10.16-19, 10.20+, 12-19, 20-99, 100+, or 11.11
23091 var noHeader = /^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/;
23092 var headerLength = noHeader.test(process.version) ? 0 : 62;
23093 if (line === 1 && column > headerLength && !isInBrowser() && !frame.isEval()) {
23094 column -= headerLength;
23095 }
23096
23097 var position = mapSourcePosition({
23098 source: source,
23099 line: line,
23100 column: column
23101 });
23102 state.curPosition = position;
23103 frame = cloneCallSite(frame);
23104 var originalFunctionName = frame.getFunctionName;
23105 frame.getFunctionName = function() {
23106 if (state.nextPosition == null) {
23107 return originalFunctionName();
23108 }
23109 return state.nextPosition.name || originalFunctionName();
23110 };
23111 frame.getFileName = function() { return position.source; };
23112 frame.getLineNumber = function() { return position.line; };
23113 frame.getColumnNumber = function() { return position.column + 1; };
23114 frame.getScriptNameOrSourceURL = function() { return position.source; };
23115 return frame;
23116 }
23117
23118 // Code called using eval() needs special handling
23119 var origin = frame.isEval() && frame.getEvalOrigin();
23120 if (origin) {
23121 origin = mapEvalOrigin(origin);
23122 frame = cloneCallSite(frame);
23123 frame.getEvalOrigin = function() { return origin; };
23124 return frame;
23125 }
23126
23127 // If we get here then we were unable to change the source position
23128 return frame;
23129}
23130
23131// This function is part of the V8 stack trace API, for more info see:
23132// https://v8.dev/docs/stack-trace-api
23133function prepareStackTrace(error, stack) {
23134 if (emptyCacheBetweenOperations) {
23135 fileContentsCache = {};
23136 sourceMapCache = {};
23137 }
23138
23139 var name = error.name || 'Error';
23140 var message = error.message || '';
23141 var errorString = name + ": " + message;
23142
23143 var state = { nextPosition: null, curPosition: null };
23144 var processedStack = [];
23145 for (var i = stack.length - 1; i >= 0; i--) {
23146 processedStack.push('\n at ' + wrapCallSite(stack[i], state));
23147 state.nextPosition = state.curPosition;
23148 }
23149 state.curPosition = state.nextPosition = null;
23150 return errorString + processedStack.reverse().join('');
23151}
23152
23153// Generate position and snippet of original source with pointer
23154function getErrorSource(error) {
23155 var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack);
23156 if (match) {
23157 var source = match[1];
23158 var line = +match[2];
23159 var column = +match[3];
23160
23161 // Support the inline sourceContents inside the source map
23162 var contents = fileContentsCache[source];
23163
23164 // Support files on disk
23165 if (!contents && fs && fs.existsSync(source)) {
23166 try {
23167 contents = fs.readFileSync(source, 'utf8');
23168 } catch (er) {
23169 contents = '';
23170 }
23171 }
23172
23173 // Format the line from the original source code like node does
23174 if (contents) {
23175 var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1];
23176 if (code) {
23177 return source + ':' + line + '\n' + code + '\n' +
23178 new Array(column).join(' ') + '^';
23179 }
23180 }
23181 }
23182 return null;
23183}
23184
23185function printErrorAndExit (error) {
23186 var source = getErrorSource(error);
23187
23188 // Ensure error is printed synchronously and not truncated
23189 if (process.stderr._handle && process.stderr._handle.setBlocking) {
23190 process.stderr._handle.setBlocking(true);
23191 }
23192
23193 if (source) {
23194 console.error();
23195 console.error(source);
23196 }
23197
23198 console.error(error.stack);
23199 process.exit(1);
23200}
23201
23202function shimEmitUncaughtException () {
23203 var origEmit = process.emit;
23204
23205 process.emit = function (type) {
23206 if (type === 'uncaughtException') {
23207 var hasStack = (arguments[1] && arguments[1].stack);
23208 var hasListeners = (this.listeners(type).length > 0);
23209
23210 if (hasStack && !hasListeners) {
23211 return printErrorAndExit(arguments[1]);
23212 }
23213 }
23214
23215 return origEmit.apply(this, arguments);
23216 };
23217}
23218
23219var originalRetrieveFileHandlers = retrieveFileHandlers.slice(0);
23220var originalRetrieveMapHandlers = retrieveMapHandlers.slice(0);
23221
23222exports.wrapCallSite = wrapCallSite;
23223exports.getErrorSource = getErrorSource;
23224exports.mapSourcePosition = mapSourcePosition;
23225exports.retrieveSourceMap = retrieveSourceMap;
23226
23227exports.install = function(options) {
23228 options = options || {};
23229
23230 if (options.environment) {
23231 environment = options.environment;
23232 if (["node", "browser", "auto"].indexOf(environment) === -1) {
23233 throw new Error("environment " + environment + " was unknown. Available options are {auto, browser, node}")
23234 }
23235 }
23236
23237 // Allow sources to be found by methods other than reading the files
23238 // directly from disk.
23239 if (options.retrieveFile) {
23240 if (options.overrideRetrieveFile) {
23241 retrieveFileHandlers.length = 0;
23242 }
23243
23244 retrieveFileHandlers.unshift(options.retrieveFile);
23245 }
23246
23247 // Allow source maps to be found by methods other than reading the files
23248 // directly from disk.
23249 if (options.retrieveSourceMap) {
23250 if (options.overrideRetrieveSourceMap) {
23251 retrieveMapHandlers.length = 0;
23252 }
23253
23254 retrieveMapHandlers.unshift(options.retrieveSourceMap);
23255 }
23256
23257 // Support runtime transpilers that include inline source maps
23258 if (options.hookRequire && !isInBrowser()) {
23259 // Use dynamicRequire to avoid including in browser bundles
23260 var Module = dynamicRequire(module, 'module');
23261 var $compile = Module.prototype._compile;
23262
23263 if (!$compile.__sourceMapSupport) {
23264 Module.prototype._compile = function(content, filename) {
23265 fileContentsCache[filename] = content;
23266 sourceMapCache[filename] = undefined;
23267 return $compile.call(this, content, filename);
23268 };
23269
23270 Module.prototype._compile.__sourceMapSupport = true;
23271 }
23272 }
23273
23274 // Configure options
23275 if (!emptyCacheBetweenOperations) {
23276 emptyCacheBetweenOperations = 'emptyCacheBetweenOperations' in options ?
23277 options.emptyCacheBetweenOperations : false;
23278 }
23279
23280 // Install the error reformatter
23281 if (!errorFormatterInstalled) {
23282 errorFormatterInstalled = true;
23283 Error.prepareStackTrace = prepareStackTrace;
23284 }
23285
23286 if (!uncaughtShimInstalled) {
23287 var installHandler = 'handleUncaughtExceptions' in options ?
23288 options.handleUncaughtExceptions : true;
23289
23290 // Do not override 'uncaughtException' with our own handler in Node.js
23291 // Worker threads. Workers pass the error to the main thread as an event,
23292 // rather than printing something to stderr and exiting.
23293 try {
23294 // We need to use `dynamicRequire` because `require` on it's own will be optimized by WebPack/Browserify.
23295 var worker_threads = dynamicRequire(module, 'worker_threads');
23296 if (worker_threads.isMainThread === false) {
23297 installHandler = false;
23298 }
23299 } catch(e) {}
23300
23301 // Provide the option to not install the uncaught exception handler. This is
23302 // to support other uncaught exception handlers (in test frameworks, for
23303 // example). If this handler is not installed and there are no other uncaught
23304 // exception handlers, uncaught exceptions will be caught by node's built-in
23305 // exception handler and the process will still be terminated. However, the
23306 // generated JavaScript code will be shown above the stack trace instead of
23307 // the original source code.
23308 if (installHandler && hasGlobalProcessEventEmitter()) {
23309 uncaughtShimInstalled = true;
23310 shimEmitUncaughtException();
23311 }
23312 }
23313};
23314
23315exports.resetRetrieveHandlers = function() {
23316 retrieveFileHandlers.length = 0;
23317 retrieveMapHandlers.length = 0;
23318
23319 retrieveFileHandlers = originalRetrieveFileHandlers.slice(0);
23320 retrieveMapHandlers = originalRetrieveMapHandlers.slice(0);
23321
23322 retrieveSourceMap = handlerExec(retrieveMapHandlers);
23323 retrieveFile = handlerExec(retrieveFileHandlers);
23324};
23325}(sourceMapSupport, sourceMapSupport.exports));
23326
23327var makeError$2 = {exports: {}};
23328
23329(function (module, exports) {
23330
23331// ===================================================================
23332
23333var construct = typeof Reflect !== "undefined" ? Reflect.construct : undefined;
23334var defineProperty = Object.defineProperty;
23335
23336// -------------------------------------------------------------------
23337
23338var captureStackTrace = Error.captureStackTrace;
23339if (captureStackTrace === undefined) {
23340 captureStackTrace = function captureStackTrace(error) {
23341 var container = new Error();
23342
23343 defineProperty(error, "stack", {
23344 configurable: true,
23345 get: function getStack() {
23346 var stack = container.stack;
23347
23348 // Replace property with value for faster future accesses.
23349 defineProperty(this, "stack", {
23350 configurable: true,
23351 value: stack,
23352 writable: true,
23353 });
23354
23355 return stack;
23356 },
23357 set: function setStack(stack) {
23358 defineProperty(error, "stack", {
23359 configurable: true,
23360 value: stack,
23361 writable: true,
23362 });
23363 },
23364 });
23365 };
23366}
23367
23368// -------------------------------------------------------------------
23369
23370function BaseError(message) {
23371 if (message !== undefined) {
23372 defineProperty(this, "message", {
23373 configurable: true,
23374 value: message,
23375 writable: true,
23376 });
23377 }
23378
23379 var cname = this.constructor.name;
23380 if (cname !== undefined && cname !== this.name) {
23381 defineProperty(this, "name", {
23382 configurable: true,
23383 value: cname,
23384 writable: true,
23385 });
23386 }
23387
23388 captureStackTrace(this, this.constructor);
23389}
23390
23391BaseError.prototype = Object.create(Error.prototype, {
23392 // See: https://github.com/JsCommunity/make-error/issues/4
23393 constructor: {
23394 configurable: true,
23395 value: BaseError,
23396 writable: true,
23397 },
23398});
23399
23400// -------------------------------------------------------------------
23401
23402// Sets the name of a function if possible (depends of the JS engine).
23403var setFunctionName = (function() {
23404 function setFunctionName(fn, name) {
23405 return defineProperty(fn, "name", {
23406 configurable: true,
23407 value: name,
23408 });
23409 }
23410 try {
23411 var f = function() {};
23412 setFunctionName(f, "foo");
23413 if (f.name === "foo") {
23414 return setFunctionName;
23415 }
23416 } catch (_) {}
23417})();
23418
23419// -------------------------------------------------------------------
23420
23421function makeError(constructor, super_) {
23422 if (super_ == null || super_ === Error) {
23423 super_ = BaseError;
23424 } else if (typeof super_ !== "function") {
23425 throw new TypeError("super_ should be a function");
23426 }
23427
23428 var name;
23429 if (typeof constructor === "string") {
23430 name = constructor;
23431 constructor =
23432 construct !== undefined
23433 ? function() {
23434 return construct(super_, arguments, this.constructor);
23435 }
23436 : function() {
23437 super_.apply(this, arguments);
23438 };
23439
23440 // If the name can be set, do it once and for all.
23441 if (setFunctionName !== undefined) {
23442 setFunctionName(constructor, name);
23443 name = undefined;
23444 }
23445 } else if (typeof constructor !== "function") {
23446 throw new TypeError("constructor should be either a string or a function");
23447 }
23448
23449 // Also register the super constructor also as `constructor.super_` just
23450 // like Node's `util.inherits()`.
23451 //
23452 // eslint-disable-next-line dot-notation
23453 constructor.super_ = constructor["super"] = super_;
23454
23455 var properties = {
23456 constructor: {
23457 configurable: true,
23458 value: constructor,
23459 writable: true,
23460 },
23461 };
23462
23463 // If the name could not be set on the constructor, set it on the
23464 // prototype.
23465 if (name !== undefined) {
23466 properties.name = {
23467 configurable: true,
23468 value: name,
23469 writable: true,
23470 };
23471 }
23472 constructor.prototype = Object.create(super_.prototype, properties);
23473
23474 return constructor;
23475}
23476exports = module.exports = makeError;
23477exports.BaseError = BaseError;
23478}(makeError$2, makeError$2.exports));
23479
23480var util$1 = {};
23481
23482var yn$2 = {exports: {}};
23483
23484const YES_MATCH_SCORE_THRESHOLD = 2;
23485const NO_MATCH_SCORE_THRESHOLD = 1.25;
23486
23487const yMatch = new Map([
23488 [5, 0.25],
23489 [6, 0.25],
23490 [7, 0.25],
23491 ['t', 0.75],
23492 ['y', 1],
23493 ['u', 0.75],
23494 ['g', 0.25],
23495 ['h', 0.25],
23496 ['j', 0.25]
23497]);
23498
23499const eMatch = new Map([
23500 [2, 0.25],
23501 [3, 0.25],
23502 [4, 0.25],
23503 ['w', 0.75],
23504 ['e', 1],
23505 ['r', 0.75],
23506 ['s', 0.25],
23507 ['d', 0.25],
23508 ['f', 0.25]
23509]);
23510
23511const sMatch = new Map([
23512 ['q', 0.25],
23513 ['w', 0.25],
23514 ['e', 0.25],
23515 ['a', 0.75],
23516 ['s', 1],
23517 ['d', 0.75],
23518 ['z', 0.25],
23519 ['x', 0.25],
23520 ['c', 0.25]
23521]);
23522
23523const nMatch = new Map([
23524 ['h', 0.25],
23525 ['j', 0.25],
23526 ['k', 0.25],
23527 ['b', 0.75],
23528 ['n', 1],
23529 ['m', 0.75]
23530]);
23531
23532const oMatch = new Map([
23533 [9, 0.25],
23534 [0, 0.25],
23535 ['i', 0.75],
23536 ['o', 1],
23537 ['p', 0.75],
23538 ['k', 0.25],
23539 ['l', 0.25]
23540]);
23541
23542function getYesMatchScore(value) {
23543 const [y, e, s] = value;
23544 let score = 0;
23545
23546 if (yMatch.has(y)) {
23547 score += yMatch.get(y);
23548 }
23549
23550 if (eMatch.has(e)) {
23551 score += eMatch.get(e);
23552 }
23553
23554 if (sMatch.has(s)) {
23555 score += sMatch.get(s);
23556 }
23557
23558 return score;
23559}
23560
23561function getNoMatchScore(value) {
23562 const [n, o] = value;
23563 let score = 0;
23564
23565 if (nMatch.has(n)) {
23566 score += nMatch.get(n);
23567 }
23568
23569 if (oMatch.has(o)) {
23570 score += oMatch.get(o);
23571 }
23572
23573 return score;
23574}
23575
23576var lenient$1 = (input, options) => {
23577 if (getYesMatchScore(input) >= YES_MATCH_SCORE_THRESHOLD) {
23578 return true;
23579 }
23580
23581 if (getNoMatchScore(input) >= NO_MATCH_SCORE_THRESHOLD) {
23582 return false;
23583 }
23584
23585 return options.default;
23586};
23587
23588const lenient = lenient$1;
23589
23590const yn$1 = (input, options) => {
23591 input = String(input).trim();
23592
23593 options = Object.assign({
23594 lenient: false,
23595 default: null
23596 }, options);
23597
23598 if (options.default !== null && typeof options.default !== 'boolean') {
23599 throw new TypeError(`Expected the \`default\` option to be of type \`boolean\`, got \`${typeof options.default}\``);
23600 }
23601
23602 if (/^(?:y|yes|true|1)$/i.test(input)) {
23603 return true;
23604 }
23605
23606 if (/^(?:n|no|false|0)$/i.test(input)) {
23607 return false;
23608 }
23609
23610 if (options.lenient === true) {
23611 return lenient(input, options);
23612 }
23613
23614 return options.default;
23615};
23616
23617yn$2.exports = yn$1;
23618// TODO: Remove this for the next major release
23619yn$2.exports.default = yn$1;
23620
23621const nativeModule = require$$0__default$5;
23622const path$o = path__default;
23623const fs$m = fs__default;
23624
23625function createRequire (filename) {
23626 // Fallback to process.cwd() if no filename passed
23627 if (!filename) {
23628 filename = process.cwd();
23629 }
23630
23631 // If filename is dir, createRequire goes with parent directory, so we need fakepath
23632 if (isDir(filename)) {
23633 filename = path$o.join(filename, 'index.js');
23634 }
23635
23636 // Added in Node v12.2.0
23637 if (nativeModule.createRequire) {
23638 return nativeModule.createRequire(filename)
23639 }
23640
23641 // Added in Node v10.12.0 and deprecated since Node v12.2.0
23642 if (nativeModule.createRequireFromPath) {
23643 return nativeModule.createRequireFromPath(filename)
23644 }
23645
23646 // Polyfill
23647 return _createRequire(filename)
23648}
23649
23650// Polyfill
23651function _createRequire (filename) {
23652 const mod = new nativeModule.Module(filename, null);
23653 mod.filename = filename;
23654 mod.paths = nativeModule.Module._nodeModulePaths(path$o.dirname(filename));
23655 mod._compile('module.exports = require;', filename);
23656 return mod.exports
23657}
23658
23659function isDir (path) {
23660 try {
23661 const stat = fs$m.lstatSync(path);
23662 return stat.isDirectory()
23663 } catch (e) {
23664 // lstatSync throws an error if path doesn't exist
23665 return false
23666 }
23667}
23668
23669var createRequire_1 = createRequire;
23670
23671var _a;
23672Object.defineProperty(util$1, "__esModule", { value: true });
23673util$1.normalizeSlashes = util$1.parse = util$1.split = util$1.assign = util$1.yn = util$1.createRequire = void 0;
23674const module_1 = require$$0__default$5;
23675const ynModule = yn$2.exports;
23676/** @internal */
23677util$1.createRequire = (_a = module_1.createRequire !== null && module_1.createRequire !== void 0 ? module_1.createRequire : module_1.createRequireFromPath) !== null && _a !== void 0 ? _a : createRequire_1;
23678/**
23679 * Wrapper around yn module that returns `undefined` instead of `null`.
23680 * This is implemented by yn v4, but we're staying on v3 to avoid v4's node 10 requirement.
23681 * @internal
23682 */
23683function yn(value) {
23684 var _a;
23685 return (_a = ynModule(value)) !== null && _a !== void 0 ? _a : undefined;
23686}
23687util$1.yn = yn;
23688/**
23689 * Like `Object.assign`, but ignores `undefined` properties.
23690 *
23691 * @internal
23692 */
23693function assign(initialValue, ...sources) {
23694 for (const source of sources) {
23695 for (const key of Object.keys(source)) {
23696 const value = source[key];
23697 if (value !== undefined)
23698 initialValue[key] = value;
23699 }
23700 }
23701 return initialValue;
23702}
23703util$1.assign = assign;
23704/**
23705 * Split a string array of values.
23706 * @internal
23707 */
23708function split(value) {
23709 return typeof value === 'string' ? value.split(/ *, */g) : undefined;
23710}
23711util$1.split = split;
23712/**
23713 * Parse a string as JSON.
23714 * @internal
23715 */
23716function parse$f(value) {
23717 return typeof value === 'string' ? JSON.parse(value) : undefined;
23718}
23719util$1.parse = parse$f;
23720/**
23721 * Replace backslashes with forward slashes.
23722 * @internal
23723 */
23724function normalizeSlashes(value) {
23725 return value.replace(/\\/g, '/');
23726}
23727util$1.normalizeSlashes = normalizeSlashes;
23728
23729var configuration = {};
23730
23731var tsconfigs = {};
23732
23733var $schema$3 = "https://json.schemastore.org/tsconfig";
23734var display$3 = "Node 16";
23735var compilerOptions$3 = {
23736 lib: [
23737 "es2020"
23738 ],
23739 module: "commonjs",
23740 target: "es2020",
23741 strict: true,
23742 esModuleInterop: true,
23743 skipLibCheck: true,
23744 forceConsistentCasingInFileNames: true
23745};
23746var require$$0$4 = {
23747 $schema: $schema$3,
23748 display: display$3,
23749 compilerOptions: compilerOptions$3
23750};
23751
23752var $schema$2 = "https://json.schemastore.org/tsconfig";
23753var display$2 = "Node 14";
23754var compilerOptions$2 = {
23755 lib: [
23756 "es2020"
23757 ],
23758 module: "commonjs",
23759 target: "es2020",
23760 strict: true,
23761 esModuleInterop: true,
23762 skipLibCheck: true,
23763 forceConsistentCasingInFileNames: true
23764};
23765var require$$1$1 = {
23766 $schema: $schema$2,
23767 display: display$2,
23768 compilerOptions: compilerOptions$2
23769};
23770
23771var $schema$1 = "https://json.schemastore.org/tsconfig";
23772var display$1 = "Node 12";
23773var compilerOptions$1 = {
23774 lib: [
23775 "es2019",
23776 "es2020.promise",
23777 "es2020.bigint",
23778 "es2020.string"
23779 ],
23780 module: "commonjs",
23781 target: "es2019",
23782 strict: true,
23783 esModuleInterop: true,
23784 skipLibCheck: true,
23785 forceConsistentCasingInFileNames: true
23786};
23787var require$$2 = {
23788 $schema: $schema$1,
23789 display: display$1,
23790 compilerOptions: compilerOptions$1
23791};
23792
23793var $schema = "https://json.schemastore.org/tsconfig";
23794var display = "Node 10";
23795var compilerOptions = {
23796 lib: [
23797 "es2018"
23798 ],
23799 module: "commonjs",
23800 target: "es2018",
23801 strict: true,
23802 esModuleInterop: true,
23803 skipLibCheck: true,
23804 forceConsistentCasingInFileNames: true
23805};
23806var require$$3 = {
23807 $schema: $schema,
23808 display: display,
23809 compilerOptions: compilerOptions
23810};
23811
23812Object.defineProperty(tsconfigs, "__esModule", { value: true });
23813tsconfigs.getDefaultTsconfigJsonForNodeVersion = void 0;
23814const nodeMajor = parseInt(process.versions.node.split('.')[0], 10);
23815/**
23816 * return parsed JSON of the bundled @tsconfig/bases config appropriate for the
23817 * running version of nodejs
23818 * @internal
23819 */
23820function getDefaultTsconfigJsonForNodeVersion(ts) {
23821 const tsInternal = ts;
23822 if (nodeMajor >= 16) {
23823 const config = require$$0$4;
23824 if (configCompatible(config))
23825 return config;
23826 }
23827 if (nodeMajor >= 14) {
23828 const config = require$$1$1;
23829 if (configCompatible(config))
23830 return config;
23831 }
23832 if (nodeMajor >= 12) {
23833 const config = require$$2;
23834 if (configCompatible(config))
23835 return config;
23836 }
23837 return require$$3;
23838 // Verify that tsconfig target and lib options are compatible with TypeScript compiler
23839 function configCompatible(config) {
23840 return (typeof ts.ScriptTarget[config.compilerOptions.target.toUpperCase()] === 'number' &&
23841 tsInternal.libs &&
23842 config.compilerOptions.lib.every((lib) => tsInternal.libs.includes(lib)));
23843 }
23844}
23845tsconfigs.getDefaultTsconfigJsonForNodeVersion = getDefaultTsconfigJsonForNodeVersion;
23846
23847Object.defineProperty(configuration, "__esModule", { value: true });
23848configuration.readConfig = void 0;
23849const path_1 = path__default;
23850const index_1 = dist$1;
23851const tsconfigs_1 = tsconfigs;
23852const util_1 = util$1;
23853/**
23854 * TypeScript compiler option values required by `ts-node` which cannot be overridden.
23855 */
23856const TS_NODE_COMPILER_OPTIONS = {
23857 sourceMap: true,
23858 inlineSourceMap: false,
23859 inlineSources: true,
23860 declaration: false,
23861 noEmit: false,
23862 outDir: '.ts-node',
23863};
23864/*
23865 * Do post-processing on config options to support `ts-node`.
23866 */
23867function fixConfig(ts, config) {
23868 // Delete options that *should not* be passed through.
23869 delete config.options.out;
23870 delete config.options.outFile;
23871 delete config.options.composite;
23872 delete config.options.declarationDir;
23873 delete config.options.declarationMap;
23874 delete config.options.emitDeclarationOnly;
23875 // Target ES5 output by default (instead of ES3).
23876 if (config.options.target === undefined) {
23877 config.options.target = ts.ScriptTarget.ES5;
23878 }
23879 // Target CommonJS modules by default (instead of magically switching to ES6 when the target is ES6).
23880 if (config.options.module === undefined) {
23881 config.options.module = ts.ModuleKind.CommonJS;
23882 }
23883 return config;
23884}
23885/**
23886 * Load TypeScript configuration. Returns the parsed TypeScript config and
23887 * any `ts-node` options specified in the config file.
23888 *
23889 * Even when a tsconfig.json is not loaded, this function still handles merging
23890 * compilerOptions from various sources: API, environment variables, etc.
23891 *
23892 * @internal
23893 */
23894function readConfig(cwd, ts, rawApiOptions) {
23895 var _a, _b, _c;
23896 let config = { compilerOptions: {} };
23897 let basePath = cwd;
23898 let configFilePath = undefined;
23899 const projectSearchDir = path_1.resolve(cwd, (_a = rawApiOptions.projectSearchDir) !== null && _a !== void 0 ? _a : cwd);
23900 const { fileExists = ts.sys.fileExists, readFile = ts.sys.readFile, skipProject = index_1.DEFAULTS.skipProject, project = index_1.DEFAULTS.project, } = rawApiOptions;
23901 // Read project configuration when available.
23902 if (!skipProject) {
23903 configFilePath = project
23904 ? path_1.resolve(cwd, project)
23905 : ts.findConfigFile(projectSearchDir, fileExists);
23906 if (configFilePath) {
23907 const result = ts.readConfigFile(configFilePath, readFile);
23908 // Return diagnostics.
23909 if (result.error) {
23910 return {
23911 configFilePath,
23912 config: { errors: [result.error], fileNames: [], options: {} },
23913 tsNodeOptionsFromTsconfig: {},
23914 };
23915 }
23916 config = result.config;
23917 basePath = path_1.dirname(configFilePath);
23918 }
23919 }
23920 // Fix ts-node options that come from tsconfig.json
23921 const tsNodeOptionsFromTsconfig = Object.assign({}, filterRecognizedTsConfigTsNodeOptions(config['ts-node']));
23922 // Remove resolution of "files".
23923 const files = (_c = (_b = rawApiOptions.files) !== null && _b !== void 0 ? _b : tsNodeOptionsFromTsconfig.files) !== null && _c !== void 0 ? _c : index_1.DEFAULTS.files;
23924 if (!files) {
23925 config.files = [];
23926 config.include = [];
23927 }
23928 // Only if a config file is *not* loaded, load an implicit configuration from @tsconfig/bases
23929 const skipDefaultCompilerOptions = configFilePath != null;
23930 const defaultCompilerOptionsForNodeVersion = skipDefaultCompilerOptions
23931 ? undefined
23932 : Object.assign(Object.assign({}, tsconfigs_1.getDefaultTsconfigJsonForNodeVersion(ts).compilerOptions), { types: ['node'] });
23933 // Merge compilerOptions from all sources
23934 config.compilerOptions = Object.assign({},
23935 // automatically-applied options from @tsconfig/bases
23936 defaultCompilerOptionsForNodeVersion,
23937 // tsconfig.json "compilerOptions"
23938 config.compilerOptions,
23939 // from env var
23940 index_1.DEFAULTS.compilerOptions,
23941 // tsconfig.json "ts-node": "compilerOptions"
23942 tsNodeOptionsFromTsconfig.compilerOptions,
23943 // passed programmatically
23944 rawApiOptions.compilerOptions,
23945 // overrides required by ts-node, cannot be changed
23946 TS_NODE_COMPILER_OPTIONS);
23947 const fixedConfig = fixConfig(ts, ts.parseJsonConfigFileContent(config, {
23948 fileExists,
23949 readFile,
23950 readDirectory: ts.sys.readDirectory,
23951 useCaseSensitiveFileNames: ts.sys.useCaseSensitiveFileNames,
23952 }, basePath, undefined, configFilePath));
23953 if (tsNodeOptionsFromTsconfig.require) {
23954 // Modules are found relative to the tsconfig file, not the `dir` option
23955 const tsconfigRelativeRequire = util_1.createRequire(configFilePath);
23956 tsNodeOptionsFromTsconfig.require = tsNodeOptionsFromTsconfig.require.map((path) => {
23957 return tsconfigRelativeRequire.resolve(path);
23958 });
23959 }
23960 return { configFilePath, config: fixedConfig, tsNodeOptionsFromTsconfig };
23961}
23962configuration.readConfig = readConfig;
23963/**
23964 * Given the raw "ts-node" sub-object from a tsconfig, return an object with only the properties
23965 * recognized by "ts-node"
23966 */
23967function filterRecognizedTsConfigTsNodeOptions(jsonObject) {
23968 if (jsonObject == null)
23969 return jsonObject;
23970 const { compiler, compilerHost, compilerOptions, emit, files, ignore, ignoreDiagnostics, logError, preferTsExts, pretty, require, skipIgnore, transpileOnly, typeCheck, transpiler, } = jsonObject;
23971 const filteredTsConfigOptions = {
23972 compiler,
23973 compilerHost,
23974 compilerOptions,
23975 emit,
23976 files,
23977 ignore,
23978 ignoreDiagnostics,
23979 logError,
23980 preferTsExts,
23981 pretty,
23982 require,
23983 skipIgnore,
23984 transpileOnly,
23985 typeCheck,
23986 transpiler,
23987 };
23988 return filteredTsConfigOptions;
23989}
23990
23991var repl = {};
23992
23993function Diff() {}
23994Diff.prototype = {
23995 diff: function diff(oldString, newString) {
23996 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
23997 var callback = options.callback;
23998
23999 if (typeof options === 'function') {
24000 callback = options;
24001 options = {};
24002 }
24003
24004 this.options = options;
24005 var self = this;
24006
24007 function done(value) {
24008 if (callback) {
24009 setTimeout(function () {
24010 callback(undefined, value);
24011 }, 0);
24012 return true;
24013 } else {
24014 return value;
24015 }
24016 } // Allow subclasses to massage the input prior to running
24017
24018
24019 oldString = this.castInput(oldString);
24020 newString = this.castInput(newString);
24021 oldString = this.removeEmpty(this.tokenize(oldString));
24022 newString = this.removeEmpty(this.tokenize(newString));
24023 var newLen = newString.length,
24024 oldLen = oldString.length;
24025 var editLength = 1;
24026 var maxEditLength = newLen + oldLen;
24027 var bestPath = [{
24028 newPos: -1,
24029 components: []
24030 }]; // Seed editLength = 0, i.e. the content starts with the same values
24031
24032 var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
24033
24034 if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
24035 // Identity per the equality and tokenizer
24036 return done([{
24037 value: this.join(newString),
24038 count: newString.length
24039 }]);
24040 } // Main worker method. checks all permutations of a given edit length for acceptance.
24041
24042
24043 function execEditLength() {
24044 for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
24045 var basePath = void 0;
24046
24047 var addPath = bestPath[diagonalPath - 1],
24048 removePath = bestPath[diagonalPath + 1],
24049 _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
24050
24051 if (addPath) {
24052 // No one else is going to attempt to use this value, clear it
24053 bestPath[diagonalPath - 1] = undefined;
24054 }
24055
24056 var canAdd = addPath && addPath.newPos + 1 < newLen,
24057 canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen;
24058
24059 if (!canAdd && !canRemove) {
24060 // If this path is a terminal then prune
24061 bestPath[diagonalPath] = undefined;
24062 continue;
24063 } // Select the diagonal that we want to branch from. We select the prior
24064 // path whose position in the new string is the farthest from the origin
24065 // and does not pass the bounds of the diff graph
24066
24067
24068 if (!canAdd || canRemove && addPath.newPos < removePath.newPos) {
24069 basePath = clonePath(removePath);
24070 self.pushComponent(basePath.components, undefined, true);
24071 } else {
24072 basePath = addPath; // No need to clone, we've pulled it from the list
24073
24074 basePath.newPos++;
24075 self.pushComponent(basePath.components, true, undefined);
24076 }
24077
24078 _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done
24079
24080 if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {
24081 return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken));
24082 } else {
24083 // Otherwise track this path as a potential candidate and continue.
24084 bestPath[diagonalPath] = basePath;
24085 }
24086 }
24087
24088 editLength++;
24089 } // Performs the length of edit iteration. Is a bit fugly as this has to support the
24090 // sync and async mode which is never fun. Loops over execEditLength until a value
24091 // is produced.
24092
24093
24094 if (callback) {
24095 (function exec() {
24096 setTimeout(function () {
24097 // This should not happen, but we want to be safe.
24098
24099 /* istanbul ignore next */
24100 if (editLength > maxEditLength) {
24101 return callback();
24102 }
24103
24104 if (!execEditLength()) {
24105 exec();
24106 }
24107 }, 0);
24108 })();
24109 } else {
24110 while (editLength <= maxEditLength) {
24111 var ret = execEditLength();
24112
24113 if (ret) {
24114 return ret;
24115 }
24116 }
24117 }
24118 },
24119 pushComponent: function pushComponent(components, added, removed) {
24120 var last = components[components.length - 1];
24121
24122 if (last && last.added === added && last.removed === removed) {
24123 // We need to clone here as the component clone operation is just
24124 // as shallow array clone
24125 components[components.length - 1] = {
24126 count: last.count + 1,
24127 added: added,
24128 removed: removed
24129 };
24130 } else {
24131 components.push({
24132 count: 1,
24133 added: added,
24134 removed: removed
24135 });
24136 }
24137 },
24138 extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {
24139 var newLen = newString.length,
24140 oldLen = oldString.length,
24141 newPos = basePath.newPos,
24142 oldPos = newPos - diagonalPath,
24143 commonCount = 0;
24144
24145 while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
24146 newPos++;
24147 oldPos++;
24148 commonCount++;
24149 }
24150
24151 if (commonCount) {
24152 basePath.components.push({
24153 count: commonCount
24154 });
24155 }
24156
24157 basePath.newPos = newPos;
24158 return oldPos;
24159 },
24160 equals: function equals(left, right) {
24161 if (this.options.comparator) {
24162 return this.options.comparator(left, right);
24163 } else {
24164 return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase();
24165 }
24166 },
24167 removeEmpty: function removeEmpty(array) {
24168 var ret = [];
24169
24170 for (var i = 0; i < array.length; i++) {
24171 if (array[i]) {
24172 ret.push(array[i]);
24173 }
24174 }
24175
24176 return ret;
24177 },
24178 castInput: function castInput(value) {
24179 return value;
24180 },
24181 tokenize: function tokenize(value) {
24182 return value.split('');
24183 },
24184 join: function join(chars) {
24185 return chars.join('');
24186 }
24187};
24188
24189function buildValues(diff, components, newString, oldString, useLongestToken) {
24190 var componentPos = 0,
24191 componentLen = components.length,
24192 newPos = 0,
24193 oldPos = 0;
24194
24195 for (; componentPos < componentLen; componentPos++) {
24196 var component = components[componentPos];
24197
24198 if (!component.removed) {
24199 if (!component.added && useLongestToken) {
24200 var value = newString.slice(newPos, newPos + component.count);
24201 value = value.map(function (value, i) {
24202 var oldValue = oldString[oldPos + i];
24203 return oldValue.length > value.length ? oldValue : value;
24204 });
24205 component.value = diff.join(value);
24206 } else {
24207 component.value = diff.join(newString.slice(newPos, newPos + component.count));
24208 }
24209
24210 newPos += component.count; // Common case
24211
24212 if (!component.added) {
24213 oldPos += component.count;
24214 }
24215 } else {
24216 component.value = diff.join(oldString.slice(oldPos, oldPos + component.count));
24217 oldPos += component.count; // Reverse add and remove so removes are output first to match common convention
24218 // The diffing algorithm is tied to add then remove output and this is the simplest
24219 // route to get the desired output with minimal overhead.
24220
24221 if (componentPos && components[componentPos - 1].added) {
24222 var tmp = components[componentPos - 1];
24223 components[componentPos - 1] = components[componentPos];
24224 components[componentPos] = tmp;
24225 }
24226 }
24227 } // Special case handle for when one terminal is ignored (i.e. whitespace).
24228 // For this case we merge the terminal into the prior string and drop the change.
24229 // This is only available for string mode.
24230
24231
24232 var lastComponent = components[componentLen - 1];
24233
24234 if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) {
24235 components[componentLen - 2].value += lastComponent.value;
24236 components.pop();
24237 }
24238
24239 return components;
24240}
24241
24242function clonePath(path) {
24243 return {
24244 newPos: path.newPos,
24245 components: path.components.slice(0)
24246 };
24247}
24248
24249var characterDiff = new Diff();
24250function diffChars(oldStr, newStr, options) {
24251 return characterDiff.diff(oldStr, newStr, options);
24252}
24253
24254function generateOptions(options, defaults) {
24255 if (typeof options === 'function') {
24256 defaults.callback = options;
24257 } else if (options) {
24258 for (var name in options) {
24259 /* istanbul ignore else */
24260 if (options.hasOwnProperty(name)) {
24261 defaults[name] = options[name];
24262 }
24263 }
24264 }
24265
24266 return defaults;
24267}
24268
24269//
24270// Ranges and exceptions:
24271// Latin-1 Supplement, 0080–00FF
24272// - U+00D7 × Multiplication sign
24273// - U+00F7 ÷ Division sign
24274// Latin Extended-A, 0100–017F
24275// Latin Extended-B, 0180–024F
24276// IPA Extensions, 0250–02AF
24277// Spacing Modifier Letters, 02B0–02FF
24278// - U+02C7 ˇ &#711; Caron
24279// - U+02D8 ˘ &#728; Breve
24280// - U+02D9 ˙ &#729; Dot Above
24281// - U+02DA ˚ &#730; Ring Above
24282// - U+02DB ˛ &#731; Ogonek
24283// - U+02DC ˜ &#732; Small Tilde
24284// - U+02DD ˝ &#733; Double Acute Accent
24285// Latin Extended Additional, 1E00–1EFF
24286
24287var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/;
24288var reWhitespace = /\S/;
24289var wordDiff = new Diff();
24290
24291wordDiff.equals = function (left, right) {
24292 if (this.options.ignoreCase) {
24293 left = left.toLowerCase();
24294 right = right.toLowerCase();
24295 }
24296
24297 return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right);
24298};
24299
24300wordDiff.tokenize = function (value) {
24301 var tokens = value.split(/(\s+|[()[\]{}'"]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set.
24302
24303 for (var i = 0; i < tokens.length - 1; i++) {
24304 // If we have an empty string in the next field and we have only word chars before and after, merge
24305 if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) {
24306 tokens[i] += tokens[i + 2];
24307 tokens.splice(i + 1, 2);
24308 i--;
24309 }
24310 }
24311
24312 return tokens;
24313};
24314
24315function diffWords(oldStr, newStr, options) {
24316 options = generateOptions(options, {
24317 ignoreWhitespace: true
24318 });
24319 return wordDiff.diff(oldStr, newStr, options);
24320}
24321function diffWordsWithSpace(oldStr, newStr, options) {
24322 return wordDiff.diff(oldStr, newStr, options);
24323}
24324
24325var lineDiff = new Diff();
24326
24327lineDiff.tokenize = function (value) {
24328 var retLines = [],
24329 linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line
24330
24331 if (!linesAndNewlines[linesAndNewlines.length - 1]) {
24332 linesAndNewlines.pop();
24333 } // Merge the content and line separators into single tokens
24334
24335
24336 for (var i = 0; i < linesAndNewlines.length; i++) {
24337 var line = linesAndNewlines[i];
24338
24339 if (i % 2 && !this.options.newlineIsToken) {
24340 retLines[retLines.length - 1] += line;
24341 } else {
24342 if (this.options.ignoreWhitespace) {
24343 line = line.trim();
24344 }
24345
24346 retLines.push(line);
24347 }
24348 }
24349
24350 return retLines;
24351};
24352
24353function diffLines(oldStr, newStr, callback) {
24354 return lineDiff.diff(oldStr, newStr, callback);
24355}
24356function diffTrimmedLines(oldStr, newStr, callback) {
24357 var options = generateOptions(callback, {
24358 ignoreWhitespace: true
24359 });
24360 return lineDiff.diff(oldStr, newStr, options);
24361}
24362
24363var sentenceDiff = new Diff();
24364
24365sentenceDiff.tokenize = function (value) {
24366 return value.split(/(\S.+?[.!?])(?=\s+|$)/);
24367};
24368
24369function diffSentences(oldStr, newStr, callback) {
24370 return sentenceDiff.diff(oldStr, newStr, callback);
24371}
24372
24373var cssDiff = new Diff();
24374
24375cssDiff.tokenize = function (value) {
24376 return value.split(/([{}:;,]|\s+)/);
24377};
24378
24379function diffCss(oldStr, newStr, callback) {
24380 return cssDiff.diff(oldStr, newStr, callback);
24381}
24382
24383function _typeof(obj) {
24384 if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
24385 _typeof = function (obj) {
24386 return typeof obj;
24387 };
24388 } else {
24389 _typeof = function (obj) {
24390 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
24391 };
24392 }
24393
24394 return _typeof(obj);
24395}
24396
24397function _toConsumableArray(arr) {
24398 return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
24399}
24400
24401function _arrayWithoutHoles(arr) {
24402 if (Array.isArray(arr)) {
24403 for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
24404
24405 return arr2;
24406 }
24407}
24408
24409function _iterableToArray(iter) {
24410 if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
24411}
24412
24413function _nonIterableSpread() {
24414 throw new TypeError("Invalid attempt to spread non-iterable instance");
24415}
24416
24417var objectPrototypeToString = Object.prototype.toString;
24418var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a
24419// dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:
24420
24421jsonDiff.useLongestToken = true;
24422jsonDiff.tokenize = lineDiff.tokenize;
24423
24424jsonDiff.castInput = function (value) {
24425 var _this$options = this.options,
24426 undefinedReplacement = _this$options.undefinedReplacement,
24427 _this$options$stringi = _this$options.stringifyReplacer,
24428 stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) {
24429 return typeof v === 'undefined' ? undefinedReplacement : v;
24430 } : _this$options$stringi;
24431 return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' ');
24432};
24433
24434jsonDiff.equals = function (left, right) {
24435 return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'));
24436};
24437
24438function diffJson(oldObj, newObj, options) {
24439 return jsonDiff.diff(oldObj, newObj, options);
24440} // This function handles the presence of circular references by bailing out when encountering an
24441// object that is already on the "stack" of items being processed. Accepts an optional replacer
24442
24443function canonicalize(obj, stack, replacementStack, replacer, key) {
24444 stack = stack || [];
24445 replacementStack = replacementStack || [];
24446
24447 if (replacer) {
24448 obj = replacer(key, obj);
24449 }
24450
24451 var i;
24452
24453 for (i = 0; i < stack.length; i += 1) {
24454 if (stack[i] === obj) {
24455 return replacementStack[i];
24456 }
24457 }
24458
24459 var canonicalizedObj;
24460
24461 if ('[object Array]' === objectPrototypeToString.call(obj)) {
24462 stack.push(obj);
24463 canonicalizedObj = new Array(obj.length);
24464 replacementStack.push(canonicalizedObj);
24465
24466 for (i = 0; i < obj.length; i += 1) {
24467 canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key);
24468 }
24469
24470 stack.pop();
24471 replacementStack.pop();
24472 return canonicalizedObj;
24473 }
24474
24475 if (obj && obj.toJSON) {
24476 obj = obj.toJSON();
24477 }
24478
24479 if (_typeof(obj) === 'object' && obj !== null) {
24480 stack.push(obj);
24481 canonicalizedObj = {};
24482 replacementStack.push(canonicalizedObj);
24483
24484 var sortedKeys = [],
24485 _key;
24486
24487 for (_key in obj) {
24488 /* istanbul ignore else */
24489 if (obj.hasOwnProperty(_key)) {
24490 sortedKeys.push(_key);
24491 }
24492 }
24493
24494 sortedKeys.sort();
24495
24496 for (i = 0; i < sortedKeys.length; i += 1) {
24497 _key = sortedKeys[i];
24498 canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);
24499 }
24500
24501 stack.pop();
24502 replacementStack.pop();
24503 } else {
24504 canonicalizedObj = obj;
24505 }
24506
24507 return canonicalizedObj;
24508}
24509
24510var arrayDiff = new Diff();
24511
24512arrayDiff.tokenize = function (value) {
24513 return value.slice();
24514};
24515
24516arrayDiff.join = arrayDiff.removeEmpty = function (value) {
24517 return value;
24518};
24519
24520function diffArrays(oldArr, newArr, callback) {
24521 return arrayDiff.diff(oldArr, newArr, callback);
24522}
24523
24524function parsePatch(uniDiff) {
24525 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
24526 var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/),
24527 delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [],
24528 list = [],
24529 i = 0;
24530
24531 function parseIndex() {
24532 var index = {};
24533 list.push(index); // Parse diff metadata
24534
24535 while (i < diffstr.length) {
24536 var line = diffstr[i]; // File header found, end parsing diff metadata
24537
24538 if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) {
24539 break;
24540 } // Diff index
24541
24542
24543 var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line);
24544
24545 if (header) {
24546 index.index = header[1];
24547 }
24548
24549 i++;
24550 } // Parse file headers if they are defined. Unified diff requires them, but
24551 // there's no technical issues to have an isolated hunk without file header
24552
24553
24554 parseFileHeader(index);
24555 parseFileHeader(index); // Parse hunks
24556
24557 index.hunks = [];
24558
24559 while (i < diffstr.length) {
24560 var _line = diffstr[i];
24561
24562 if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) {
24563 break;
24564 } else if (/^@@/.test(_line)) {
24565 index.hunks.push(parseHunk());
24566 } else if (_line && options.strict) {
24567 // Ignore unexpected content unless in strict mode
24568 throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line));
24569 } else {
24570 i++;
24571 }
24572 }
24573 } // Parses the --- and +++ headers, if none are found, no lines
24574 // are consumed.
24575
24576
24577 function parseFileHeader(index) {
24578 var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]);
24579
24580 if (fileHeader) {
24581 var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new';
24582 var data = fileHeader[2].split('\t', 2);
24583 var fileName = data[0].replace(/\\\\/g, '\\');
24584
24585 if (/^".*"$/.test(fileName)) {
24586 fileName = fileName.substr(1, fileName.length - 2);
24587 }
24588
24589 index[keyPrefix + 'FileName'] = fileName;
24590 index[keyPrefix + 'Header'] = (data[1] || '').trim();
24591 i++;
24592 }
24593 } // Parses a hunk
24594 // This assumes that we are at the start of a hunk.
24595
24596
24597 function parseHunk() {
24598 var chunkHeaderIndex = i,
24599 chunkHeaderLine = diffstr[i++],
24600 chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
24601 var hunk = {
24602 oldStart: +chunkHeader[1],
24603 oldLines: +chunkHeader[2] || 1,
24604 newStart: +chunkHeader[3],
24605 newLines: +chunkHeader[4] || 1,
24606 lines: [],
24607 linedelimiters: []
24608 };
24609 var addCount = 0,
24610 removeCount = 0;
24611
24612 for (; i < diffstr.length; i++) {
24613 // Lines starting with '---' could be mistaken for the "remove line" operation
24614 // But they could be the header for the next file. Therefore prune such cases out.
24615 if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) {
24616 break;
24617 }
24618
24619 var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0];
24620
24621 if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') {
24622 hunk.lines.push(diffstr[i]);
24623 hunk.linedelimiters.push(delimiters[i] || '\n');
24624
24625 if (operation === '+') {
24626 addCount++;
24627 } else if (operation === '-') {
24628 removeCount++;
24629 } else if (operation === ' ') {
24630 addCount++;
24631 removeCount++;
24632 }
24633 } else {
24634 break;
24635 }
24636 } // Handle the empty block count case
24637
24638
24639 if (!addCount && hunk.newLines === 1) {
24640 hunk.newLines = 0;
24641 }
24642
24643 if (!removeCount && hunk.oldLines === 1) {
24644 hunk.oldLines = 0;
24645 } // Perform optional sanity checking
24646
24647
24648 if (options.strict) {
24649 if (addCount !== hunk.newLines) {
24650 throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
24651 }
24652
24653 if (removeCount !== hunk.oldLines) {
24654 throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
24655 }
24656 }
24657
24658 return hunk;
24659 }
24660
24661 while (i < diffstr.length) {
24662 parseIndex();
24663 }
24664
24665 return list;
24666}
24667
24668// Iterator that traverses in the range of [min, max], stepping
24669// by distance from a given start position. I.e. for [0, 4], with
24670// start of 2, this will iterate 2, 3, 1, 4, 0.
24671function distanceIterator (start, minLine, maxLine) {
24672 var wantForward = true,
24673 backwardExhausted = false,
24674 forwardExhausted = false,
24675 localOffset = 1;
24676 return function iterator() {
24677 if (wantForward && !forwardExhausted) {
24678 if (backwardExhausted) {
24679 localOffset++;
24680 } else {
24681 wantForward = false;
24682 } // Check if trying to fit beyond text length, and if not, check it fits
24683 // after offset location (or desired location on first iteration)
24684
24685
24686 if (start + localOffset <= maxLine) {
24687 return localOffset;
24688 }
24689
24690 forwardExhausted = true;
24691 }
24692
24693 if (!backwardExhausted) {
24694 if (!forwardExhausted) {
24695 wantForward = true;
24696 } // Check if trying to fit before text beginning, and if not, check it fits
24697 // before offset location
24698
24699
24700 if (minLine <= start - localOffset) {
24701 return -localOffset++;
24702 }
24703
24704 backwardExhausted = true;
24705 return iterator();
24706 } // We tried to fit hunk before text beginning and beyond text length, then
24707 // hunk can't fit on the text. Return undefined
24708
24709 };
24710}
24711
24712function applyPatch(source, uniDiff) {
24713 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
24714
24715 if (typeof uniDiff === 'string') {
24716 uniDiff = parsePatch(uniDiff);
24717 }
24718
24719 if (Array.isArray(uniDiff)) {
24720 if (uniDiff.length > 1) {
24721 throw new Error('applyPatch only works with a single input.');
24722 }
24723
24724 uniDiff = uniDiff[0];
24725 } // Apply the diff to the input
24726
24727
24728 var lines = source.split(/\r\n|[\n\v\f\r\x85]/),
24729 delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [],
24730 hunks = uniDiff.hunks,
24731 compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) {
24732 return line === patchContent;
24733 },
24734 errorCount = 0,
24735 fuzzFactor = options.fuzzFactor || 0,
24736 minLine = 0,
24737 offset = 0,
24738 removeEOFNL,
24739 addEOFNL;
24740 /**
24741 * Checks if the hunk exactly fits on the provided location
24742 */
24743
24744
24745 function hunkFits(hunk, toPos) {
24746 for (var j = 0; j < hunk.lines.length; j++) {
24747 var line = hunk.lines[j],
24748 operation = line.length > 0 ? line[0] : ' ',
24749 content = line.length > 0 ? line.substr(1) : line;
24750
24751 if (operation === ' ' || operation === '-') {
24752 // Context sanity check
24753 if (!compareLine(toPos + 1, lines[toPos], operation, content)) {
24754 errorCount++;
24755
24756 if (errorCount > fuzzFactor) {
24757 return false;
24758 }
24759 }
24760
24761 toPos++;
24762 }
24763 }
24764
24765 return true;
24766 } // Search best fit offsets for each hunk based on the previous ones
24767
24768
24769 for (var i = 0; i < hunks.length; i++) {
24770 var hunk = hunks[i],
24771 maxLine = lines.length - hunk.oldLines,
24772 localOffset = 0,
24773 toPos = offset + hunk.oldStart - 1;
24774 var iterator = distanceIterator(toPos, minLine, maxLine);
24775
24776 for (; localOffset !== undefined; localOffset = iterator()) {
24777 if (hunkFits(hunk, toPos + localOffset)) {
24778 hunk.offset = offset += localOffset;
24779 break;
24780 }
24781 }
24782
24783 if (localOffset === undefined) {
24784 return false;
24785 } // Set lower text limit to end of the current hunk, so next ones don't try
24786 // to fit over already patched text
24787
24788
24789 minLine = hunk.offset + hunk.oldStart + hunk.oldLines;
24790 } // Apply patch hunks
24791
24792
24793 var diffOffset = 0;
24794
24795 for (var _i = 0; _i < hunks.length; _i++) {
24796 var _hunk = hunks[_i],
24797 _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1;
24798
24799 diffOffset += _hunk.newLines - _hunk.oldLines;
24800
24801 if (_toPos < 0) {
24802 // Creating a new file
24803 _toPos = 0;
24804 }
24805
24806 for (var j = 0; j < _hunk.lines.length; j++) {
24807 var line = _hunk.lines[j],
24808 operation = line.length > 0 ? line[0] : ' ',
24809 content = line.length > 0 ? line.substr(1) : line,
24810 delimiter = _hunk.linedelimiters[j];
24811
24812 if (operation === ' ') {
24813 _toPos++;
24814 } else if (operation === '-') {
24815 lines.splice(_toPos, 1);
24816 delimiters.splice(_toPos, 1);
24817 /* istanbul ignore else */
24818 } else if (operation === '+') {
24819 lines.splice(_toPos, 0, content);
24820 delimiters.splice(_toPos, 0, delimiter);
24821 _toPos++;
24822 } else if (operation === '\\') {
24823 var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null;
24824
24825 if (previousOperation === '+') {
24826 removeEOFNL = true;
24827 } else if (previousOperation === '-') {
24828 addEOFNL = true;
24829 }
24830 }
24831 }
24832 } // Handle EOFNL insertion/removal
24833
24834
24835 if (removeEOFNL) {
24836 while (!lines[lines.length - 1]) {
24837 lines.pop();
24838 delimiters.pop();
24839 }
24840 } else if (addEOFNL) {
24841 lines.push('');
24842 delimiters.push('\n');
24843 }
24844
24845 for (var _k = 0; _k < lines.length - 1; _k++) {
24846 lines[_k] = lines[_k] + delimiters[_k];
24847 }
24848
24849 return lines.join('');
24850} // Wrapper that supports multiple file patches via callbacks.
24851
24852function applyPatches(uniDiff, options) {
24853 if (typeof uniDiff === 'string') {
24854 uniDiff = parsePatch(uniDiff);
24855 }
24856
24857 var currentIndex = 0;
24858
24859 function processIndex() {
24860 var index = uniDiff[currentIndex++];
24861
24862 if (!index) {
24863 return options.complete();
24864 }
24865
24866 options.loadFile(index, function (err, data) {
24867 if (err) {
24868 return options.complete(err);
24869 }
24870
24871 var updatedContent = applyPatch(data, index, options);
24872 options.patched(index, updatedContent, function (err) {
24873 if (err) {
24874 return options.complete(err);
24875 }
24876
24877 processIndex();
24878 });
24879 });
24880 }
24881
24882 processIndex();
24883}
24884
24885function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
24886 if (!options) {
24887 options = {};
24888 }
24889
24890 if (typeof options.context === 'undefined') {
24891 options.context = 4;
24892 }
24893
24894 var diff = diffLines(oldStr, newStr, options);
24895 diff.push({
24896 value: '',
24897 lines: []
24898 }); // Append an empty value to make cleanup easier
24899
24900 function contextLines(lines) {
24901 return lines.map(function (entry) {
24902 return ' ' + entry;
24903 });
24904 }
24905
24906 var hunks = [];
24907 var oldRangeStart = 0,
24908 newRangeStart = 0,
24909 curRange = [],
24910 oldLine = 1,
24911 newLine = 1;
24912
24913 var _loop = function _loop(i) {
24914 var current = diff[i],
24915 lines = current.lines || current.value.replace(/\n$/, '').split('\n');
24916 current.lines = lines;
24917
24918 if (current.added || current.removed) {
24919 var _curRange;
24920
24921 // If we have previous context, start with that
24922 if (!oldRangeStart) {
24923 var prev = diff[i - 1];
24924 oldRangeStart = oldLine;
24925 newRangeStart = newLine;
24926
24927 if (prev) {
24928 curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : [];
24929 oldRangeStart -= curRange.length;
24930 newRangeStart -= curRange.length;
24931 }
24932 } // Output our changes
24933
24934
24935 (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) {
24936 return (current.added ? '+' : '-') + entry;
24937 }))); // Track the updated file position
24938
24939
24940 if (current.added) {
24941 newLine += lines.length;
24942 } else {
24943 oldLine += lines.length;
24944 }
24945 } else {
24946 // Identical context lines. Track line changes
24947 if (oldRangeStart) {
24948 // Close out any changes that have been output (or join overlapping)
24949 if (lines.length <= options.context * 2 && i < diff.length - 2) {
24950 var _curRange2;
24951
24952 // Overlapping
24953 (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines)));
24954 } else {
24955 var _curRange3;
24956
24957 // end the range and output
24958 var contextSize = Math.min(lines.length, options.context);
24959
24960 (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize))));
24961
24962 var hunk = {
24963 oldStart: oldRangeStart,
24964 oldLines: oldLine - oldRangeStart + contextSize,
24965 newStart: newRangeStart,
24966 newLines: newLine - newRangeStart + contextSize,
24967 lines: curRange
24968 };
24969
24970 if (i >= diff.length - 2 && lines.length <= options.context) {
24971 // EOF is inside this hunk
24972 var oldEOFNewline = /\n$/.test(oldStr);
24973 var newEOFNewline = /\n$/.test(newStr);
24974 var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines;
24975
24976 if (!oldEOFNewline && noNlBeforeAdds) {
24977 // special case: old has no eol and no trailing context; no-nl can end up before adds
24978 curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file');
24979 }
24980
24981 if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) {
24982 curRange.push('\\ No newline at end of file');
24983 }
24984 }
24985
24986 hunks.push(hunk);
24987 oldRangeStart = 0;
24988 newRangeStart = 0;
24989 curRange = [];
24990 }
24991 }
24992
24993 oldLine += lines.length;
24994 newLine += lines.length;
24995 }
24996 };
24997
24998 for (var i = 0; i < diff.length; i++) {
24999 _loop(i);
25000 }
25001
25002 return {
25003 oldFileName: oldFileName,
25004 newFileName: newFileName,
25005 oldHeader: oldHeader,
25006 newHeader: newHeader,
25007 hunks: hunks
25008 };
25009}
25010function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
25011 var diff = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options);
25012 var ret = [];
25013
25014 if (oldFileName == newFileName) {
25015 ret.push('Index: ' + oldFileName);
25016 }
25017
25018 ret.push('===================================================================');
25019 ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader));
25020 ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader));
25021
25022 for (var i = 0; i < diff.hunks.length; i++) {
25023 var hunk = diff.hunks[i];
25024 ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@');
25025 ret.push.apply(ret, hunk.lines);
25026 }
25027
25028 return ret.join('\n') + '\n';
25029}
25030function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {
25031 return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);
25032}
25033
25034function arrayEqual(a, b) {
25035 if (a.length !== b.length) {
25036 return false;
25037 }
25038
25039 return arrayStartsWith(a, b);
25040}
25041function arrayStartsWith(array, start) {
25042 if (start.length > array.length) {
25043 return false;
25044 }
25045
25046 for (var i = 0; i < start.length; i++) {
25047 if (start[i] !== array[i]) {
25048 return false;
25049 }
25050 }
25051
25052 return true;
25053}
25054
25055function calcLineCount(hunk) {
25056 var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines),
25057 oldLines = _calcOldNewLineCount.oldLines,
25058 newLines = _calcOldNewLineCount.newLines;
25059
25060 if (oldLines !== undefined) {
25061 hunk.oldLines = oldLines;
25062 } else {
25063 delete hunk.oldLines;
25064 }
25065
25066 if (newLines !== undefined) {
25067 hunk.newLines = newLines;
25068 } else {
25069 delete hunk.newLines;
25070 }
25071}
25072function merge$2(mine, theirs, base) {
25073 mine = loadPatch(mine, base);
25074 theirs = loadPatch(theirs, base);
25075 var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning.
25076 // Leaving sanity checks on this to the API consumer that may know more about the
25077 // meaning in their own context.
25078
25079 if (mine.index || theirs.index) {
25080 ret.index = mine.index || theirs.index;
25081 }
25082
25083 if (mine.newFileName || theirs.newFileName) {
25084 if (!fileNameChanged(mine)) {
25085 // No header or no change in ours, use theirs (and ours if theirs does not exist)
25086 ret.oldFileName = theirs.oldFileName || mine.oldFileName;
25087 ret.newFileName = theirs.newFileName || mine.newFileName;
25088 ret.oldHeader = theirs.oldHeader || mine.oldHeader;
25089 ret.newHeader = theirs.newHeader || mine.newHeader;
25090 } else if (!fileNameChanged(theirs)) {
25091 // No header or no change in theirs, use ours
25092 ret.oldFileName = mine.oldFileName;
25093 ret.newFileName = mine.newFileName;
25094 ret.oldHeader = mine.oldHeader;
25095 ret.newHeader = mine.newHeader;
25096 } else {
25097 // Both changed... figure it out
25098 ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName);
25099 ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName);
25100 ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader);
25101 ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader);
25102 }
25103 }
25104
25105 ret.hunks = [];
25106 var mineIndex = 0,
25107 theirsIndex = 0,
25108 mineOffset = 0,
25109 theirsOffset = 0;
25110
25111 while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) {
25112 var mineCurrent = mine.hunks[mineIndex] || {
25113 oldStart: Infinity
25114 },
25115 theirsCurrent = theirs.hunks[theirsIndex] || {
25116 oldStart: Infinity
25117 };
25118
25119 if (hunkBefore(mineCurrent, theirsCurrent)) {
25120 // This patch does not overlap with any of the others, yay.
25121 ret.hunks.push(cloneHunk(mineCurrent, mineOffset));
25122 mineIndex++;
25123 theirsOffset += mineCurrent.newLines - mineCurrent.oldLines;
25124 } else if (hunkBefore(theirsCurrent, mineCurrent)) {
25125 // This patch does not overlap with any of the others, yay.
25126 ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset));
25127 theirsIndex++;
25128 mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines;
25129 } else {
25130 // Overlap, merge as best we can
25131 var mergedHunk = {
25132 oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart),
25133 oldLines: 0,
25134 newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset),
25135 newLines: 0,
25136 lines: []
25137 };
25138 mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines);
25139 theirsIndex++;
25140 mineIndex++;
25141 ret.hunks.push(mergedHunk);
25142 }
25143 }
25144
25145 return ret;
25146}
25147
25148function loadPatch(param, base) {
25149 if (typeof param === 'string') {
25150 if (/^@@/m.test(param) || /^Index:/m.test(param)) {
25151 return parsePatch(param)[0];
25152 }
25153
25154 if (!base) {
25155 throw new Error('Must provide a base reference or pass in a patch');
25156 }
25157
25158 return structuredPatch(undefined, undefined, base, param);
25159 }
25160
25161 return param;
25162}
25163
25164function fileNameChanged(patch) {
25165 return patch.newFileName && patch.newFileName !== patch.oldFileName;
25166}
25167
25168function selectField(index, mine, theirs) {
25169 if (mine === theirs) {
25170 return mine;
25171 } else {
25172 index.conflict = true;
25173 return {
25174 mine: mine,
25175 theirs: theirs
25176 };
25177 }
25178}
25179
25180function hunkBefore(test, check) {
25181 return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart;
25182}
25183
25184function cloneHunk(hunk, offset) {
25185 return {
25186 oldStart: hunk.oldStart,
25187 oldLines: hunk.oldLines,
25188 newStart: hunk.newStart + offset,
25189 newLines: hunk.newLines,
25190 lines: hunk.lines
25191 };
25192}
25193
25194function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) {
25195 // This will generally result in a conflicted hunk, but there are cases where the context
25196 // is the only overlap where we can successfully merge the content here.
25197 var mine = {
25198 offset: mineOffset,
25199 lines: mineLines,
25200 index: 0
25201 },
25202 their = {
25203 offset: theirOffset,
25204 lines: theirLines,
25205 index: 0
25206 }; // Handle any leading content
25207
25208 insertLeading(hunk, mine, their);
25209 insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each.
25210
25211 while (mine.index < mine.lines.length && their.index < their.lines.length) {
25212 var mineCurrent = mine.lines[mine.index],
25213 theirCurrent = their.lines[their.index];
25214
25215 if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) {
25216 // Both modified ...
25217 mutualChange(hunk, mine, their);
25218 } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') {
25219 var _hunk$lines;
25220
25221 // Mine inserted
25222 (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine)));
25223 } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') {
25224 var _hunk$lines2;
25225
25226 // Theirs inserted
25227 (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their)));
25228 } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') {
25229 // Mine removed or edited
25230 removal(hunk, mine, their);
25231 } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') {
25232 // Their removed or edited
25233 removal(hunk, their, mine, true);
25234 } else if (mineCurrent === theirCurrent) {
25235 // Context identity
25236 hunk.lines.push(mineCurrent);
25237 mine.index++;
25238 their.index++;
25239 } else {
25240 // Context mismatch
25241 conflict(hunk, collectChange(mine), collectChange(their));
25242 }
25243 } // Now push anything that may be remaining
25244
25245
25246 insertTrailing(hunk, mine);
25247 insertTrailing(hunk, their);
25248 calcLineCount(hunk);
25249}
25250
25251function mutualChange(hunk, mine, their) {
25252 var myChanges = collectChange(mine),
25253 theirChanges = collectChange(their);
25254
25255 if (allRemoves(myChanges) && allRemoves(theirChanges)) {
25256 // Special case for remove changes that are supersets of one another
25257 if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) {
25258 var _hunk$lines3;
25259
25260 (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges));
25261
25262 return;
25263 } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) {
25264 var _hunk$lines4;
25265
25266 (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges));
25267
25268 return;
25269 }
25270 } else if (arrayEqual(myChanges, theirChanges)) {
25271 var _hunk$lines5;
25272
25273 (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges));
25274
25275 return;
25276 }
25277
25278 conflict(hunk, myChanges, theirChanges);
25279}
25280
25281function removal(hunk, mine, their, swap) {
25282 var myChanges = collectChange(mine),
25283 theirChanges = collectContext(their, myChanges);
25284
25285 if (theirChanges.merged) {
25286 var _hunk$lines6;
25287
25288 (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged));
25289 } else {
25290 conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges);
25291 }
25292}
25293
25294function conflict(hunk, mine, their) {
25295 hunk.conflict = true;
25296 hunk.lines.push({
25297 conflict: true,
25298 mine: mine,
25299 theirs: their
25300 });
25301}
25302
25303function insertLeading(hunk, insert, their) {
25304 while (insert.offset < their.offset && insert.index < insert.lines.length) {
25305 var line = insert.lines[insert.index++];
25306 hunk.lines.push(line);
25307 insert.offset++;
25308 }
25309}
25310
25311function insertTrailing(hunk, insert) {
25312 while (insert.index < insert.lines.length) {
25313 var line = insert.lines[insert.index++];
25314 hunk.lines.push(line);
25315 }
25316}
25317
25318function collectChange(state) {
25319 var ret = [],
25320 operation = state.lines[state.index][0];
25321
25322 while (state.index < state.lines.length) {
25323 var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change.
25324
25325 if (operation === '-' && line[0] === '+') {
25326 operation = '+';
25327 }
25328
25329 if (operation === line[0]) {
25330 ret.push(line);
25331 state.index++;
25332 } else {
25333 break;
25334 }
25335 }
25336
25337 return ret;
25338}
25339
25340function collectContext(state, matchChanges) {
25341 var changes = [],
25342 merged = [],
25343 matchIndex = 0,
25344 contextChanges = false,
25345 conflicted = false;
25346
25347 while (matchIndex < matchChanges.length && state.index < state.lines.length) {
25348 var change = state.lines[state.index],
25349 match = matchChanges[matchIndex]; // Once we've hit our add, then we are done
25350
25351 if (match[0] === '+') {
25352 break;
25353 }
25354
25355 contextChanges = contextChanges || change[0] !== ' ';
25356 merged.push(match);
25357 matchIndex++; // Consume any additions in the other block as a conflict to attempt
25358 // to pull in the remaining context after this
25359
25360 if (change[0] === '+') {
25361 conflicted = true;
25362
25363 while (change[0] === '+') {
25364 changes.push(change);
25365 change = state.lines[++state.index];
25366 }
25367 }
25368
25369 if (match.substr(1) === change.substr(1)) {
25370 changes.push(change);
25371 state.index++;
25372 } else {
25373 conflicted = true;
25374 }
25375 }
25376
25377 if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) {
25378 conflicted = true;
25379 }
25380
25381 if (conflicted) {
25382 return changes;
25383 }
25384
25385 while (matchIndex < matchChanges.length) {
25386 merged.push(matchChanges[matchIndex++]);
25387 }
25388
25389 return {
25390 merged: merged,
25391 changes: changes
25392 };
25393}
25394
25395function allRemoves(changes) {
25396 return changes.reduce(function (prev, change) {
25397 return prev && change[0] === '-';
25398 }, true);
25399}
25400
25401function skipRemoveSuperset(state, removeChanges, delta) {
25402 for (var i = 0; i < delta; i++) {
25403 var changeContent = removeChanges[removeChanges.length - delta + i].substr(1);
25404
25405 if (state.lines[state.index + i] !== ' ' + changeContent) {
25406 return false;
25407 }
25408 }
25409
25410 state.index += delta;
25411 return true;
25412}
25413
25414function calcOldNewLineCount(lines) {
25415 var oldLines = 0;
25416 var newLines = 0;
25417 lines.forEach(function (line) {
25418 if (typeof line !== 'string') {
25419 var myCount = calcOldNewLineCount(line.mine);
25420 var theirCount = calcOldNewLineCount(line.theirs);
25421
25422 if (oldLines !== undefined) {
25423 if (myCount.oldLines === theirCount.oldLines) {
25424 oldLines += myCount.oldLines;
25425 } else {
25426 oldLines = undefined;
25427 }
25428 }
25429
25430 if (newLines !== undefined) {
25431 if (myCount.newLines === theirCount.newLines) {
25432 newLines += myCount.newLines;
25433 } else {
25434 newLines = undefined;
25435 }
25436 }
25437 } else {
25438 if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) {
25439 newLines++;
25440 }
25441
25442 if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) {
25443 oldLines++;
25444 }
25445 }
25446 });
25447 return {
25448 oldLines: oldLines,
25449 newLines: newLines
25450 };
25451}
25452
25453// See: http://code.google.com/p/google-diff-match-patch/wiki/API
25454function convertChangesToDMP(changes) {
25455 var ret = [],
25456 change,
25457 operation;
25458
25459 for (var i = 0; i < changes.length; i++) {
25460 change = changes[i];
25461
25462 if (change.added) {
25463 operation = 1;
25464 } else if (change.removed) {
25465 operation = -1;
25466 } else {
25467 operation = 0;
25468 }
25469
25470 ret.push([operation, change.value]);
25471 }
25472
25473 return ret;
25474}
25475
25476function convertChangesToXML(changes) {
25477 var ret = [];
25478
25479 for (var i = 0; i < changes.length; i++) {
25480 var change = changes[i];
25481
25482 if (change.added) {
25483 ret.push('<ins>');
25484 } else if (change.removed) {
25485 ret.push('<del>');
25486 }
25487
25488 ret.push(escapeHTML(change.value));
25489
25490 if (change.added) {
25491 ret.push('</ins>');
25492 } else if (change.removed) {
25493 ret.push('</del>');
25494 }
25495 }
25496
25497 return ret.join('');
25498}
25499
25500function escapeHTML(s) {
25501 var n = s;
25502 n = n.replace(/&/g, '&amp;');
25503 n = n.replace(/</g, '&lt;');
25504 n = n.replace(/>/g, '&gt;');
25505 n = n.replace(/"/g, '&quot;');
25506 return n;
25507}
25508
25509var index_es6 = {
25510 __proto__: null,
25511 Diff: Diff,
25512 diffChars: diffChars,
25513 diffWords: diffWords,
25514 diffWordsWithSpace: diffWordsWithSpace,
25515 diffLines: diffLines,
25516 diffTrimmedLines: diffTrimmedLines,
25517 diffSentences: diffSentences,
25518 diffCss: diffCss,
25519 diffJson: diffJson,
25520 diffArrays: diffArrays,
25521 structuredPatch: structuredPatch,
25522 createTwoFilesPatch: createTwoFilesPatch,
25523 createPatch: createPatch,
25524 applyPatch: applyPatch,
25525 applyPatches: applyPatches,
25526 parsePatch: parsePatch,
25527 merge: merge$2,
25528 convertChangesToDMP: convertChangesToDMP,
25529 convertChangesToXML: convertChangesToXML,
25530 canonicalize: canonicalize
25531};
25532
25533var require$$0$3 = /*@__PURE__*/getAugmentedNamespace(index_es6);
25534
25535(function (exports) {
25536Object.defineProperty(exports, "__esModule", { value: true });
25537exports.createEvalAwarePartialHost = exports.EvalState = exports.createRepl = exports.EVAL_FILENAME = void 0;
25538const diff_1 = require$$0$3;
25539const os_1 = require$$0__default$1;
25540const path_1 = path__default;
25541const repl_1 = require$$3__default;
25542const vm_1 = require$$4__default;
25543const index_1 = dist$1;
25544const fs_1 = fs__default;
25545const console_1 = require$$7__default;
25546/**
25547 * Eval filename for REPL/debug.
25548 * @internal
25549 */
25550exports.EVAL_FILENAME = `[eval].ts`;
25551/**
25552 * Create a ts-node REPL instance.
25553 *
25554 * Usage example:
25555 *
25556 * const repl = tsNode.createRepl()
25557 * const service = tsNode.create({...repl.evalAwarePartialHost})
25558 * repl.setService(service)
25559 * repl.start()
25560 */
25561function createRepl(options = {}) {
25562 var _a, _b, _c, _d, _e;
25563 let service = options.service;
25564 const state = (_a = options.state) !== null && _a !== void 0 ? _a : new EvalState(path_1.join(process.cwd(), exports.EVAL_FILENAME));
25565 const evalAwarePartialHost = createEvalAwarePartialHost(state);
25566 const stdin = (_b = options.stdin) !== null && _b !== void 0 ? _b : process.stdin;
25567 const stdout = (_c = options.stdout) !== null && _c !== void 0 ? _c : process.stdout;
25568 const stderr = (_d = options.stderr) !== null && _d !== void 0 ? _d : process.stderr;
25569 const _console = stdout === process.stdout && stderr === process.stderr
25570 ? console
25571 : new console_1.Console(stdout, stderr);
25572 const replService = {
25573 state: (_e = options.state) !== null && _e !== void 0 ? _e : new EvalState(path_1.join(process.cwd(), exports.EVAL_FILENAME)),
25574 setService,
25575 evalCode,
25576 nodeEval,
25577 evalAwarePartialHost,
25578 start,
25579 stdin,
25580 stdout,
25581 stderr,
25582 console: _console,
25583 };
25584 return replService;
25585 function setService(_service) {
25586 service = _service;
25587 }
25588 function evalCode(code) {
25589 return _eval(service, state, code);
25590 }
25591 function nodeEval(code, _context, _filename, callback) {
25592 let err = null;
25593 let result;
25594 // TODO: Figure out how to handle completion here.
25595 if (code === '.scope') {
25596 callback(err);
25597 return;
25598 }
25599 try {
25600 result = evalCode(code);
25601 }
25602 catch (error) {
25603 if (error instanceof index_1.TSError) {
25604 // Support recoverable compilations using >= node 6.
25605 if (repl_1.Recoverable && isRecoverable(error)) {
25606 err = new repl_1.Recoverable(error);
25607 }
25608 else {
25609 _console.error(error);
25610 }
25611 }
25612 else {
25613 err = error;
25614 }
25615 }
25616 return callback(err, result);
25617 }
25618 function start(code) {
25619 // TODO assert that service is set; remove all ! postfixes
25620 return startRepl(replService, service, state, code);
25621 }
25622}
25623exports.createRepl = createRepl;
25624/**
25625 * Eval state management. Stores virtual `[eval].ts` file
25626 */
25627class EvalState {
25628 constructor(path) {
25629 this.path = path;
25630 /** @internal */
25631 this.input = '';
25632 /** @internal */
25633 this.output = '';
25634 /** @internal */
25635 this.version = 0;
25636 /** @internal */
25637 this.lines = 0;
25638 }
25639}
25640exports.EvalState = EvalState;
25641function createEvalAwarePartialHost(state) {
25642 function readFile(path) {
25643 if (path === state.path)
25644 return state.input;
25645 try {
25646 return fs_1.readFileSync(path, 'utf8');
25647 }
25648 catch (err) {
25649 /* Ignore. */
25650 }
25651 }
25652 function fileExists(path) {
25653 if (path === state.path)
25654 return true;
25655 try {
25656 const stats = fs_1.statSync(path);
25657 return stats.isFile() || stats.isFIFO();
25658 }
25659 catch (err) {
25660 return false;
25661 }
25662 }
25663 return { readFile, fileExists };
25664}
25665exports.createEvalAwarePartialHost = createEvalAwarePartialHost;
25666/**
25667 * Evaluate the code snippet.
25668 */
25669function _eval(service, state, input) {
25670 const lines = state.lines;
25671 const isCompletion = !/\n$/.test(input);
25672 const undo = appendEval(state, input);
25673 let output;
25674 try {
25675 output = service.compile(state.input, state.path, -lines);
25676 }
25677 catch (err) {
25678 undo();
25679 throw err;
25680 }
25681 // Use `diff` to check for new JavaScript to execute.
25682 const changes = diff_1.diffLines(state.output, output);
25683 if (isCompletion) {
25684 undo();
25685 }
25686 else {
25687 state.output = output;
25688 }
25689 return changes.reduce((result, change) => {
25690 return change.added ? exec(change.value, state.path) : result;
25691 }, undefined);
25692}
25693/**
25694 * Execute some code.
25695 */
25696function exec(code, filename) {
25697 const script = new vm_1.Script(code, { filename: filename });
25698 return script.runInThisContext();
25699}
25700/**
25701 * Start a CLI REPL.
25702 */
25703function startRepl(replService, service, state, code) {
25704 // Eval incoming code before the REPL starts.
25705 if (code) {
25706 try {
25707 replService.evalCode(`${code}\n`);
25708 }
25709 catch (err) {
25710 replService.console.error(err);
25711 process.exit(1);
25712 }
25713 }
25714 const repl = repl_1.start({
25715 prompt: '> ',
25716 input: replService.stdin,
25717 output: replService.stdout,
25718 // Mimicking node's REPL implementation: https://github.com/nodejs/node/blob/168b22ba073ee1cbf8d0bcb4ded7ff3099335d04/lib/internal/repl.js#L28-L30
25719 terminal: replService.stdout.isTTY &&
25720 !parseInt(index_1.env.NODE_NO_READLINE, 10),
25721 eval: replService.nodeEval,
25722 useGlobal: true,
25723 });
25724 // Bookmark the point where we should reset the REPL state.
25725 const resetEval = appendEval(state, '');
25726 function reset() {
25727 resetEval();
25728 // Hard fix for TypeScript forcing `Object.defineProperty(exports, ...)`.
25729 exec('exports = module.exports', state.path);
25730 }
25731 reset();
25732 repl.on('reset', reset);
25733 repl.defineCommand('type', {
25734 help: 'Check the type of a TypeScript identifier',
25735 action: function (identifier) {
25736 if (!identifier) {
25737 repl.displayPrompt();
25738 return;
25739 }
25740 const undo = appendEval(state, identifier);
25741 const { name, comment } = service.getTypeInfo(state.input, state.path, state.input.length);
25742 undo();
25743 if (name)
25744 repl.outputStream.write(`${name}\n`);
25745 if (comment)
25746 repl.outputStream.write(`${comment}\n`);
25747 repl.displayPrompt();
25748 },
25749 });
25750 // Set up REPL history when available natively via node.js >= 11.
25751 if (repl.setupHistory) {
25752 const historyPath = index_1.env.TS_NODE_HISTORY || path_1.join(os_1.homedir(), '.ts_node_repl_history');
25753 repl.setupHistory(historyPath, (err) => {
25754 if (!err)
25755 return;
25756 replService.console.error(err);
25757 process.exit(1);
25758 });
25759 }
25760}
25761/**
25762 * Append to the eval instance and return an undo function.
25763 */
25764function appendEval(state, input) {
25765 const undoInput = state.input;
25766 const undoVersion = state.version;
25767 const undoOutput = state.output;
25768 const undoLines = state.lines;
25769 // Handle ASI issues with TypeScript re-evaluation.
25770 if (undoInput.charAt(undoInput.length - 1) === '\n' &&
25771 /^\s*[\/\[(`-]/.test(input) &&
25772 !/;\s*$/.test(undoInput)) {
25773 state.input = `${state.input.slice(0, -1)};\n`;
25774 }
25775 state.input += input;
25776 state.lines += lineCount(input);
25777 state.version++;
25778 return function () {
25779 state.input = undoInput;
25780 state.output = undoOutput;
25781 state.version = undoVersion;
25782 state.lines = undoLines;
25783 };
25784}
25785/**
25786 * Count the number of lines.
25787 */
25788function lineCount(value) {
25789 let count = 0;
25790 for (const char of value) {
25791 if (char === '\n') {
25792 count++;
25793 }
25794 }
25795 return count;
25796}
25797const RECOVERY_CODES = new Set([
25798 1003,
25799 1005,
25800 1109,
25801 1126,
25802 1160,
25803 1161,
25804 2355, // "A function whose declared type is neither 'void' nor 'any' must return a value."
25805]);
25806/**
25807 * Check if a function can recover gracefully.
25808 */
25809function isRecoverable(error) {
25810 return error.diagnosticCodes.every((code) => RECOVERY_CODES.has(code));
25811}
25812
25813}(repl));
25814
25815var nodeCjsLoaderUtils = {exports: {}};
25816
25817var nodePrimordials = {
25818 ArrayIsArray: Array.isArray,
25819 ArrayPrototypeJoin: (obj, separator) => Array.prototype.join.call(obj, separator),
25820 ArrayPrototypeShift: (obj) => Array.prototype.shift.call(obj),
25821 JSONParse: JSON.parse,
25822 JSONStringify: JSON.stringify,
25823 ObjectFreeze: Object.freeze,
25824 ObjectGetOwnPropertyNames: Object.getOwnPropertyNames,
25825 ObjectPrototypeHasOwnProperty: (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop),
25826 RegExpPrototypeTest: (obj, string) => RegExp.prototype.test.call(obj, string),
25827 SafeMap: Map,
25828 SafeSet: Set,
25829 StringPrototypeEndsWith: (str, ...rest) => String.prototype.endsWith.apply(str, rest),
25830 StringPrototypeIncludes: (str, ...rest) => String.prototype.includes.apply(str, rest),
25831 StringPrototypeLastIndexOf: (str, ...rest) => String.prototype.lastIndexOf.apply(str, rest),
25832 StringPrototypeIndexOf: (str, ...rest) => String.prototype.indexOf.apply(str, rest),
25833 StringPrototypeReplace: (str, ...rest) => String.prototype.replace.apply(str, rest),
25834 StringPrototypeSlice: (str, ...rest) => String.prototype.slice.apply(str, rest),
25835 StringPrototypeSplit: (str, ...rest) => String.prototype.split.apply(str, rest),
25836 StringPrototypeStartsWith: (str, ...rest) => String.prototype.startsWith.apply(str, rest),
25837 StringPrototypeSubstr: (str, ...rest) => String.prototype.substr.apply(str, rest)
25838};
25839
25840const fs$l = fs__default;
25841
25842// In node's core, this is implemented in C
25843// https://github.com/nodejs/node/blob/v15.3.0/src/node_file.cc#L891-L985
25844function internalModuleReadJSON$1(path) {
25845 let string;
25846 try {
25847 string = fs$l.readFileSync(path, 'utf8');
25848 } catch (e) {
25849 if (e.code === 'ENOENT') return []
25850 throw e
25851 }
25852 // Node's implementation checks for the presence of relevant keys: main, name, type, exports, imports
25853 // Node does this for performance to skip unnecessary parsing.
25854 // This would slow us down and, based on our usage, we can skip it.
25855 const containsKeys = true;
25856 return [string, containsKeys]
25857}
25858
25859var nodeInternalFs = {
25860 internalModuleReadJSON: internalModuleReadJSON$1
25861};
25862
25863const flagSymbol = Symbol('arg flag');
25864
25865function arg(opts, {argv = process.argv.slice(2), permissive = false, stopAtPositional = false} = {}) {
25866 if (!opts) {
25867 throw new Error('Argument specification object is required');
25868 }
25869
25870 const result = {_: []};
25871
25872 const aliases = {};
25873 const handlers = {};
25874
25875 for (const key of Object.keys(opts)) {
25876 if (!key) {
25877 throw new TypeError('Argument key cannot be an empty string');
25878 }
25879
25880 if (key[0] !== '-') {
25881 throw new TypeError(`Argument key must start with '-' but found: '${key}'`);
25882 }
25883
25884 if (key.length === 1) {
25885 throw new TypeError(`Argument key must have a name; singular '-' keys are not allowed: ${key}`);
25886 }
25887
25888 if (typeof opts[key] === 'string') {
25889 aliases[key] = opts[key];
25890 continue;
25891 }
25892
25893 let type = opts[key];
25894 let isFlag = false;
25895
25896 if (Array.isArray(type) && type.length === 1 && typeof type[0] === 'function') {
25897 const [fn] = type;
25898 type = (value, name, prev = []) => {
25899 prev.push(fn(value, name, prev[prev.length - 1]));
25900 return prev;
25901 };
25902 isFlag = fn === Boolean || fn[flagSymbol] === true;
25903 } else if (typeof type === 'function') {
25904 isFlag = type === Boolean || type[flagSymbol] === true;
25905 } else {
25906 throw new TypeError(`Type missing or not a function or valid array type: ${key}`);
25907 }
25908
25909 if (key[1] !== '-' && key.length > 2) {
25910 throw new TypeError(`Short argument keys (with a single hyphen) must have only one character: ${key}`);
25911 }
25912
25913 handlers[key] = [type, isFlag];
25914 }
25915
25916 for (let i = 0, len = argv.length; i < len; i++) {
25917 const wholeArg = argv[i];
25918
25919 if (stopAtPositional && result._.length > 0) {
25920 result._ = result._.concat(argv.slice(i));
25921 break;
25922 }
25923
25924 if (wholeArg === '--') {
25925 result._ = result._.concat(argv.slice(i + 1));
25926 break;
25927 }
25928
25929 if (wholeArg.length > 1 && wholeArg[0] === '-') {
25930 /* eslint-disable operator-linebreak */
25931 const separatedArguments = (wholeArg[1] === '-' || wholeArg.length === 2)
25932 ? [wholeArg]
25933 : wholeArg.slice(1).split('').map(a => `-${a}`);
25934 /* eslint-enable operator-linebreak */
25935
25936 for (let j = 0; j < separatedArguments.length; j++) {
25937 const arg = separatedArguments[j];
25938 const [originalArgName, argStr] = arg[1] === '-' ? arg.split(/=(.*)/, 2) : [arg, undefined];
25939
25940 let argName = originalArgName;
25941 while (argName in aliases) {
25942 argName = aliases[argName];
25943 }
25944
25945 if (!(argName in handlers)) {
25946 if (permissive) {
25947 result._.push(arg);
25948 continue;
25949 } else {
25950 const err = new Error(`Unknown or unexpected option: ${originalArgName}`);
25951 err.code = 'ARG_UNKNOWN_OPTION';
25952 throw err;
25953 }
25954 }
25955
25956 const [type, isFlag] = handlers[argName];
25957
25958 if (!isFlag && ((j + 1) < separatedArguments.length)) {
25959 throw new TypeError(`Option requires argument (but was followed by another short argument): ${originalArgName}`);
25960 }
25961
25962 if (isFlag) {
25963 result[argName] = type(true, argName, result[argName]);
25964 } else if (argStr === undefined) {
25965 if (
25966 argv.length < i + 2 ||
25967 (
25968 argv[i + 1].length > 1 &&
25969 (argv[i + 1][0] === '-') &&
25970 !(
25971 argv[i + 1].match(/^-?\d*(\.(?=\d))?\d*$/) &&
25972 (
25973 type === Number ||
25974 // eslint-disable-next-line no-undef
25975 (typeof BigInt !== 'undefined' && type === BigInt)
25976 )
25977 )
25978 )
25979 ) {
25980 const extended = originalArgName === argName ? '' : ` (alias for ${argName})`;
25981 throw new Error(`Option requires argument: ${originalArgName}${extended}`);
25982 }
25983
25984 result[argName] = type(argv[i + 1], argName, result[argName]);
25985 ++i;
25986 } else {
25987 result[argName] = type(argStr, argName, result[argName]);
25988 }
25989 }
25990 } else {
25991 result._.push(wholeArg);
25992 }
25993 }
25994
25995 return result;
25996}
25997
25998arg.flag = fn => {
25999 fn[flagSymbol] = true;
26000 return fn;
26001};
26002
26003// Utility types
26004arg.COUNT = arg.flag((v, name, existingCount) => (existingCount || 0) + 1);
26005
26006const { SafeMap } = nodePrimordials;
26007const { internalModuleReadJSON } = nodeInternalFs;
26008const { pathToFileURL } = require$$0__default$7;
26009const { toNamespacedPath } = path__default;
26010
26011const cache = new SafeMap();
26012
26013let manifest;
26014
26015/**
26016 * @param {string} jsonPath
26017 * @return {[string, boolean]}
26018 */
26019function read(jsonPath) {
26020 if (cache.has(jsonPath)) {
26021 return cache.get(jsonPath);
26022 }
26023
26024 const [string, containsKeys] = internalModuleReadJSON(
26025 toNamespacedPath(jsonPath)
26026 );
26027 const result = { string, containsKeys };
26028 if (string !== undefined) {
26029 if (manifest === undefined) {
26030 // manifest = getOptionValue('--experimental-policy') ?
26031 // require('internal/process/policy').manifest :
26032 // null;
26033 // disabled for now. I am not sure if/how we should support this
26034 manifest = null;
26035 }
26036 if (manifest !== null) {
26037 const jsonURL = pathToFileURL(jsonPath);
26038 manifest.assertIntegrity(jsonURL, string);
26039 }
26040 }
26041 cache.set(jsonPath, result);
26042 return result;
26043}
26044
26045var nodePackageJsonReader = { read };
26046
26047(function (module) {
26048// Copied from several files in node's source code.
26049// https://github.com/nodejs/node/blob/2d5d77306f6dff9110c1f77fefab25f973415770/lib/internal/modules/cjs/loader.js
26050// Each function and variable below must have a comment linking to the source in node's github repo.
26051
26052const path = path__default;
26053const packageJsonReader = nodePackageJsonReader;
26054const {JSONParse} = nodePrimordials;
26055
26056module.exports.assertScriptCanLoadAsCJSImpl = assertScriptCanLoadAsCJSImpl;
26057
26058// copied from Module._extensions['.js']
26059// https://github.com/nodejs/node/blob/v15.3.0/lib/internal/modules/cjs/loader.js#L1113-L1120
26060function assertScriptCanLoadAsCJSImpl(filename) {
26061 const pkg = readPackageScope(filename);
26062 // Function require shouldn't be used in ES modules.
26063 if (pkg && pkg.data && pkg.data.type === 'module') {
26064 const parentPath = module.parent && module.parent.filename;
26065 const packageJsonPath = path.resolve(pkg.path, 'package.json');
26066 throw createErrRequireEsm(filename, parentPath, packageJsonPath);
26067 }
26068}
26069
26070// Copied from https://github.com/nodejs/node/blob/2d5d77306f6dff9110c1f77fefab25f973415770/lib/internal/modules/cjs/loader.js#L285-L301
26071function readPackageScope(checkPath) {
26072 const rootSeparatorIndex = checkPath.indexOf(path.sep);
26073 let separatorIndex;
26074 while (
26075 (separatorIndex = checkPath.lastIndexOf(path.sep)) > rootSeparatorIndex
26076 ) {
26077 checkPath = checkPath.slice(0, separatorIndex);
26078 if (checkPath.endsWith(path.sep + 'node_modules'))
26079 return false;
26080 const pjson = readPackage(checkPath);
26081 if (pjson) return {
26082 path: checkPath,
26083 data: pjson
26084 };
26085 }
26086 return false;
26087}
26088
26089// Copied from https://github.com/nodejs/node/blob/2d5d77306f6dff9110c1f77fefab25f973415770/lib/internal/modules/cjs/loader.js#L249
26090const packageJsonCache = new Map();
26091
26092// Copied from https://github.com/nodejs/node/blob/v15.3.0/lib/internal/modules/cjs/loader.js#L275-L304
26093function readPackage(requestPath) {
26094 const jsonPath = path.resolve(requestPath, 'package.json');
26095
26096 const existing = packageJsonCache.get(jsonPath);
26097 if (existing !== undefined) return existing;
26098
26099 const result = packageJsonReader.read(jsonPath);
26100 const json = result.containsKeys === false ? '{}' : result.string;
26101 if (json === undefined) {
26102 packageJsonCache.set(jsonPath, false);
26103 return false;
26104 }
26105
26106 try {
26107 const parsed = JSONParse(json);
26108 const filtered = {
26109 name: parsed.name,
26110 main: parsed.main,
26111 exports: parsed.exports,
26112 imports: parsed.imports,
26113 type: parsed.type
26114 };
26115 packageJsonCache.set(jsonPath, filtered);
26116 return filtered;
26117 } catch (e) {
26118 e.path = jsonPath;
26119 e.message = 'Error parsing ' + jsonPath + ': ' + e.message;
26120 throw e;
26121 }
26122}
26123
26124// Native ERR_REQUIRE_ESM Error is declared here:
26125// https://github.com/nodejs/node/blob/2d5d77306f6dff9110c1f77fefab25f973415770/lib/internal/errors.js#L1294-L1313
26126// Error class factory is implemented here:
26127// function E: https://github.com/nodejs/node/blob/2d5d77306f6dff9110c1f77fefab25f973415770/lib/internal/errors.js#L323-L341
26128// function makeNodeErrorWithCode: https://github.com/nodejs/node/blob/2d5d77306f6dff9110c1f77fefab25f973415770/lib/internal/errors.js#L251-L278
26129// The code below should create an error that matches the native error as closely as possible.
26130// Third-party libraries which attempt to catch the native ERR_REQUIRE_ESM should recognize our imitation error.
26131function createErrRequireEsm(filename, parentPath, packageJsonPath) {
26132 const code = 'ERR_REQUIRE_ESM';
26133 const err = new Error(getMessage(filename, parentPath, packageJsonPath));
26134 // Set `name` to be used in stack trace, generate stack trace with that name baked in, then re-declare the `name` field.
26135 // This trick is copied from node's source.
26136 err.name = `Error [${ code }]`;
26137 Object.defineProperty(err, 'name', {
26138 value: 'Error',
26139 enumerable: false,
26140 writable: true,
26141 configurable: true
26142 });
26143 err.code = code;
26144 return err
26145
26146 // Copy-pasted from https://github.com/nodejs/node/blob/b533fb3508009e5f567cc776daba8fbf665386a6/lib/internal/errors.js#L1293-L1311
26147 // so that our error message is identical to the native message.
26148 function getMessage(filename, parentPath = null, packageJsonPath = null) {
26149 const ext = path.extname(filename);
26150 let msg = `Must use import to load ES Module: ${filename}`;
26151 if (parentPath && packageJsonPath) {
26152 const path = path__default;
26153 path.basename(filename) === path.basename(parentPath) ?
26154 filename : path.basename(filename);
26155 msg +=
26156 '\nrequire() of ES modules is not supported.\nrequire() of ' +
26157 `${filename} ${parentPath ? `from ${parentPath} ` : ''}` +
26158 `is an ES module file as it is a ${ext} file whose nearest parent ` +
26159 `package.json contains "type": "module" which defines all ${ext} ` +
26160 'files in that package scope as ES modules.\nInstead ' +
26161 'change the requiring code to use ' +
26162 'import(), or remove "type": "module" from ' +
26163 `${packageJsonPath}.\n`;
26164 return msg;
26165 }
26166 return msg;
26167 }
26168}
26169}(nodeCjsLoaderUtils));
26170
26171var name = "ts-node";
26172var version$2 = "10.0.0";
26173var description = "TypeScript execution environment and REPL for node.js, with source map support";
26174var main$3 = "dist/index.js";
26175var exports$1 = {
26176 ".": "./dist/index.js",
26177 "./package": "./package.json",
26178 "./package.json": "./package.json",
26179 "./dist/bin": "./dist/bin.js",
26180 "./dist/bin.js": "./dist/bin.js",
26181 "./dist/bin-transpile": "./dist/bin-transpile.js",
26182 "./dist/bin-transpile.js": "./dist/bin-transpile.js",
26183 "./dist/bin-script": "./dist/bin-script.js",
26184 "./dist/bin-script.js": "./dist/bin-script.js",
26185 "./dist/bin-cwd": "./dist/bin-cwd.js",
26186 "./dist/bin-cwd.js": "./dist/bin-cwd.js",
26187 "./register": "./register/index.js",
26188 "./register/files": "./register/files.js",
26189 "./register/transpile-only": "./register/transpile-only.js",
26190 "./register/type-check": "./register/type-check.js",
26191 "./esm": "./esm.mjs",
26192 "./esm.mjs": "./esm.mjs",
26193 "./esm/transpile-only": "./esm/transpile-only.mjs",
26194 "./esm/transpile-only.mjs": "./esm/transpile-only.mjs",
26195 "./transpilers/swc-experimental": "./transpilers/swc-experimental.js",
26196 "./node10/tsconfig.json": "./node10/tsconfig.json",
26197 "./node12/tsconfig.json": "./node12/tsconfig.json",
26198 "./node14/tsconfig.json": "./node14/tsconfig.json",
26199 "./node16/tsconfig.json": "./node16/tsconfig.json"
26200};
26201var types$2 = "dist/index.d.ts";
26202var bin = {
26203 "ts-node": "dist/bin.js",
26204 "ts-script": "dist/bin-script-deprecated.js",
26205 "ts-node-script": "dist/bin-script.js",
26206 "ts-node-cwd": "dist/bin-cwd.js",
26207 "ts-node-transpile-only": "dist/bin-transpile.js"
26208};
26209var files = [
26210 "/transpilers/",
26211 "/dist/",
26212 "!/dist/test",
26213 "/dist-raw/",
26214 "/register/",
26215 "/esm/",
26216 "/esm.mjs",
26217 "/LICENSE",
26218 "/tsconfig.schema.json",
26219 "/tsconfig.schemastore-schema.json",
26220 "/node10/",
26221 "/node12/",
26222 "/node14/",
26223 "/node16/"
26224];
26225var scripts = {
26226 lint: "prettier --check .",
26227 "lint-fix": "prettier --write .",
26228 clean: "rimraf dist tsconfig.schema.json tsconfig.schemastore-schema.json tsconfig.tsbuildinfo tests/ts-node-packed.tgz",
26229 rebuild: "npm run clean && npm run build",
26230 build: "npm run build-nopack && npm run build-pack",
26231 "build-nopack": "npm run build-tsc && npm run build-configSchema",
26232 "build-tsc": "tsc",
26233 "build-configSchema": "typescript-json-schema --topRef --refs --validationKeywords allOf --out tsconfig.schema.json tsconfig.build-schema.json TsConfigSchema && node --require ./register ./scripts/create-merged-schema",
26234 "build-pack": "node ./scripts/build-pack.js",
26235 "test-spec": "ava",
26236 "test-cov": "nyc ava",
26237 test: "npm run build && npm run lint && npm run test-cov --",
26238 "test-local": "npm run lint && npm run build-tsc && npm run build-pack && npm run test-spec --",
26239 "coverage-report": "nyc report --reporter=lcov",
26240 prepare: "npm run clean && npm run build-nopack",
26241 "api-extractor": "api-extractor run --local --verbose"
26242};
26243var engines = {
26244 node: ">=12.0.0"
26245};
26246var repository = {
26247 type: "git",
26248 url: "git://github.com/TypeStrong/ts-node.git"
26249};
26250var keywords$2 = [
26251 "typescript",
26252 "node",
26253 "runtime",
26254 "environment",
26255 "ts",
26256 "compiler"
26257];
26258var author = {
26259 name: "Blake Embrey",
26260 email: "hello@blakeembrey.com",
26261 url: "http://blakeembrey.me"
26262};
26263var contributors = [
26264 {
26265 name: "Andrew Bradley",
26266 email: "cspotcode@gmail.com",
26267 url: "https://github.com/cspotcode"
26268 }
26269];
26270var license = "MIT";
26271var bugs = {
26272 url: "https://github.com/TypeStrong/ts-node/issues"
26273};
26274var homepage = "https://typestrong.org/ts-node";
26275var ava = {
26276 files: [
26277 "dist/test/*.spec.js"
26278 ],
26279 failWithoutAssertions: false,
26280 timeout: "300s"
26281};
26282var devDependencies = {
26283 "@microsoft/api-extractor": "^7.15.2",
26284 "@swc/core": ">=1.2.45",
26285 "@swc/wasm": ">=1.2.45",
26286 "@types/chai": "^4.0.4",
26287 "@types/diff": "^4.0.2",
26288 "@types/lodash": "^4.14.151",
26289 "@types/node": "13.13.5",
26290 "@types/proxyquire": "^1.3.28",
26291 "@types/react": "^16.0.2",
26292 "@types/rimraf": "^3.0.0",
26293 "@types/semver": "^7.1.0",
26294 "@types/source-map-support": "^0.5.0",
26295 "@yarnpkg/fslib": "^2.4.0",
26296 ava: "^3.15.0",
26297 axios: "^0.21.1",
26298 chai: "^4.0.1",
26299 "get-stream": "^6.0.0",
26300 lodash: "^4.17.15",
26301 ntypescript: "^1.201507091536.1",
26302 nyc: "^15.0.1",
26303 prettier: "^2.2.1",
26304 proxyquire: "^2.0.0",
26305 react: "^16.14.0",
26306 rimraf: "^3.0.0",
26307 semver: "^7.1.3",
26308 throat: "^6.0.1",
26309 typedoc: "^0.20.28",
26310 typescript: "4.2.2",
26311 "typescript-json-schema": "^0.42.0",
26312 "util.promisify": "^1.0.1"
26313};
26314var peerDependencies$1 = {
26315 "@swc/core": ">=1.2.45",
26316 "@swc/wasm": ">=1.2.45",
26317 "@types/node": "*",
26318 typescript: ">=2.7"
26319};
26320var peerDependenciesMeta = {
26321 "@swc/core": {
26322 optional: true
26323 },
26324 "@swc/wasm": {
26325 optional: true
26326 }
26327};
26328var dependencies = {
26329 "@tsconfig/node10": "^1.0.7",
26330 "@tsconfig/node12": "^1.0.7",
26331 "@tsconfig/node14": "^1.0.0",
26332 "@tsconfig/node16": "^1.0.1",
26333 arg: "^4.1.0",
26334 "create-require": "^1.1.0",
26335 diff: "^4.0.1",
26336 "make-error": "^1.1.1",
26337 "source-map-support": "^0.5.17",
26338 yn: "3.1.1"
26339};
26340var prettier = {
26341 singleQuote: true
26342};
26343var require$$10 = {
26344 name: name,
26345 version: version$2,
26346 description: description,
26347 main: main$3,
26348 exports: exports$1,
26349 types: types$2,
26350 bin: bin,
26351 files: files,
26352 scripts: scripts,
26353 engines: engines,
26354 repository: repository,
26355 keywords: keywords$2,
26356 author: author,
26357 contributors: contributors,
26358 license: license,
26359 bugs: bugs,
26360 homepage: homepage,
26361 ava: ava,
26362 devDependencies: devDependencies,
26363 peerDependencies: peerDependencies$1,
26364 peerDependenciesMeta: peerDependenciesMeta,
26365 dependencies: dependencies,
26366 prettier: prettier
26367};
26368
26369(function (exports) {
26370var _a;
26371Object.defineProperty(exports, "__esModule", { value: true });
26372exports.create = exports.register = exports.getExtensions = exports.TSError = exports.DEFAULTS = exports.VERSION = exports.debug = exports.INSPECT_CUSTOM = exports.env = exports.REGISTER_INSTANCE = exports.createRepl = void 0;
26373const path_1 = path__default;
26374const module_1 = require$$0__default$5;
26375const util = require$$0__default$3;
26376const url_1 = require$$0__default$7;
26377const sourceMapSupport$1 = sourceMapSupport.exports;
26378const make_error_1 = makeError$2.exports;
26379const util_1 = util$1;
26380const configuration_1 = configuration;
26381var repl_1 = repl;
26382Object.defineProperty(exports, "createRepl", { enumerable: true, get: function () { return repl_1.createRepl; } });
26383/**
26384 * Does this version of node obey the package.json "type" field
26385 * and throw ERR_REQUIRE_ESM when attempting to require() an ESM modules.
26386 */
26387const engineSupportsPackageTypeField = parseInt(process.versions.node.split('.')[0], 10) >= 12;
26388/**
26389 * Assert that script can be loaded as CommonJS when we attempt to require it.
26390 * If it should be loaded as ESM, throw ERR_REQUIRE_ESM like node does.
26391 *
26392 * Loaded conditionally so we don't need to support older node versions
26393 */
26394const assertScriptCanLoadAsCJS = engineSupportsPackageTypeField
26395 ? nodeCjsLoaderUtils.exports.assertScriptCanLoadAsCJSImpl
26396 : () => {
26397 /* noop */
26398 };
26399/**
26400 * Registered `ts-node` instance information.
26401 */
26402exports.REGISTER_INSTANCE = Symbol.for('ts-node.register.instance');
26403/** @internal */
26404exports.env = process.env;
26405/**
26406 * @internal
26407 */
26408exports.INSPECT_CUSTOM = util.inspect.custom || 'inspect';
26409/**
26410 * Debugging `ts-node`.
26411 */
26412const shouldDebug = util_1.yn(exports.env.TS_NODE_DEBUG);
26413/** @internal */
26414exports.debug = shouldDebug
26415 ? (...args) => console.log(`[ts-node ${new Date().toISOString()}]`, ...args)
26416 : () => undefined;
26417const debugFn = shouldDebug
26418 ? (key, fn) => {
26419 let i = 0;
26420 return (x) => {
26421 exports.debug(key, x, ++i);
26422 return fn(x);
26423 };
26424 }
26425 : (_, fn) => fn;
26426/**
26427 * Export the current version.
26428 */
26429exports.VERSION = require$$10.version;
26430/**
26431 * Default register options, including values specified via environment
26432 * variables.
26433 * @internal
26434 */
26435exports.DEFAULTS = {
26436 cwd: (_a = exports.env.TS_NODE_CWD) !== null && _a !== void 0 ? _a : exports.env.TS_NODE_DIR,
26437 emit: util_1.yn(exports.env.TS_NODE_EMIT),
26438 scope: util_1.yn(exports.env.TS_NODE_SCOPE),
26439 files: util_1.yn(exports.env.TS_NODE_FILES),
26440 pretty: util_1.yn(exports.env.TS_NODE_PRETTY),
26441 compiler: exports.env.TS_NODE_COMPILER,
26442 compilerOptions: util_1.parse(exports.env.TS_NODE_COMPILER_OPTIONS),
26443 ignore: util_1.split(exports.env.TS_NODE_IGNORE),
26444 project: exports.env.TS_NODE_PROJECT,
26445 skipProject: util_1.yn(exports.env.TS_NODE_SKIP_PROJECT),
26446 skipIgnore: util_1.yn(exports.env.TS_NODE_SKIP_IGNORE),
26447 preferTsExts: util_1.yn(exports.env.TS_NODE_PREFER_TS_EXTS),
26448 ignoreDiagnostics: util_1.split(exports.env.TS_NODE_IGNORE_DIAGNOSTICS),
26449 transpileOnly: util_1.yn(exports.env.TS_NODE_TRANSPILE_ONLY),
26450 typeCheck: util_1.yn(exports.env.TS_NODE_TYPE_CHECK),
26451 compilerHost: util_1.yn(exports.env.TS_NODE_COMPILER_HOST),
26452 logError: util_1.yn(exports.env.TS_NODE_LOG_ERROR),
26453 experimentalEsmLoader: false,
26454};
26455/**
26456 * TypeScript diagnostics error.
26457 */
26458class TSError extends make_error_1.BaseError {
26459 constructor(diagnosticText, diagnosticCodes) {
26460 super(`⨯ Unable to compile TypeScript:\n${diagnosticText}`);
26461 this.diagnosticText = diagnosticText;
26462 this.diagnosticCodes = diagnosticCodes;
26463 this.name = 'TSError';
26464 }
26465 /**
26466 * @internal
26467 */
26468 [exports.INSPECT_CUSTOM]() {
26469 return this.diagnosticText;
26470 }
26471}
26472exports.TSError = TSError;
26473/**
26474 * Cached fs operation wrapper.
26475 */
26476function cachedLookup(fn) {
26477 const cache = new Map();
26478 return (arg) => {
26479 if (!cache.has(arg)) {
26480 cache.set(arg, fn(arg));
26481 }
26482 return cache.get(arg);
26483 };
26484}
26485/** @internal */
26486function getExtensions(config) {
26487 const tsExtensions = ['.ts'];
26488 const jsExtensions = [];
26489 // Enable additional extensions when JSX or `allowJs` is enabled.
26490 if (config.options.jsx)
26491 tsExtensions.push('.tsx');
26492 if (config.options.allowJs)
26493 jsExtensions.push('.js');
26494 if (config.options.jsx && config.options.allowJs)
26495 jsExtensions.push('.jsx');
26496 return { tsExtensions, jsExtensions };
26497}
26498exports.getExtensions = getExtensions;
26499/**
26500 * Register TypeScript compiler instance onto node.js
26501 */
26502function register(opts = {}) {
26503 const originalJsHandler = commonjsRequire.extensions['.js'];
26504 const service = create(opts);
26505 const { tsExtensions, jsExtensions } = getExtensions(service.config);
26506 const extensions = [...tsExtensions, ...jsExtensions];
26507 // Expose registered instance globally.
26508 process[exports.REGISTER_INSTANCE] = service;
26509 // Register the extensions.
26510 registerExtensions(service.options.preferTsExts, extensions, service, originalJsHandler);
26511 // Require specified modules before start-up.
26512 module_1.Module._preloadModules(service.options.require);
26513 return service;
26514}
26515exports.register = register;
26516/**
26517 * Create TypeScript compiler instance.
26518 */
26519function create(rawOptions = {}) {
26520 var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
26521 const cwd = path_1.resolve((_c = (_b = (_a = rawOptions.cwd) !== null && _a !== void 0 ? _a : rawOptions.dir) !== null && _b !== void 0 ? _b : exports.DEFAULTS.cwd) !== null && _c !== void 0 ? _c : process.cwd());
26522 const compilerName = (_d = rawOptions.compiler) !== null && _d !== void 0 ? _d : exports.DEFAULTS.compiler;
26523 /**
26524 * Load the typescript compiler. It is required to load the tsconfig but might
26525 * be changed by the tsconfig, so we have to do this twice.
26526 */
26527 function loadCompiler(name, relativeToPath) {
26528 const compiler = require.resolve(name || 'typescript', {
26529 paths: [relativeToPath, __dirname],
26530 });
26531 const ts = commonjsRequire(compiler);
26532 return { compiler, ts };
26533 }
26534 // Compute minimum options to read the config file.
26535 let { compiler, ts } = loadCompiler(compilerName, (_f = (_e = rawOptions.projectSearchDir) !== null && _e !== void 0 ? _e : rawOptions.project) !== null && _f !== void 0 ? _f : cwd);
26536 // Read config file and merge new options between env and CLI options.
26537 const { configFilePath, config, tsNodeOptionsFromTsconfig } = configuration_1.readConfig(cwd, ts, rawOptions);
26538 const options = util_1.assign({}, exports.DEFAULTS, tsNodeOptionsFromTsconfig || {}, rawOptions);
26539 options.require = [
26540 ...(tsNodeOptionsFromTsconfig.require || []),
26541 ...(rawOptions.require || []),
26542 ];
26543 // Re-load the compiler in case it has changed.
26544 // Compiler is loaded relative to tsconfig.json, so tsconfig discovery may cause us to load a
26545 // different compiler than we did above, even if the name has not changed.
26546 if (configFilePath) {
26547 ({ compiler, ts } = loadCompiler(options.compiler, configFilePath));
26548 }
26549 const readFile = options.readFile || ts.sys.readFile;
26550 const fileExists = options.fileExists || ts.sys.fileExists;
26551 // typeCheck can override transpileOnly, useful for CLI flag to override config file
26552 const transpileOnly = options.transpileOnly === true && options.typeCheck !== true;
26553 const transformers = options.transformers || undefined;
26554 const ignoreDiagnostics = [
26555 6059,
26556 18002,
26557 18003,
26558 ...(options.ignoreDiagnostics || []),
26559 ].map(Number);
26560 const configDiagnosticList = filterDiagnostics(config.errors, ignoreDiagnostics);
26561 const outputCache = new Map();
26562 const configFileDirname = configFilePath ? path_1.dirname(configFilePath) : null;
26563 const scopeDir = (_j = (_h = (_g = options.scopeDir) !== null && _g !== void 0 ? _g : config.options.rootDir) !== null && _h !== void 0 ? _h : configFileDirname) !== null && _j !== void 0 ? _j : cwd;
26564 const ignoreBaseDir = configFileDirname !== null && configFileDirname !== void 0 ? configFileDirname : cwd;
26565 const isScoped = options.scope
26566 ? (fileName) => path_1.relative(scopeDir, fileName).charAt(0) !== '.'
26567 : () => true;
26568 const shouldIgnore = createIgnore(ignoreBaseDir, options.skipIgnore
26569 ? []
26570 : (options.ignore || ['(?:^|/)node_modules/']).map((str) => new RegExp(str)));
26571 const diagnosticHost = {
26572 getNewLine: () => ts.sys.newLine,
26573 getCurrentDirectory: () => cwd,
26574 getCanonicalFileName: ts.sys.useCaseSensitiveFileNames
26575 ? (x) => x
26576 : (x) => x.toLowerCase(),
26577 };
26578 if (options.transpileOnly && typeof transformers === 'function') {
26579 throw new TypeError('Transformers function is unavailable in "--transpile-only"');
26580 }
26581 let customTranspiler = undefined;
26582 if (options.transpiler) {
26583 if (!transpileOnly)
26584 throw new Error('Custom transpiler can only be used when transpileOnly is enabled.');
26585 const transpilerName = typeof options.transpiler === 'string'
26586 ? options.transpiler
26587 : options.transpiler[0];
26588 const transpilerOptions = typeof options.transpiler === 'string' ? {} : (_k = options.transpiler[1]) !== null && _k !== void 0 ? _k : {};
26589 // TODO mimic fixed resolution logic from loadCompiler main
26590 // TODO refactor into a more generic "resolve dep relative to project" helper
26591 const transpilerPath = require.resolve(transpilerName, {
26592 paths: [cwd, __dirname],
26593 });
26594 const transpilerFactory = commonjsRequire(transpilerPath).create;
26595 customTranspiler = transpilerFactory(Object.assign({ service: { options, config } }, transpilerOptions));
26596 }
26597 // Install source map support and read from memory cache.
26598 sourceMapSupport$1.install({
26599 environment: 'node',
26600 retrieveFile(pathOrUrl) {
26601 var _a;
26602 let path = pathOrUrl;
26603 // If it's a file URL, convert to local path
26604 // Note: fileURLToPath does not exist on early node v10
26605 // I could not find a way to handle non-URLs except to swallow an error
26606 if (options.experimentalEsmLoader && path.startsWith('file://')) {
26607 try {
26608 path = url_1.fileURLToPath(path);
26609 }
26610 catch (e) {
26611 /* swallow error */
26612 }
26613 }
26614 path = util_1.normalizeSlashes(path);
26615 return ((_a = outputCache.get(path)) === null || _a === void 0 ? void 0 : _a.content) || '';
26616 },
26617 });
26618 const formatDiagnostics = process.stdout.isTTY || options.pretty
26619 ? ts.formatDiagnosticsWithColorAndContext || ts.formatDiagnostics
26620 : ts.formatDiagnostics;
26621 function createTSError(diagnostics) {
26622 const diagnosticText = formatDiagnostics(diagnostics, diagnosticHost);
26623 const diagnosticCodes = diagnostics.map((x) => x.code);
26624 return new TSError(diagnosticText, diagnosticCodes);
26625 }
26626 function reportTSError(configDiagnosticList) {
26627 const error = createTSError(configDiagnosticList);
26628 if (options.logError) {
26629 // Print error in red color and continue execution.
26630 console.error('\x1b[31m%s\x1b[0m', error);
26631 }
26632 else {
26633 // Throw error and exit the script.
26634 throw error;
26635 }
26636 }
26637 // Render the configuration errors.
26638 if (configDiagnosticList.length)
26639 reportTSError(configDiagnosticList);
26640 /**
26641 * Get the extension for a transpiled file.
26642 */
26643 const getExtension = config.options.jsx === ts.JsxEmit.Preserve
26644 ? (path) => (/\.[tj]sx$/.test(path) ? '.jsx' : '.js')
26645 : (_) => '.js';
26646 /**
26647 * Create the basic required function using transpile mode.
26648 */
26649 let getOutput;
26650 let getTypeInfo;
26651 const getCanonicalFileName = ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames);
26652 // In a factory because these are shared across both CompilerHost and LanguageService codepaths
26653 function createResolverFunctions(serviceHost) {
26654 const moduleResolutionCache = ts.createModuleResolutionCache(cwd, getCanonicalFileName, config.options);
26655 const knownInternalFilenames = new Set();
26656 /** "Buckets" (module directories) whose contents should be marked "internal" */
26657 const internalBuckets = new Set();
26658 // Get bucket for a source filename. Bucket is the containing `./node_modules/*/` directory
26659 // For '/project/node_modules/foo/node_modules/bar/lib/index.js' bucket is '/project/node_modules/foo/node_modules/bar/'
26660 // For '/project/node_modules/foo/node_modules/@scope/bar/lib/index.js' bucket is '/project/node_modules/foo/node_modules/@scope/bar/'
26661 const moduleBucketRe = /.*\/node_modules\/(?:@[^\/]+\/)?[^\/]+\//;
26662 function getModuleBucket(filename) {
26663 const find = moduleBucketRe.exec(filename);
26664 if (find)
26665 return find[0];
26666 return '';
26667 }
26668 // Mark that this file and all siblings in its bucket should be "internal"
26669 function markBucketOfFilenameInternal(filename) {
26670 internalBuckets.add(getModuleBucket(filename));
26671 }
26672 function isFileInInternalBucket(filename) {
26673 return internalBuckets.has(getModuleBucket(filename));
26674 }
26675 function isFileKnownToBeInternal(filename) {
26676 return knownInternalFilenames.has(filename);
26677 }
26678 /**
26679 * If we need to emit JS for a file, force TS to consider it non-external
26680 */
26681 const fixupResolvedModule = (resolvedModule) => {
26682 const { resolvedFileName } = resolvedModule;
26683 if (resolvedFileName === undefined)
26684 return;
26685 // .ts is always switched to internal
26686 // .js is switched on-demand
26687 if (resolvedModule.isExternalLibraryImport &&
26688 ((resolvedFileName.endsWith('.ts') &&
26689 !resolvedFileName.endsWith('.d.ts')) ||
26690 isFileKnownToBeInternal(resolvedFileName) ||
26691 isFileInInternalBucket(resolvedFileName))) {
26692 resolvedModule.isExternalLibraryImport = false;
26693 }
26694 if (!resolvedModule.isExternalLibraryImport) {
26695 knownInternalFilenames.add(resolvedFileName);
26696 }
26697 };
26698 /*
26699 * NOTE:
26700 * Older ts versions do not pass `redirectedReference` nor `options`.
26701 * We must pass `redirectedReference` to newer ts versions, but cannot rely on `options`, hence the weird argument name
26702 */
26703 const resolveModuleNames = (moduleNames, containingFile, reusedNames, redirectedReference, optionsOnlyWithNewerTsVersions) => {
26704 return moduleNames.map((moduleName) => {
26705 const { resolvedModule } = ts.resolveModuleName(moduleName, containingFile, config.options, serviceHost, moduleResolutionCache, redirectedReference);
26706 if (resolvedModule) {
26707 fixupResolvedModule(resolvedModule);
26708 }
26709 return resolvedModule;
26710 });
26711 };
26712 // language service never calls this, but TS docs recommend that we implement it
26713 const getResolvedModuleWithFailedLookupLocationsFromCache = (moduleName, containingFile) => {
26714 const ret = ts.resolveModuleNameFromCache(moduleName, containingFile, moduleResolutionCache);
26715 if (ret && ret.resolvedModule) {
26716 fixupResolvedModule(ret.resolvedModule);
26717 }
26718 return ret;
26719 };
26720 const resolveTypeReferenceDirectives = (typeDirectiveNames, containingFile, redirectedReference, options) => {
26721 // Note: seems to be called with empty typeDirectiveNames array for all files.
26722 return typeDirectiveNames.map((typeDirectiveName) => {
26723 let { resolvedTypeReferenceDirective, } = ts.resolveTypeReferenceDirective(typeDirectiveName, containingFile, config.options, serviceHost, redirectedReference);
26724 if (typeDirectiveName === 'node' && !resolvedTypeReferenceDirective) {
26725 // Resolve @types/node relative to project first, then __dirname (copy logic from elsewhere / refactor into reusable function)
26726 const typesNodePackageJsonPath = require.resolve('@types/node/package.json', {
26727 paths: [configFilePath !== null && configFilePath !== void 0 ? configFilePath : cwd, __dirname],
26728 });
26729 const typeRoots = [path_1.resolve(typesNodePackageJsonPath, '../..')];
26730 ({
26731 resolvedTypeReferenceDirective,
26732 } = ts.resolveTypeReferenceDirective(typeDirectiveName, containingFile, Object.assign(Object.assign({}, config.options), { typeRoots }), serviceHost, redirectedReference));
26733 }
26734 if (resolvedTypeReferenceDirective) {
26735 fixupResolvedModule(resolvedTypeReferenceDirective);
26736 }
26737 return resolvedTypeReferenceDirective;
26738 });
26739 };
26740 return {
26741 resolveModuleNames,
26742 getResolvedModuleWithFailedLookupLocationsFromCache,
26743 resolveTypeReferenceDirectives,
26744 isFileKnownToBeInternal,
26745 markBucketOfFilenameInternal,
26746 };
26747 }
26748 // Use full language services when the fast option is disabled.
26749 if (!transpileOnly) {
26750 const fileContents = new Map();
26751 const rootFileNames = new Set(config.fileNames);
26752 const cachedReadFile = cachedLookup(debugFn('readFile', readFile));
26753 // Use language services by default (TODO: invert next major version).
26754 if (!options.compilerHost) {
26755 let projectVersion = 1;
26756 const fileVersions = new Map(Array.from(rootFileNames).map((fileName) => [fileName, 0]));
26757 const getCustomTransformers = () => {
26758 if (typeof transformers === 'function') {
26759 const program = service.getProgram();
26760 return program ? transformers(program) : undefined;
26761 }
26762 return transformers;
26763 };
26764 // Create the compiler host for type checking.
26765 const serviceHost = {
26766 getProjectVersion: () => String(projectVersion),
26767 getScriptFileNames: () => Array.from(rootFileNames),
26768 getScriptVersion: (fileName) => {
26769 const version = fileVersions.get(fileName);
26770 return version ? version.toString() : '';
26771 },
26772 getScriptSnapshot(fileName) {
26773 // TODO ordering of this with getScriptVersion? Should they sync up?
26774 let contents = fileContents.get(fileName);
26775 // Read contents into TypeScript memory cache.
26776 if (contents === undefined) {
26777 contents = cachedReadFile(fileName);
26778 if (contents === undefined)
26779 return;
26780 fileVersions.set(fileName, 1);
26781 fileContents.set(fileName, contents);
26782 projectVersion++;
26783 }
26784 return ts.ScriptSnapshot.fromString(contents);
26785 },
26786 readFile: cachedReadFile,
26787 readDirectory: ts.sys.readDirectory,
26788 getDirectories: cachedLookup(debugFn('getDirectories', ts.sys.getDirectories)),
26789 fileExists: cachedLookup(debugFn('fileExists', fileExists)),
26790 directoryExists: cachedLookup(debugFn('directoryExists', ts.sys.directoryExists)),
26791 realpath: ts.sys.realpath
26792 ? cachedLookup(debugFn('realpath', ts.sys.realpath))
26793 : undefined,
26794 getNewLine: () => ts.sys.newLine,
26795 useCaseSensitiveFileNames: () => ts.sys.useCaseSensitiveFileNames,
26796 getCurrentDirectory: () => cwd,
26797 getCompilationSettings: () => config.options,
26798 getDefaultLibFileName: () => ts.getDefaultLibFilePath(config.options),
26799 getCustomTransformers: getCustomTransformers,
26800 };
26801 const { resolveModuleNames, getResolvedModuleWithFailedLookupLocationsFromCache, resolveTypeReferenceDirectives, isFileKnownToBeInternal, markBucketOfFilenameInternal, } = createResolverFunctions(serviceHost);
26802 serviceHost.resolveModuleNames = resolveModuleNames;
26803 serviceHost.getResolvedModuleWithFailedLookupLocationsFromCache = getResolvedModuleWithFailedLookupLocationsFromCache;
26804 serviceHost.resolveTypeReferenceDirectives = resolveTypeReferenceDirectives;
26805 const registry = ts.createDocumentRegistry(ts.sys.useCaseSensitiveFileNames, cwd);
26806 const service = ts.createLanguageService(serviceHost, registry);
26807 const updateMemoryCache = (contents, fileName) => {
26808 // Add to `rootFiles` as necessary, either to make TS include a file it has not seen,
26809 // or to trigger a re-classification of files from external to internal.
26810 if (!rootFileNames.has(fileName) &&
26811 !isFileKnownToBeInternal(fileName)) {
26812 markBucketOfFilenameInternal(fileName);
26813 rootFileNames.add(fileName);
26814 // Increment project version for every change to rootFileNames.
26815 projectVersion++;
26816 }
26817 const previousVersion = fileVersions.get(fileName) || 0;
26818 const previousContents = fileContents.get(fileName);
26819 // Avoid incrementing cache when nothing has changed.
26820 if (contents !== previousContents) {
26821 fileVersions.set(fileName, previousVersion + 1);
26822 fileContents.set(fileName, contents);
26823 // Increment project version for every file change.
26824 projectVersion++;
26825 }
26826 };
26827 let previousProgram = undefined;
26828 getOutput = (code, fileName) => {
26829 updateMemoryCache(code, fileName);
26830 const programBefore = service.getProgram();
26831 if (programBefore !== previousProgram) {
26832 exports.debug(`compiler rebuilt Program instance when getting output for ${fileName}`);
26833 }
26834 const output = service.getEmitOutput(fileName);
26835 // Get the relevant diagnostics - this is 3x faster than `getPreEmitDiagnostics`.
26836 const diagnostics = service
26837 .getSemanticDiagnostics(fileName)
26838 .concat(service.getSyntacticDiagnostics(fileName));
26839 const programAfter = service.getProgram();
26840 exports.debug('invariant: Is service.getProject() identical before and after getting emit output and diagnostics? (should always be true) ', programBefore === programAfter);
26841 previousProgram = programAfter;
26842 const diagnosticList = filterDiagnostics(diagnostics, ignoreDiagnostics);
26843 if (diagnosticList.length)
26844 reportTSError(diagnosticList);
26845 if (output.emitSkipped) {
26846 throw new TypeError(`${path_1.relative(cwd, fileName)}: Emit skipped`);
26847 }
26848 // Throw an error when requiring `.d.ts` files.
26849 if (output.outputFiles.length === 0) {
26850 throw new TypeError(`Unable to require file: ${path_1.relative(cwd, fileName)}\n` +
26851 'This is usually the result of a faulty configuration or import. ' +
26852 'Make sure there is a `.js`, `.json` or other executable extension with ' +
26853 'loader attached before `ts-node` available.');
26854 }
26855 return [output.outputFiles[1].text, output.outputFiles[0].text];
26856 };
26857 getTypeInfo = (code, fileName, position) => {
26858 updateMemoryCache(code, fileName);
26859 const info = service.getQuickInfoAtPosition(fileName, position);
26860 const name = ts.displayPartsToString(info ? info.displayParts : []);
26861 const comment = ts.displayPartsToString(info ? info.documentation : []);
26862 return { name, comment };
26863 };
26864 }
26865 else {
26866 const sys = Object.assign(Object.assign(Object.assign({}, ts.sys), diagnosticHost), { readFile: (fileName) => {
26867 const cacheContents = fileContents.get(fileName);
26868 if (cacheContents !== undefined)
26869 return cacheContents;
26870 const contents = cachedReadFile(fileName);
26871 if (contents)
26872 fileContents.set(fileName, contents);
26873 return contents;
26874 }, readDirectory: ts.sys.readDirectory, getDirectories: cachedLookup(debugFn('getDirectories', ts.sys.getDirectories)), fileExists: cachedLookup(debugFn('fileExists', fileExists)), directoryExists: cachedLookup(debugFn('directoryExists', ts.sys.directoryExists)), resolvePath: cachedLookup(debugFn('resolvePath', ts.sys.resolvePath)), realpath: ts.sys.realpath
26875 ? cachedLookup(debugFn('realpath', ts.sys.realpath))
26876 : undefined });
26877 const host = ts.createIncrementalCompilerHost
26878 ? ts.createIncrementalCompilerHost(config.options, sys)
26879 : Object.assign(Object.assign({}, sys), { getSourceFile: (fileName, languageVersion) => {
26880 const contents = sys.readFile(fileName);
26881 if (contents === undefined)
26882 return;
26883 return ts.createSourceFile(fileName, contents, languageVersion);
26884 }, getDefaultLibLocation: () => util_1.normalizeSlashes(path_1.dirname(compiler)), getDefaultLibFileName: () => util_1.normalizeSlashes(path_1.join(path_1.dirname(compiler), ts.getDefaultLibFileName(config.options))), useCaseSensitiveFileNames: () => sys.useCaseSensitiveFileNames });
26885 const { resolveModuleNames, resolveTypeReferenceDirectives, isFileKnownToBeInternal, markBucketOfFilenameInternal, } = createResolverFunctions(host);
26886 host.resolveModuleNames = resolveModuleNames;
26887 host.resolveTypeReferenceDirectives = resolveTypeReferenceDirectives;
26888 // Fallback for older TypeScript releases without incremental API.
26889 let builderProgram = ts.createIncrementalProgram
26890 ? ts.createIncrementalProgram({
26891 rootNames: Array.from(rootFileNames),
26892 options: config.options,
26893 host: host,
26894 configFileParsingDiagnostics: config.errors,
26895 projectReferences: config.projectReferences,
26896 })
26897 : ts.createEmitAndSemanticDiagnosticsBuilderProgram(Array.from(rootFileNames), config.options, host, undefined, config.errors, config.projectReferences);
26898 // Read and cache custom transformers.
26899 const customTransformers = typeof transformers === 'function'
26900 ? transformers(builderProgram.getProgram())
26901 : transformers;
26902 // Set the file contents into cache manually.
26903 const updateMemoryCache = (contents, fileName) => {
26904 const previousContents = fileContents.get(fileName);
26905 const contentsChanged = previousContents !== contents;
26906 if (contentsChanged) {
26907 fileContents.set(fileName, contents);
26908 }
26909 // Add to `rootFiles` when discovered by compiler for the first time.
26910 let addedToRootFileNames = false;
26911 if (!rootFileNames.has(fileName) &&
26912 !isFileKnownToBeInternal(fileName)) {
26913 markBucketOfFilenameInternal(fileName);
26914 rootFileNames.add(fileName);
26915 addedToRootFileNames = true;
26916 }
26917 // Update program when file changes.
26918 if (addedToRootFileNames || contentsChanged) {
26919 builderProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram(Array.from(rootFileNames), config.options, host, builderProgram, config.errors, config.projectReferences);
26920 }
26921 };
26922 getOutput = (code, fileName) => {
26923 const output = ['', ''];
26924 updateMemoryCache(code, fileName);
26925 const sourceFile = builderProgram.getSourceFile(fileName);
26926 if (!sourceFile)
26927 throw new TypeError(`Unable to read file: ${fileName}`);
26928 const program = builderProgram.getProgram();
26929 const diagnostics = ts.getPreEmitDiagnostics(program, sourceFile);
26930 const diagnosticList = filterDiagnostics(diagnostics, ignoreDiagnostics);
26931 if (diagnosticList.length)
26932 reportTSError(diagnosticList);
26933 const result = builderProgram.emit(sourceFile, (path, file, writeByteOrderMark) => {
26934 if (path.endsWith('.map')) {
26935 output[1] = file;
26936 }
26937 else {
26938 output[0] = file;
26939 }
26940 if (options.emit)
26941 sys.writeFile(path, file, writeByteOrderMark);
26942 }, undefined, undefined, customTransformers);
26943 if (result.emitSkipped) {
26944 throw new TypeError(`${path_1.relative(cwd, fileName)}: Emit skipped`);
26945 }
26946 // Throw an error when requiring files that cannot be compiled.
26947 if (output[0] === '') {
26948 if (program.isSourceFileFromExternalLibrary(sourceFile)) {
26949 throw new TypeError(`Unable to compile file from external library: ${path_1.relative(cwd, fileName)}`);
26950 }
26951 throw new TypeError(`Unable to require file: ${path_1.relative(cwd, fileName)}\n` +
26952 'This is usually the result of a faulty configuration or import. ' +
26953 'Make sure there is a `.js`, `.json` or other executable extension with ' +
26954 'loader attached before `ts-node` available.');
26955 }
26956 return output;
26957 };
26958 getTypeInfo = (code, fileName, position) => {
26959 updateMemoryCache(code, fileName);
26960 const sourceFile = builderProgram.getSourceFile(fileName);
26961 if (!sourceFile)
26962 throw new TypeError(`Unable to read file: ${fileName}`);
26963 const node = getTokenAtPosition(ts, sourceFile, position);
26964 const checker = builderProgram.getProgram().getTypeChecker();
26965 const symbol = checker.getSymbolAtLocation(node);
26966 if (!symbol)
26967 return { name: '', comment: '' };
26968 const type = checker.getTypeOfSymbolAtLocation(symbol, node);
26969 const signatures = [
26970 ...type.getConstructSignatures(),
26971 ...type.getCallSignatures(),
26972 ];
26973 return {
26974 name: signatures.length
26975 ? signatures.map((x) => checker.signatureToString(x)).join('\n')
26976 : checker.typeToString(type),
26977 comment: ts.displayPartsToString(symbol ? symbol.getDocumentationComment(checker) : []),
26978 };
26979 };
26980 // Write `.tsbuildinfo` when `--build` is enabled.
26981 if (options.emit && config.options.incremental) {
26982 process.on('exit', () => {
26983 // Emits `.tsbuildinfo` to filesystem.
26984 builderProgram.getProgram().emitBuildInfo();
26985 });
26986 }
26987 }
26988 }
26989 else {
26990 getOutput = (code, fileName) => {
26991 let result;
26992 if (customTranspiler) {
26993 result = customTranspiler.transpile(code, {
26994 fileName,
26995 });
26996 }
26997 else {
26998 result = ts.transpileModule(code, {
26999 fileName,
27000 compilerOptions: config.options,
27001 reportDiagnostics: true,
27002 transformers: transformers,
27003 });
27004 }
27005 const diagnosticList = filterDiagnostics(result.diagnostics || [], ignoreDiagnostics);
27006 if (diagnosticList.length)
27007 reportTSError(diagnosticList);
27008 return [result.outputText, result.sourceMapText];
27009 };
27010 getTypeInfo = () => {
27011 throw new TypeError('Type information is unavailable in "--transpile-only"');
27012 };
27013 }
27014 // Create a simple TypeScript compiler proxy.
27015 function compile(code, fileName, lineOffset = 0) {
27016 const normalizedFileName = util_1.normalizeSlashes(fileName);
27017 const [value, sourceMap] = getOutput(code, normalizedFileName);
27018 const output = updateOutput(value, normalizedFileName, sourceMap, getExtension);
27019 outputCache.set(normalizedFileName, { content: output });
27020 return output;
27021 }
27022 let active = true;
27023 const enabled = (enabled) => enabled === undefined ? active : (active = !!enabled);
27024 const extensions = getExtensions(config);
27025 const ignored = (fileName) => {
27026 if (!active)
27027 return true;
27028 const ext = path_1.extname(fileName);
27029 if (extensions.tsExtensions.includes(ext) ||
27030 extensions.jsExtensions.includes(ext)) {
27031 return !isScoped(fileName) || shouldIgnore(fileName);
27032 }
27033 return true;
27034 };
27035 return {
27036 ts,
27037 config,
27038 compile,
27039 getTypeInfo,
27040 ignored,
27041 enabled,
27042 options,
27043 configFilePath,
27044 };
27045}
27046exports.create = create;
27047/**
27048 * Check if the filename should be ignored.
27049 */
27050function createIgnore(ignoreBaseDir, ignore) {
27051 return (fileName) => {
27052 const relname = path_1.relative(ignoreBaseDir, fileName);
27053 const path = util_1.normalizeSlashes(relname);
27054 return ignore.some((x) => x.test(path));
27055 };
27056}
27057/**
27058 * "Refreshes" an extension on `require.extensions`.
27059 *
27060 * @param {string} ext
27061 */
27062function reorderRequireExtension(ext) {
27063 const old = commonjsRequire.extensions[ext];
27064 delete commonjsRequire.extensions[ext];
27065 commonjsRequire.extensions[ext] = old;
27066}
27067/**
27068 * Register the extensions to support when importing files.
27069 */
27070function registerExtensions(preferTsExts, extensions, service, originalJsHandler) {
27071 // Register new extensions.
27072 for (const ext of extensions) {
27073 registerExtension(ext, service, originalJsHandler);
27074 }
27075 if (preferTsExts) {
27076 const preferredExtensions = new Set([
27077 ...extensions,
27078 ...Object.keys(commonjsRequire.extensions),
27079 ]);
27080 for (const ext of preferredExtensions)
27081 reorderRequireExtension(ext);
27082 }
27083}
27084/**
27085 * Register the extension for node.
27086 */
27087function registerExtension(ext, service, originalHandler) {
27088 const old = commonjsRequire.extensions[ext] || originalHandler;
27089 commonjsRequire.extensions[ext] = function (m, filename) {
27090 if (service.ignored(filename))
27091 return old(m, filename);
27092 assertScriptCanLoadAsCJS(filename);
27093 const _compile = m._compile;
27094 m._compile = function (code, fileName) {
27095 exports.debug('module._compile', fileName);
27096 return _compile.call(this, service.compile(code, fileName), fileName);
27097 };
27098 return old(m, filename);
27099 };
27100}
27101/**
27102 * Update the output remapping the source map.
27103 */
27104function updateOutput(outputText, fileName, sourceMap, getExtension) {
27105 const base64Map = Buffer.from(updateSourceMap(sourceMap, fileName), 'utf8').toString('base64');
27106 const sourceMapContent = `//# sourceMappingURL=data:application/json;charset=utf-8;base64,${base64Map}`;
27107 // Expected form: `//# sourceMappingURL=foo bar.js.map` or `//# sourceMappingURL=foo%20bar.js.map` for input file "foo bar.tsx"
27108 // Percent-encoding behavior added in TS 4.1.1: https://github.com/microsoft/TypeScript/issues/40951
27109 const prefix = '//# sourceMappingURL=';
27110 const prefixLength = prefix.length;
27111 const baseName = /*foo.tsx*/ path_1.basename(fileName);
27112 const extName = /*.tsx*/ path_1.extname(fileName);
27113 const extension = /*.js*/ getExtension(fileName);
27114 const sourcemapFilename = baseName.slice(0, -extName.length) + extension + '.map';
27115 const sourceMapLengthWithoutPercentEncoding = prefixLength + sourcemapFilename.length;
27116 /*
27117 * Only rewrite if existing directive exists at the location we expect, to support:
27118 * a) compilers that do not append a sourcemap directive
27119 * b) situations where we did the math wrong
27120 * Not ideal, but appending our sourcemap *after* a pre-existing sourcemap still overrides, so the end-user is happy.
27121 */
27122 if (outputText.substr(-sourceMapLengthWithoutPercentEncoding, prefixLength) ===
27123 prefix) {
27124 return (outputText.slice(0, -sourceMapLengthWithoutPercentEncoding) +
27125 sourceMapContent);
27126 }
27127 // If anyone asks why we're not using URL, the URL equivalent is: `u = new URL('http://d'); u.pathname = "/" + sourcemapFilename; return u.pathname.slice(1);
27128 const sourceMapLengthWithPercentEncoding = prefixLength + encodeURI(sourcemapFilename).length;
27129 if (outputText.substr(-sourceMapLengthWithPercentEncoding, prefixLength) ===
27130 prefix) {
27131 return (outputText.slice(0, -sourceMapLengthWithPercentEncoding) +
27132 sourceMapContent);
27133 }
27134 return `${outputText}\n${sourceMapContent}`;
27135}
27136/**
27137 * Update the source map contents for improved output.
27138 */
27139function updateSourceMap(sourceMapText, fileName) {
27140 const sourceMap = JSON.parse(sourceMapText);
27141 sourceMap.file = fileName;
27142 sourceMap.sources = [fileName];
27143 delete sourceMap.sourceRoot;
27144 return JSON.stringify(sourceMap);
27145}
27146/**
27147 * Filter diagnostics.
27148 */
27149function filterDiagnostics(diagnostics, ignore) {
27150 return diagnostics.filter((x) => ignore.indexOf(x.code) === -1);
27151}
27152/**
27153 * Get token at file position.
27154 *
27155 * Reference: https://github.com/microsoft/TypeScript/blob/fcd9334f57d85b73dd66ad2d21c02e84822f4841/src/services/utilities.ts#L705-L731
27156 */
27157function getTokenAtPosition(ts, sourceFile, position) {
27158 let current = sourceFile;
27159 outer: while (true) {
27160 for (const child of current.getChildren(sourceFile)) {
27161 const start = child.getFullStart();
27162 if (start > position)
27163 break;
27164 const end = child.getEnd();
27165 if (position <= end) {
27166 current = child;
27167 continue outer;
27168 }
27169 }
27170 return current;
27171 }
27172}
27173
27174}(dist$1));
27175
27176const resolve$2 = path__default.resolve;
27177
27178const config$1 = dist$3;
27179const yaml = yaml$1;
27180
27181const loadOptions = options_1;
27182const loadPlugins = plugins_1;
27183
27184/* istanbul ignore next */
27185const interopRequireDefault = (obj) => obj && obj.__esModule ? obj : { default: obj };
27186
27187/**
27188 * Process the result from cosmiconfig
27189 *
27190 * @param {Object} ctx Config Context
27191 * @param {Object} result Cosmiconfig result
27192 *
27193 * @return {Object} PostCSS Config
27194 */
27195const processResult = (ctx, result) => {
27196 const file = result.filepath || '';
27197 let config = interopRequireDefault(result.config).default || {};
27198
27199 if (typeof config === 'function') {
27200 config = config(ctx);
27201 } else {
27202 config = Object.assign({}, config, ctx);
27203 }
27204
27205 if (!config.plugins) {
27206 config.plugins = [];
27207 }
27208
27209 return {
27210 plugins: loadPlugins(config, file),
27211 options: loadOptions(config, file),
27212 file: file
27213 }
27214};
27215
27216/**
27217 * Builds the Config Context
27218 *
27219 * @param {Object} ctx Config Context
27220 *
27221 * @return {Object} Config Context
27222 */
27223const createContext = (ctx) => {
27224 /**
27225 * @type {Object}
27226 *
27227 * @prop {String} cwd=process.cwd() Config search start location
27228 * @prop {String} env=process.env.NODE_ENV Config Enviroment, will be set to `development` by `postcss-load-config` if `process.env.NODE_ENV` is `undefined`
27229 */
27230 ctx = Object.assign({
27231 cwd: process.cwd(),
27232 env: process.env.NODE_ENV
27233 }, ctx);
27234
27235 if (!ctx.env) {
27236 process.env.NODE_ENV = 'development';
27237 }
27238
27239 return ctx
27240};
27241
27242const addTypeScriptLoader = (options = {}, loader) => {
27243 const moduleName = 'postcss';
27244
27245 return {
27246 ...options,
27247 searchPlaces: [
27248 ...(options.searchPlaces || []),
27249 'package.json',
27250 `.${moduleName}rc`,
27251 `.${moduleName}rc.json`,
27252 `.${moduleName}rc.yaml`,
27253 `.${moduleName}rc.yml`,
27254 `.${moduleName}rc.ts`,
27255 `.${moduleName}rc.js`,
27256 `.${moduleName}rc.cjs`,
27257 `${moduleName}.config.ts`,
27258 `${moduleName}.config.js`,
27259 `${moduleName}.config.cjs`
27260 ],
27261 loaders: {
27262 ...options.loaders,
27263 '.yaml': (filepath, content) => yaml.parse(content),
27264 '.yml': (filepath, content) => yaml.parse(content),
27265 '.ts': loader
27266 }
27267 }
27268};
27269
27270const withTypeScriptLoader = (rcFunc) => {
27271 return (ctx, path, options) => {
27272 return rcFunc(ctx, path, addTypeScriptLoader(options, (configFile) => {
27273 let registerer = { enabled () {} };
27274
27275 try {
27276 // Register TypeScript compiler instance
27277 registerer = dist$1.register();
27278
27279 return commonjsRequire(configFile)
27280 } catch (err) {
27281 if (err.code === 'MODULE_NOT_FOUND') {
27282 throw new Error(
27283 `'ts-node' is required for the TypeScript configuration files. Make sure it is installed\nError: ${err.message}`
27284 )
27285 }
27286
27287 throw err
27288 } finally {
27289 registerer.enabled(false);
27290 }
27291 }))
27292 }
27293};
27294
27295/**
27296 * Load Config
27297 *
27298 * @method rc
27299 *
27300 * @param {Object} ctx Config Context
27301 * @param {String} path Config Path
27302 * @param {Object} options Config Options
27303 *
27304 * @return {Promise} config PostCSS Config
27305 */
27306const rc = withTypeScriptLoader((ctx, path, options) => {
27307 /**
27308 * @type {Object} The full Config Context
27309 */
27310 ctx = createContext(ctx);
27311
27312 /**
27313 * @type {String} `process.cwd()`
27314 */
27315 path = path ? resolve$2(path) : process.cwd();
27316
27317 return config$1.lilconfig('postcss', options)
27318 .search(path)
27319 .then((result) => {
27320 if (!result) {
27321 throw new Error(`No PostCSS Config found in: ${path}`)
27322 }
27323
27324 return processResult(ctx, result)
27325 })
27326});
27327
27328rc.sync = withTypeScriptLoader((ctx, path, options) => {
27329 /**
27330 * @type {Object} The full Config Context
27331 */
27332 ctx = createContext(ctx);
27333
27334 /**
27335 * @type {String} `process.cwd()`
27336 */
27337 path = path ? resolve$2(path) : process.cwd();
27338
27339 const result = config$1.lilconfigSync('postcss', options).search(path);
27340
27341 if (!result) {
27342 throw new Error(`No PostCSS Config found in: ${path}`)
27343 }
27344
27345 return processResult(ctx, result)
27346});
27347
27348/**
27349 * Autoload Config for PostCSS
27350 *
27351 * @author Michael Ciniawsky @michael-ciniawsky <michael.ciniawsky@gmail.com>
27352 * @license MIT
27353 *
27354 * @module postcss-load-config
27355 * @version 2.1.0
27356 *
27357 * @requires comsiconfig
27358 * @requires ./options
27359 * @requires ./plugins
27360 */
27361var src$3 = rc;
27362
27363// Helper since Typescript can't detect readonly arrays with Array.isArray
27364function isArray$3(arg) {
27365 return Array.isArray(arg);
27366}
27367function ensureArray$1(thing) {
27368 if (isArray$3(thing))
27369 return thing;
27370 if (thing == null)
27371 return [];
27372 return [thing];
27373}
27374
27375const normalizePath$3 = function (filename) {
27376 return filename.split(path$A.win32.sep).join(path$A.posix.sep);
27377};
27378
27379function getMatcherString$1(id, resolutionBase) {
27380 if (resolutionBase === false || path$A.isAbsolute(id) || id.startsWith('*')) {
27381 return id;
27382 }
27383 // resolve('') is valid and will default to process.cwd()
27384 const basePath = normalizePath$3(path$A.resolve(resolutionBase || ''))
27385 // escape all possible (posix + win) path characters that might interfere with regex
27386 .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
27387 // Note that we use posix.join because:
27388 // 1. the basePath has been normalized to use /
27389 // 2. the incoming glob (id) matcher, also uses /
27390 // otherwise Node will force backslash (\) on windows
27391 return path$A.posix.join(basePath, id);
27392}
27393const createFilter$1 = function createFilter(include, exclude, options) {
27394 const resolutionBase = options && options.resolve;
27395 const getMatcher = (id) => id instanceof RegExp
27396 ? id
27397 : {
27398 test: (what) => {
27399 // this refactor is a tad overly verbose but makes for easy debugging
27400 const pattern = getMatcherString$1(id, resolutionBase);
27401 const fn = picomatch$4(pattern, { dot: true });
27402 const result = fn(what);
27403 return result;
27404 }
27405 };
27406 const includeMatchers = ensureArray$1(include).map(getMatcher);
27407 const excludeMatchers = ensureArray$1(exclude).map(getMatcher);
27408 return function result(id) {
27409 if (typeof id !== 'string')
27410 return false;
27411 if (/\0/.test(id))
27412 return false;
27413 const pathId = normalizePath$3(id);
27414 for (let i = 0; i < excludeMatchers.length; ++i) {
27415 const matcher = excludeMatchers[i];
27416 if (matcher.test(pathId))
27417 return false;
27418 }
27419 for (let i = 0; i < includeMatchers.length; ++i) {
27420 const matcher = includeMatchers[i];
27421 if (matcher.test(pathId))
27422 return true;
27423 }
27424 return !includeMatchers.length;
27425 };
27426};
27427
27428const reservedWords$2 = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public';
27429const builtins$1 = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl';
27430const forbiddenIdentifiers$1 = new Set(`${reservedWords$2} ${builtins$1}`.split(' '));
27431forbiddenIdentifiers$1.add('');
27432const makeLegalIdentifier$1 = function makeLegalIdentifier(str) {
27433 let identifier = str
27434 .replace(/-(\w)/g, (_, letter) => letter.toUpperCase())
27435 .replace(/[^$_a-zA-Z0-9]/g, '_');
27436 if (/\d/.test(identifier[0]) || forbiddenIdentifiers$1.has(identifier)) {
27437 identifier = `_${identifier}`;
27438 }
27439 return identifier || '_';
27440};
27441
27442function stringify(obj) {
27443 return (JSON.stringify(obj) || 'undefined').replace(/[\u2028\u2029]/g, (char) => `\\u${`000${char.charCodeAt(0).toString(16)}`.slice(-4)}`);
27444}
27445function serializeArray(arr, indent, baseIndent) {
27446 let output = '[';
27447 const separator = indent ? `\n${baseIndent}${indent}` : '';
27448 for (let i = 0; i < arr.length; i++) {
27449 const key = arr[i];
27450 output += `${i > 0 ? ',' : ''}${separator}${serialize(key, indent, baseIndent + indent)}`;
27451 }
27452 return `${output}${indent ? `\n${baseIndent}` : ''}]`;
27453}
27454function serializeObject(obj, indent, baseIndent) {
27455 let output = '{';
27456 const separator = indent ? `\n${baseIndent}${indent}` : '';
27457 const entries = Object.entries(obj);
27458 for (let i = 0; i < entries.length; i++) {
27459 const [key, value] = entries[i];
27460 const stringKey = makeLegalIdentifier$1(key) === key ? key : stringify(key);
27461 output += `${i > 0 ? ',' : ''}${separator}${stringKey}:${indent ? ' ' : ''}${serialize(value, indent, baseIndent + indent)}`;
27462 }
27463 return `${output}${indent ? `\n${baseIndent}` : ''}}`;
27464}
27465function serialize(obj, indent, baseIndent) {
27466 if (obj === Infinity)
27467 return 'Infinity';
27468 if (obj === -Infinity)
27469 return '-Infinity';
27470 if (obj === 0 && 1 / obj === -Infinity)
27471 return '-0';
27472 if (obj instanceof Date)
27473 return `new Date(${obj.getTime()})`;
27474 if (obj instanceof RegExp)
27475 return obj.toString();
27476 if (obj !== obj)
27477 return 'NaN'; // eslint-disable-line no-self-compare
27478 if (Array.isArray(obj))
27479 return serializeArray(obj, indent, baseIndent);
27480 if (obj === null)
27481 return 'null';
27482 if (typeof obj === 'object')
27483 return serializeObject(obj, indent, baseIndent);
27484 return stringify(obj);
27485}
27486const dataToEsm = function dataToEsm(data, options = {}) {
27487 const t = options.compact ? '' : 'indent' in options ? options.indent : '\t';
27488 const _ = options.compact ? '' : ' ';
27489 const n = options.compact ? '' : '\n';
27490 const declarationType = options.preferConst ? 'const' : 'var';
27491 if (options.namedExports === false ||
27492 typeof data !== 'object' ||
27493 Array.isArray(data) ||
27494 data instanceof Date ||
27495 data instanceof RegExp ||
27496 data === null) {
27497 const code = serialize(data, options.compact ? null : t, '');
27498 const magic = _ || (/^[{[\-\/]/.test(code) ? '' : ' '); // eslint-disable-line no-useless-escape
27499 return `export default${magic}${code};`;
27500 }
27501 let namedExportCode = '';
27502 const defaultExportRows = [];
27503 for (const [key, value] of Object.entries(data)) {
27504 if (key === makeLegalIdentifier$1(key)) {
27505 if (options.objectShorthand)
27506 defaultExportRows.push(key);
27507 else
27508 defaultExportRows.push(`${key}:${_}${key}`);
27509 namedExportCode += `export ${declarationType} ${key}${_}=${_}${serialize(value, options.compact ? null : t, '')};${n}`;
27510 }
27511 else {
27512 defaultExportRows.push(`${stringify(key)}:${_}${serialize(value, options.compact ? null : t, '')}`);
27513 }
27514 }
27515 return `${namedExportCode}export default${_}{${n}${t}${defaultExportRows.join(`,${n}${t}`)}${n}};${n}`;
27516};
27517
27518const cssLangs = `\\.(css|less|sass|scss|styl|stylus|pcss|postcss)($|\\?)`;
27519const cssLangRE = new RegExp(cssLangs);
27520const cssModuleRE = new RegExp(`\\.module${cssLangs}`);
27521const directRequestRE = /(\?|&)direct\b/;
27522const commonjsProxyRE = /\?commonjs-proxy/;
27523const isCSSRequest = (request) => cssLangRE.test(request) && !directRequestRE.test(request);
27524const isDirectCSSRequest = (request) => cssLangRE.test(request) && directRequestRE.test(request);
27525const cssModulesCache = new WeakMap();
27526const chunkToEmittedCssFileMap = new WeakMap();
27527/**
27528 * Plugin applied before user plugins
27529 */
27530function cssPlugin(config) {
27531 let server;
27532 let moduleCache;
27533 const resolveUrl = config.createResolver({
27534 preferRelative: true,
27535 tryIndex: false,
27536 extensions: []
27537 });
27538 const atImportResolvers = createCSSResolvers(config);
27539 return {
27540 name: 'vite:css',
27541 configureServer(_server) {
27542 server = _server;
27543 },
27544 buildStart() {
27545 // Ensure a new cache for every build (i.e. rebuilding in watch mode)
27546 moduleCache = new Map();
27547 cssModulesCache.set(config, moduleCache);
27548 },
27549 async transform(raw, id) {
27550 if (!cssLangRE.test(id) || commonjsProxyRE.test(id)) {
27551 return;
27552 }
27553 const urlReplacer = async (url, importer) => {
27554 if (checkPublicFile(url, config)) {
27555 return config.base + url.slice(1);
27556 }
27557 const resolved = await resolveUrl(url, importer);
27558 if (resolved) {
27559 return fileToUrl(resolved, config, this);
27560 }
27561 return url;
27562 };
27563 const { code: css, modules, deps } = await compileCSS(id, raw, config, urlReplacer, atImportResolvers, server);
27564 if (modules) {
27565 moduleCache.set(id, modules);
27566 }
27567 // track deps for build watch mode
27568 if (config.command === 'build' && config.build.watch && deps) {
27569 for (const file of deps) {
27570 this.addWatchFile(file);
27571 }
27572 }
27573 // dev
27574 if (server) {
27575 // server only logic for handling CSS @import dependency hmr
27576 const { moduleGraph } = server;
27577 const thisModule = moduleGraph.getModuleById(id);
27578 // CSS modules cannot self-accept since it exports values
27579 const isSelfAccepting = !modules;
27580 if (deps) {
27581 // record deps in the module graph so edits to @import css can trigger
27582 // main import to hot update
27583 const depModules = new Set([...deps].map((file) => moduleGraph.createFileOnlyEntry(file)));
27584 moduleGraph.updateModuleInfo(thisModule, depModules,
27585 // The root CSS proxy module is self-accepting and should not
27586 // have an explicit accept list
27587 new Set(), isSelfAccepting);
27588 for (const file of deps) {
27589 this.addWatchFile(file);
27590 }
27591 }
27592 else {
27593 thisModule.isSelfAccepting = isSelfAccepting;
27594 }
27595 }
27596 return {
27597 code: css,
27598 // TODO CSS source map
27599 map: { mappings: '' }
27600 };
27601 }
27602 };
27603}
27604/**
27605 * Plugin applied after user plugins
27606 */
27607function cssPostPlugin(config) {
27608 // styles initialization in buildStart causes a styling loss in watch
27609 const styles = new Map();
27610 let pureCssChunks;
27611 // when there are multiple rollup outputs and extracting CSS, only emit once,
27612 // since output formats have no effect on the generated CSS.
27613 let outputToExtractedCSSMap;
27614 let hasEmitted = false;
27615 return {
27616 name: 'vite:css-post',
27617 buildStart() {
27618 // Ensure new caches for every build (i.e. rebuilding in watch mode)
27619 pureCssChunks = new Set();
27620 outputToExtractedCSSMap = new Map();
27621 hasEmitted = false;
27622 },
27623 transform(css, id, ssr) {
27624 if (!cssLangRE.test(id) || commonjsProxyRE.test(id)) {
27625 return;
27626 }
27627 const modules = cssModulesCache.get(config).get(id);
27628 const modulesCode = modules && dataToEsm(modules, { namedExports: true, preferConst: true });
27629 if (config.command === 'serve') {
27630 if (isDirectCSSRequest(id)) {
27631 return css;
27632 }
27633 else {
27634 // server only
27635 if (ssr) {
27636 return modulesCode || `export default ${JSON.stringify(css)}`;
27637 }
27638 return [
27639 `import { updateStyle, removeStyle } from ${JSON.stringify(path__default.posix.join(config.base, CLIENT_PUBLIC_PATH))}`,
27640 `const id = ${JSON.stringify(id)}`,
27641 `const css = ${JSON.stringify(css)}`,
27642 `updateStyle(id, css)`,
27643 // css modules exports change on edit so it can't self accept
27644 `${modulesCode || `import.meta.hot.accept()\nexport default css`}`,
27645 `import.meta.hot.prune(() => removeStyle(id))`
27646 ].join('\n');
27647 }
27648 }
27649 // build CSS handling ----------------------------------------------------
27650 // record css
27651 styles.set(id, css);
27652 return {
27653 code: modulesCode || `export default ${JSON.stringify(css)}`,
27654 map: { mappings: '' },
27655 // avoid the css module from being tree-shaken so that we can retrieve
27656 // it in renderChunk()
27657 moduleSideEffects: 'no-treeshake'
27658 };
27659 },
27660 async renderChunk(code, chunk, opts) {
27661 let chunkCSS = '';
27662 let isPureCssChunk = true;
27663 const ids = Object.keys(chunk.modules);
27664 for (const id of ids) {
27665 if (!isCSSRequest(id) ||
27666 cssModuleRE.test(id) ||
27667 commonjsProxyRE.test(id)) {
27668 isPureCssChunk = false;
27669 }
27670 if (styles.has(id)) {
27671 chunkCSS += styles.get(id);
27672 }
27673 }
27674 if (!chunkCSS) {
27675 return null;
27676 }
27677 // resolve asset URL placeholders to their built file URLs and perform
27678 // minification if necessary
27679 const processChunkCSS = async (css, { inlined, minify }) => {
27680 // replace asset url references with resolved url.
27681 const isRelativeBase = config.base === '' || config.base.startsWith('.');
27682 css = css.replace(assetUrlRE, (_, fileHash, postfix = '') => {
27683 const filename = getAssetFilename(fileHash, config) + postfix;
27684 registerAssetToChunk(chunk, filename);
27685 if (!isRelativeBase || inlined) {
27686 // absolute base or relative base but inlined (injected as style tag into
27687 // index.html) use the base as-is
27688 return config.base + filename;
27689 }
27690 else {
27691 // relative base + extracted CSS - asset file will be in the same dir
27692 return `./${path__default.posix.basename(filename)}`;
27693 }
27694 });
27695 // only external @imports should exist at this point - and they need to
27696 // be hoisted to the top of the CSS chunk per spec (#1845)
27697 if (css.includes('@import')) {
27698 css = await hoistAtImports(css);
27699 }
27700 if (minify && config.build.minify) {
27701 css = await minifyCSS(css, config);
27702 }
27703 return css;
27704 };
27705 if (config.build.cssCodeSplit) {
27706 if (isPureCssChunk) {
27707 // this is a shared CSS-only chunk that is empty.
27708 pureCssChunks.add(chunk.fileName);
27709 }
27710 if (opts.format === 'es' || opts.format === 'cjs') {
27711 chunkCSS = await processChunkCSS(chunkCSS, {
27712 inlined: false,
27713 minify: true
27714 });
27715 // emit corresponding css file
27716 const fileHandle = this.emitFile({
27717 name: chunk.name + '.css',
27718 type: 'asset',
27719 source: chunkCSS
27720 });
27721 chunkToEmittedCssFileMap.set(chunk, new Set([this.getFileName(fileHandle)]));
27722 }
27723 else if (!config.build.ssr) {
27724 // legacy build, inline css
27725 chunkCSS = await processChunkCSS(chunkCSS, {
27726 inlined: true,
27727 minify: true
27728 });
27729 const style = `__vite_style__`;
27730 const injectCode = `var ${style} = document.createElement('style');` +
27731 `${style}.innerHTML = ${JSON.stringify(chunkCSS)};` +
27732 `document.head.appendChild(${style});`;
27733 if (config.build.sourcemap) {
27734 const s = new MagicString(code);
27735 s.prepend(injectCode);
27736 return {
27737 code: s.toString(),
27738 map: s.generateMap({ hires: true })
27739 };
27740 }
27741 else {
27742 return { code: injectCode + code };
27743 }
27744 }
27745 }
27746 else {
27747 // non-split extracted CSS will be minified together
27748 chunkCSS = await processChunkCSS(chunkCSS, {
27749 inlined: false,
27750 minify: false
27751 });
27752 outputToExtractedCSSMap.set(opts, (outputToExtractedCSSMap.get(opts) || '') + chunkCSS);
27753 }
27754 return null;
27755 },
27756 async generateBundle(opts, bundle) {
27757 // remove empty css chunks and their imports
27758 if (pureCssChunks.size) {
27759 const emptyChunkFiles = [...pureCssChunks]
27760 .map((file) => path__default.basename(file))
27761 .join('|')
27762 .replace(/\./g, '\\.');
27763 const emptyChunkRE = new RegExp(opts.format === 'es'
27764 ? `\\bimport\\s*"[^"]*(?:${emptyChunkFiles})";\n?`
27765 : `\\brequire\\(\\s*"[^"]*(?:${emptyChunkFiles})"\\);\n?`, 'g');
27766 for (const file in bundle) {
27767 const chunk = bundle[file];
27768 if (chunk.type === 'chunk') {
27769 // remove pure css chunk from other chunk's imports,
27770 // and also register the emitted CSS files under the importer
27771 // chunks instead.
27772 chunk.imports = chunk.imports.filter((file) => {
27773 if (pureCssChunks.has(file)) {
27774 const css = chunkToEmittedCssFileMap.get(bundle[file]);
27775 if (css) {
27776 let existing = chunkToEmittedCssFileMap.get(chunk);
27777 if (!existing) {
27778 existing = new Set();
27779 }
27780 css.forEach((file) => existing.add(file));
27781 chunkToEmittedCssFileMap.set(chunk, existing);
27782 }
27783 return false;
27784 }
27785 return true;
27786 });
27787 chunk.code = chunk.code.replace(emptyChunkRE,
27788 // remove css import while preserving source map location
27789 (m) => `/* empty css ${''.padEnd(m.length - 15)}*/`);
27790 }
27791 }
27792 pureCssChunks.forEach((fileName) => {
27793 delete bundle[fileName];
27794 });
27795 }
27796 let extractedCss = outputToExtractedCSSMap.get(opts);
27797 if (extractedCss && !hasEmitted) {
27798 hasEmitted = true;
27799 // minify css
27800 if (config.build.minify) {
27801 extractedCss = await minifyCSS(extractedCss, config);
27802 }
27803 this.emitFile({
27804 name: 'style.css',
27805 type: 'asset',
27806 source: extractedCss
27807 });
27808 }
27809 }
27810 };
27811}
27812function createCSSResolvers(config) {
27813 let cssResolve;
27814 let sassResolve;
27815 let lessResolve;
27816 return {
27817 get css() {
27818 return (cssResolve ||
27819 (cssResolve = config.createResolver({
27820 extensions: ['.css'],
27821 mainFields: ['style'],
27822 tryIndex: false,
27823 preferRelative: true
27824 })));
27825 },
27826 get sass() {
27827 return (sassResolve ||
27828 (sassResolve = config.createResolver({
27829 extensions: ['.scss', '.sass', '.css'],
27830 mainFields: ['sass', 'style'],
27831 tryIndex: true,
27832 tryPrefix: '_',
27833 preferRelative: true
27834 })));
27835 },
27836 get less() {
27837 return (lessResolve ||
27838 (lessResolve = config.createResolver({
27839 extensions: ['.less', '.css'],
27840 mainFields: ['less', 'style'],
27841 tryIndex: false,
27842 preferRelative: true
27843 })));
27844 }
27845 };
27846}
27847async function compileCSS(id, code, config, urlReplacer, atImportResolvers, server) {
27848 var _a;
27849 const { modules: modulesOptions, preprocessorOptions } = config.css || {};
27850 const isModule = modulesOptions !== false && cssModuleRE.test(id);
27851 // although at serve time it can work without processing, we do need to
27852 // crawl them in order to register watch dependencies.
27853 const needInlineImport = code.includes('@import');
27854 const hasUrl = cssUrlRE.test(code) || cssImageSetRE.test(code);
27855 const postcssConfig = await resolvePostcssConfig(config);
27856 const lang = (_a = id.match(cssLangRE)) === null || _a === void 0 ? void 0 : _a[1];
27857 // 1. plain css that needs no processing
27858 if (lang === 'css' &&
27859 !postcssConfig &&
27860 !isModule &&
27861 !needInlineImport &&
27862 !hasUrl) {
27863 return { code };
27864 }
27865 let map;
27866 let modules;
27867 const deps = new Set();
27868 // 2. pre-processors: sass etc.
27869 if (isPreProcessor(lang)) {
27870 const preProcessor = preProcessors[lang];
27871 let opts = (preprocessorOptions && preprocessorOptions[lang]) || {};
27872 // support @import from node dependencies by default
27873 switch (lang) {
27874 case "scss" /* scss */:
27875 case "sass" /* sass */:
27876 opts = {
27877 includePaths: ['node_modules'],
27878 alias: config.resolve.alias,
27879 ...opts
27880 };
27881 break;
27882 case "less" /* less */:
27883 case "styl" /* styl */:
27884 case "stylus" /* stylus */:
27885 opts = {
27886 paths: ['node_modules'],
27887 alias: config.resolve.alias,
27888 ...opts
27889 };
27890 }
27891 // important: set this for relative import resolving
27892 opts.filename = cleanUrl(id);
27893 const preprocessResult = await preProcessor(code, config.root, opts, atImportResolvers);
27894 if (preprocessResult.errors.length) {
27895 throw preprocessResult.errors[0];
27896 }
27897 code = preprocessResult.code;
27898 map = preprocessResult.map;
27899 if (preprocessResult.deps) {
27900 preprocessResult.deps.forEach((dep) => {
27901 // sometimes sass registers the file itself as a dep
27902 if (normalizePath$4(dep) !== normalizePath$4(opts.filename)) {
27903 deps.add(dep);
27904 }
27905 });
27906 }
27907 }
27908 // 3. postcss
27909 const postcssOptions = (postcssConfig && postcssConfig.options) || {};
27910 const postcssPlugins = postcssConfig && postcssConfig.plugins ? postcssConfig.plugins.slice() : [];
27911 if (needInlineImport) {
27912 postcssPlugins.unshift((await Promise.resolve().then(function () { return require('./dep-0a2c02a1.js'); }).then(function (n) { return n.index; })).default({
27913 async resolve(id, basedir) {
27914 const resolved = await atImportResolvers.css(id, path__default.join(basedir, '*'));
27915 if (resolved) {
27916 return path__default.resolve(resolved);
27917 }
27918 return id;
27919 }
27920 }));
27921 }
27922 postcssPlugins.push(UrlRewritePostcssPlugin({
27923 replacer: urlReplacer
27924 }));
27925 if (isModule) {
27926 postcssPlugins.unshift((await Promise.resolve().then(function () { return require('./dep-b2288281.js'); }).then(function (n) { return n.index; })).default({
27927 ...modulesOptions,
27928 getJSON(cssFileName, _modules, outputFileName) {
27929 modules = _modules;
27930 if (modulesOptions && typeof modulesOptions.getJSON === 'function') {
27931 modulesOptions.getJSON(cssFileName, _modules, outputFileName);
27932 }
27933 }
27934 }));
27935 }
27936 if (!postcssPlugins.length) {
27937 return {
27938 code,
27939 map
27940 };
27941 }
27942 // postcss is an unbundled dep and should be lazy imported
27943 const postcssResult = await (await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('postcss')); }))
27944 .default(postcssPlugins)
27945 .process(code, {
27946 ...postcssOptions,
27947 to: id,
27948 from: id,
27949 map: {
27950 inline: false,
27951 annotation: false,
27952 prev: map
27953 }
27954 });
27955 // record CSS dependencies from @imports
27956 for (const message of postcssResult.messages) {
27957 if (message.type === 'dependency') {
27958 deps.add(message.file);
27959 }
27960 else if (message.type === 'dir-dependency') {
27961 // https://github.com/postcss/postcss/blob/main/docs/guidelines/plugin.md#3-dependencies
27962 const { dir, glob: globPattern = '**' } = message;
27963 const pattern = normalizePath$4(path__default.resolve(path__default.dirname(id), dir)) + `/` + globPattern;
27964 const files = out$1.sync(pattern, {
27965 ignore: ['**/node_modules/**']
27966 });
27967 for (let i = 0; i < files.length; i++) {
27968 deps.add(files[i]);
27969 }
27970 if (server) {
27971 // register glob importers so we can trigger updates on file add/remove
27972 if (!(id in server._globImporters)) {
27973 server._globImporters[id] = {
27974 module: server.moduleGraph.getModuleById(id),
27975 importGlobs: []
27976 };
27977 }
27978 server._globImporters[id].importGlobs.push({
27979 base: config.root,
27980 pattern
27981 });
27982 }
27983 }
27984 else if (message.type === 'warning') {
27985 let msg = `[vite:css] ${message.text}`;
27986 if (message.line && message.column) {
27987 msg += `\n${generateCodeFrame(code, {
27988 line: message.line,
27989 column: message.column
27990 })}`;
27991 }
27992 config.logger.warn(source.yellow(msg));
27993 }
27994 }
27995 return {
27996 ast: postcssResult,
27997 code: postcssResult.css,
27998 map: postcssResult.map,
27999 modules,
28000 deps
28001 };
28002}
28003let cachedPostcssConfig;
28004async function resolvePostcssConfig(config) {
28005 var _a;
28006 if (cachedPostcssConfig !== undefined) {
28007 return cachedPostcssConfig;
28008 }
28009 // inline postcss config via vite config
28010 const inlineOptions = (_a = config.css) === null || _a === void 0 ? void 0 : _a.postcss;
28011 if (isObject$3(inlineOptions)) {
28012 const result = {
28013 options: { ...inlineOptions },
28014 plugins: inlineOptions.plugins || []
28015 };
28016 delete result.options.plugins;
28017 return (cachedPostcssConfig = result);
28018 }
28019 try {
28020 const searchPath = typeof inlineOptions === 'string' ? inlineOptions : config.root;
28021 // @ts-ignore
28022 return (cachedPostcssConfig = await src$3({}, searchPath));
28023 }
28024 catch (e) {
28025 if (!/No PostCSS Config found/.test(e.message)) {
28026 throw e;
28027 }
28028 return (cachedPostcssConfig = null);
28029 }
28030}
28031// https://drafts.csswg.org/css-syntax-3/#identifier-code-point
28032const cssUrlRE = /(?<=^|[^\w\-\u0080-\uffff])url\(\s*('[^']+'|"[^"]+"|[^'")]+)\s*\)/;
28033const cssImageSetRE = /image-set\(([^)]+)\)/;
28034const UrlRewritePostcssPlugin = (opts) => {
28035 if (!opts) {
28036 throw new Error('base or replace is required');
28037 }
28038 return {
28039 postcssPlugin: 'vite-url-rewrite',
28040 Once(root) {
28041 const promises = [];
28042 root.walkDecls((declaration) => {
28043 const isCssUrl = cssUrlRE.test(declaration.value);
28044 const isCssImageSet = cssImageSetRE.test(declaration.value);
28045 if (isCssUrl || isCssImageSet) {
28046 const replacerForDeclaration = (rawUrl) => {
28047 var _a;
28048 const importer = (_a = declaration.source) === null || _a === void 0 ? void 0 : _a.input.file;
28049 return opts.replacer(rawUrl, importer);
28050 };
28051 const rewriterToUse = isCssUrl ? rewriteCssUrls : rewriteCssImageSet;
28052 promises.push(rewriterToUse(declaration.value, replacerForDeclaration).then((url) => {
28053 declaration.value = url;
28054 }));
28055 }
28056 });
28057 if (promises.length) {
28058 return Promise.all(promises);
28059 }
28060 }
28061 };
28062};
28063UrlRewritePostcssPlugin.postcss = true;
28064function rewriteCssUrls(css, replacer) {
28065 return asyncReplace(css, cssUrlRE, async (match) => {
28066 const [matched, rawUrl] = match;
28067 return await doUrlReplace(rawUrl, matched, replacer);
28068 });
28069}
28070function rewriteCssImageSet(css, replacer) {
28071 return asyncReplace(css, cssImageSetRE, async (match) => {
28072 const [matched, rawUrl] = match;
28073 const url = await processSrcSet(rawUrl, ({ url }) => doUrlReplace(url, matched, replacer));
28074 return `image-set(${url})`;
28075 });
28076}
28077async function doUrlReplace(rawUrl, matched, replacer) {
28078 let wrap = '';
28079 const first = rawUrl[0];
28080 if (first === `"` || first === `'`) {
28081 wrap = first;
28082 rawUrl = rawUrl.slice(1, -1);
28083 }
28084 if (isExternalUrl(rawUrl) || isDataUrl(rawUrl) || rawUrl.startsWith('#')) {
28085 return matched;
28086 }
28087 return `url(${wrap}${await replacer(rawUrl)}${wrap})`;
28088}
28089let CleanCSS;
28090async function minifyCSS(css, config) {
28091 CleanCSS = CleanCSS || (await Promise.resolve().then(function () { return require('./dep-cb9bf5e2.js'); }).then(function (n) { return n.index; })).default;
28092 const res = new CleanCSS({
28093 rebase: false,
28094 ...config.build.cleanCssOptions
28095 }).minify(css);
28096 if (res.errors && res.errors.length) {
28097 config.logger.error(source.red(`error when minifying css:\n${res.errors}`));
28098 throw res.errors[0];
28099 }
28100 // do not warn on remote @imports
28101 const warnings = res.warnings &&
28102 res.warnings.filter((m) => !m.includes('remote @import'));
28103 if (warnings && warnings.length) {
28104 config.logger.warn(source.yellow(`warnings when minifying css:\n${warnings.join('\n')}`));
28105 }
28106 return res.styles;
28107}
28108// #1845
28109// CSS @import can only appear at top of the file. We need to hoist all @import
28110// to top when multiple files are concatenated.
28111async function hoistAtImports(css) {
28112 const postcss = await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('postcss')); });
28113 return (await postcss.default([AtImportHoistPlugin]).process(css)).css;
28114}
28115const AtImportHoistPlugin = () => {
28116 return {
28117 postcssPlugin: 'vite-hoist-at-imports',
28118 Once(root) {
28119 const imports = [];
28120 root.walkAtRules((rule) => {
28121 if (rule.name === 'import') {
28122 // record in reverse so that can simply prepend to preserve order
28123 imports.unshift(rule);
28124 }
28125 });
28126 imports.forEach((i) => root.prepend(i));
28127 }
28128 };
28129};
28130AtImportHoistPlugin.postcss = true;
28131const loadedPreprocessors = {};
28132function loadPreprocessor(lang, root) {
28133 if (lang in loadedPreprocessors) {
28134 return loadedPreprocessors[lang];
28135 }
28136 try {
28137 // Search for the preprocessor in the root directory first, and fall back
28138 // to the default require paths.
28139 const fallbackPaths = require.resolve.paths(lang) || [];
28140 const resolved = require.resolve(lang, { paths: [root, ...fallbackPaths] });
28141 return (loadedPreprocessors[lang] = require(resolved));
28142 }
28143 catch (e) {
28144 throw new Error(`Preprocessor dependency "${lang}" not found. Did you install it?`);
28145 }
28146}
28147// .scss/.sass processor
28148const scss = async (source, root, options, resolvers) => {
28149 const render = loadPreprocessor("sass" /* sass */, root).render;
28150 const internalImporter = (url, importer, done) => {
28151 resolvers.sass(url, importer).then((resolved) => {
28152 if (resolved) {
28153 rebaseUrls(resolved, options.filename, options.alias).then(done);
28154 }
28155 else {
28156 done(null);
28157 }
28158 });
28159 };
28160 const importer = [internalImporter];
28161 if (options.importer) {
28162 Array.isArray(options.importer)
28163 ? importer.push(...options.importer)
28164 : importer.push(options.importer);
28165 }
28166 const finalOptions = {
28167 ...options,
28168 data: await getSource(source, options.filename, options.additionalData),
28169 file: options.filename,
28170 outFile: options.filename,
28171 importer
28172 };
28173 try {
28174 const result = await new Promise((resolve, reject) => {
28175 render(finalOptions, (err, res) => {
28176 if (err) {
28177 reject(err);
28178 }
28179 else {
28180 resolve(res);
28181 }
28182 });
28183 });
28184 const deps = result.stats.includedFiles;
28185 return {
28186 code: result.css.toString(),
28187 errors: [],
28188 deps
28189 };
28190 }
28191 catch (e) {
28192 // normalize SASS error
28193 e.id = e.file;
28194 e.frame = e.formatted;
28195 return { code: '', errors: [e], deps: [] };
28196 }
28197};
28198const sass = (source, root, options, aliasResolver) => scss(source, root, {
28199 ...options,
28200 indentedSyntax: true
28201}, aliasResolver);
28202/**
28203 * relative url() inside \@imported sass and less files must be rebased to use
28204 * root file as base.
28205 */
28206async function rebaseUrls(file, rootFile, alias) {
28207 file = path__default.resolve(file); // ensure os-specific flashes
28208 // in the same dir, no need to rebase
28209 const fileDir = path__default.dirname(file);
28210 const rootDir = path__default.dirname(rootFile);
28211 if (fileDir === rootDir) {
28212 return { file };
28213 }
28214 // no url()
28215 const content = fs__default.readFileSync(file, 'utf-8');
28216 if (!cssUrlRE.test(content)) {
28217 return { file };
28218 }
28219 const rebased = await rewriteCssUrls(content, (url) => {
28220 if (url.startsWith('/'))
28221 return url;
28222 // match alias, no need to rewrite
28223 for (const { find } of alias) {
28224 const matches = typeof find === 'string' ? url.startsWith(find) : find.test(url);
28225 if (matches) {
28226 return url;
28227 }
28228 }
28229 const absolute = path__default.resolve(fileDir, url);
28230 const relative = path__default.relative(rootDir, absolute);
28231 return normalizePath$4(relative);
28232 });
28233 return {
28234 file,
28235 contents: rebased
28236 };
28237}
28238// .less
28239const less = async (source, root, options, resolvers) => {
28240 const nodeLess = loadPreprocessor("less" /* less */, root);
28241 const viteResolverPlugin = createViteLessPlugin(nodeLess, options.filename, options.alias, resolvers);
28242 source = await getSource(source, options.filename, options.additionalData);
28243 let result;
28244 try {
28245 result = await nodeLess.render(source, {
28246 ...options,
28247 plugins: [viteResolverPlugin, ...(options.plugins || [])]
28248 });
28249 }
28250 catch (e) {
28251 const error = e;
28252 // normalize error info
28253 const normalizedError = new Error(error.message || error.type);
28254 normalizedError.loc = {
28255 file: error.filename || options.filename,
28256 line: error.line,
28257 column: error.column
28258 };
28259 return { code: '', errors: [normalizedError], deps: [] };
28260 }
28261 return {
28262 code: result.css.toString(),
28263 deps: result.imports,
28264 errors: []
28265 };
28266};
28267/**
28268 * Less manager, lazy initialized
28269 */
28270let ViteLessManager;
28271function createViteLessPlugin(less, rootFile, alias, resolvers) {
28272 if (!ViteLessManager) {
28273 ViteLessManager = class ViteManager extends less.FileManager {
28274 constructor(rootFile, resolvers, alias) {
28275 super();
28276 this.rootFile = rootFile;
28277 this.resolvers = resolvers;
28278 this.alias = alias;
28279 }
28280 supports() {
28281 return true;
28282 }
28283 supportsSync() {
28284 return false;
28285 }
28286 async loadFile(filename, dir, opts, env) {
28287 const resolved = await this.resolvers.less(filename, path__default.join(dir, '*'));
28288 if (resolved) {
28289 const result = await rebaseUrls(resolved, this.rootFile, this.alias);
28290 let contents;
28291 if (result && 'contents' in result) {
28292 contents = result.contents;
28293 }
28294 else {
28295 contents = fs__default.readFileSync(resolved, 'utf-8');
28296 }
28297 return {
28298 filename: path__default.resolve(resolved),
28299 contents
28300 };
28301 }
28302 else {
28303 return super.loadFile(filename, dir, opts, env);
28304 }
28305 }
28306 };
28307 }
28308 return {
28309 install(_, pluginManager) {
28310 pluginManager.addFileManager(new ViteLessManager(rootFile, resolvers, alias));
28311 },
28312 minVersion: [3, 0, 0]
28313 };
28314}
28315// .styl
28316const styl = async (source, root, options) => {
28317 var _a;
28318 const nodeStylus = loadPreprocessor("stylus" /* stylus */, root);
28319 // Get source with preprocessor options.additionalData. Make sure a new line separator
28320 // is added to avoid any render error, as added stylus content may not have semi-colon separators
28321 source = await getSource(source, options.filename, options.additionalData, '\n');
28322 // Get preprocessor options.imports dependencies as stylus
28323 // does not return them with its builtin `.deps()` method
28324 const importsDeps = ((_a = options.imports) !== null && _a !== void 0 ? _a : []).map((dep) => path__default.resolve(dep));
28325 try {
28326 const ref = nodeStylus(source, options);
28327 // if (map) ref.set('sourcemap', { inline: false, comment: false })
28328 const result = ref.render();
28329 // Concat imports deps with computed deps
28330 const deps = [...ref.deps(), ...importsDeps];
28331 return { code: result, errors: [], deps };
28332 }
28333 catch (e) {
28334 return { code: '', errors: [e], deps: [] };
28335 }
28336};
28337function getSource(source, filename, additionalData, sep = '') {
28338 if (!additionalData)
28339 return source;
28340 if (typeof additionalData === 'function') {
28341 return additionalData(source, filename);
28342 }
28343 return additionalData + sep + source;
28344}
28345const preProcessors = Object.freeze({
28346 ["less" /* less */]: less,
28347 ["sass" /* sass */]: sass,
28348 ["scss" /* scss */]: scss,
28349 ["styl" /* styl */]: styl,
28350 ["stylus" /* stylus */]: styl
28351});
28352function isPreProcessor(lang) {
28353 return lang && lang in preProcessors;
28354}
28355
28356/* es-module-lexer 0.6.0 */
28357const A=1===new Uint8Array(new Uint16Array([1]).buffer)[0];function parse$e(E,g="@"){if(!B)return init.then(()=>parse$e(E));const I=E.length+1,w=(B.__heap_base.value||B.__heap_base)+4*I-B.memory.buffer.byteLength;w>0&&B.memory.grow(Math.ceil(w/65536));const D=B.sa(I-1);if((A?C:Q)(E,new Uint16Array(B.memory.buffer,D,I)),!B.parse())throw Object.assign(new Error(`Parse error ${g}:${E.slice(0,B.e()).split("\n").length}:${B.e()-E.lastIndexOf("\n",B.e()-1)}`),{idx:B.e()});const L=[],N=[];for(;B.ri();){const A=B.is(),Q=B.ie(),C=B.ai(),g=B.id(),I=B.ss(),w=B.se();let D;B.ip()&&(D=J(E.slice(-1===g?A-1:A,-1===g?Q+1:Q))),L.push({n:D,s:A,e:Q,ss:I,se:w,d:g,a:C});}for(;B.re();)N.push(E.slice(B.es(),B.ee()));function J(A){try{return (0, eval)(A)}catch{}}return [L,N,!!B.f()]}function Q(A,Q){const C=A.length;let B=0;for(;B<C;){const C=A.charCodeAt(B);Q[B++]=(255&C)<<8|C>>>8;}}function C(A,Q){const C=A.length;let B=0;for(;B<C;)Q[B]=A.charCodeAt(B++);}let B;const init=WebAssembly.compile((E="AGFzbQEAAAABXA1gAX8Bf2AEf39/fwBgAn9/AGAAAX9gAABgAX8AYAZ/f39/f38Bf2AEf39/fwF/YAN/f38Bf2AHf39/f39/fwF/YAV/f39/fwF/YAJ/fwF/YAh/f39/f39/fwF/AzIxAAECAwMDAwMDAwMDAwMDAwAEBQAGBAQAAAAABAQEBAQABgcICQoLDAACAAAACwMJDAQFAXABAQEFAwEAAQYPAn8BQfDwAAt/AEHw8AALB2QRBm1lbW9yeQIAAnNhAAABZQADAmlzAAQCaWUABQJzcwAGAnNlAAcCYWkACAJpZAAJAmlwAAoCZXMACwJlZQAMAnJpAA0CcmUADgFmAA8FcGFyc2UAEAtfX2hlYXBfYmFzZQMBCqM6MWgBAX9BACAANgK0CEEAKAKQCCIBIABBAXRqIgBBADsBAEEAIABBAmoiADYCuAhBACAANgK8CEEAQQA2ApQIQQBBADYCpAhBAEEANgKcCEEAQQA2ApgIQQBBADYCrAhBAEEANgKgCCABC7IBAQJ/QQAoAqQIIgRBHGpBlAggBBtBACgCvAgiBTYCAEEAIAU2AqQIQQAgBDYCqAhBACAFQSBqNgK8CCAFIAA2AggCQAJAQQAoAogIIANHDQAgBSACNgIMDAELAkBBACgChAggA0cNACAFIAJBAmo2AgwMAQsgBUEAKAKQCDYCDAsgBSABNgIAIAUgAzYCFCAFQQA2AhAgBSACNgIEIAVBADYCHCAFQQAoAoQIIANGOgAYC0gBAX9BACgCrAgiAkEIakGYCCACG0EAKAK8CCICNgIAQQAgAjYCrAhBACACQQxqNgK8CCACQQA2AgggAiABNgIEIAIgADYCAAsIAEEAKALACAsVAEEAKAKcCCgCAEEAKAKQCGtBAXULFQBBACgCnAgoAgRBACgCkAhrQQF1CxUAQQAoApwIKAIIQQAoApAIa0EBdQsVAEEAKAKcCCgCDEEAKAKQCGtBAXULHgEBf0EAKAKcCCgCECIAQQAoApAIa0EBdUF/IAAbCzsBAX8CQEEAKAKcCCgCFCIAQQAoAoQIRw0AQX8PCwJAIABBACgCiAhHDQBBfg8LIABBACgCkAhrQQF1CwsAQQAoApwILQAYCxUAQQAoAqAIKAIAQQAoApAIa0EBdQsVAEEAKAKgCCgCBEEAKAKQCGtBAXULJQEBf0EAQQAoApwIIgBBHGpBlAggABsoAgAiADYCnAggAEEARwslAQF/QQBBACgCoAgiAEEIakGYCCAAGygCACIANgKgCCAAQQBHCwgAQQAtAMQIC5oMAQV/IwBBgPAAayIBJABBAEEBOgDECEEAQf//AzsByghBAEEAKAKMCDYCzAhBAEEAKAKQCEF+aiICNgLgCEEAIAJBACgCtAhBAXRqIgM2AuQIQQBBADsBxghBAEEAOwHICEEAQQA6ANAIQQBBADYCwAhBAEEAOgCwCEEAIAFBgNAAajYC1AhBACABQYAQajYC2AhBAEEAOgDcCAJAAkACQANAQQAgAkECaiIENgLgCAJAAkACQAJAIAIgA08NACAELwEAIgNBd2pBBUkNAyADQZt/aiIFQQRNDQEgA0EgRg0DAkAgA0EvRg0AIANBO0YNAwwGCwJAIAIvAQQiBEEqRg0AIARBL0cNBhARDAQLQQEQEgwDC0EAIQMgBCECQQAtALAIDQYMBQsCQAJAIAUOBQEFBQUAAQsgBBATRQ0BIAJBBGpB7QBB8ABB7wBB8gBB9AAQFEUNARAVDAELQQAvAcgIDQAgBBATRQ0AIAJBBGpB+ABB8ABB7wBB8gBB9AAQFEUNABAWQQAtAMQIDQBBAEEAKALgCCICNgLMCAwEC0EAQQAoAuAINgLMCAtBACgC5AghA0EAKALgCCECDAALC0EAIAI2AuAIQQBBADoAxAgLA0BBACACQQJqIgM2AuAIAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAJBACgC5AhPDQAgAy8BACIEQXdqQQVJDQ4gBEFgaiIFQQlNDQEgBEGgf2oiBUEJTQ0CAkACQAJAIARBhX9qIgNBAk0NACAEQS9HDRAgAi8BBCICQSpGDQEgAkEvRw0CEBEMEQsCQAJAIAMOAwARAQALAkBBACgCzAgiBC8BAEEpRw0AQQAoAqQIIgJFDQAgAigCBCAERw0AQQBBACgCqAgiAjYCpAgCQCACRQ0AIAJBADYCHAwBC0EAQQA2ApQICyABQQAvAcgIIgJqQQAtANwIOgAAQQAgAkEBajsByAhBACgC2AggAkECdGogBDYCAEEAQQA6ANwIDBALQQAvAcgIIgJFDQlBACACQX9qIgM7AcgIAkAgAkEALwHKCCIERw0AQQBBAC8BxghBf2oiAjsBxghBAEEAKALUCCACQf//A3FBAXRqLwEAOwHKCAwICyAEQf//A0YNDyADQf//A3EgBEkNCQwPC0EBEBIMDwsCQAJAAkACQEEAKALMCCIELwEAIgIQF0UNACACQVVqIgNBA0sNAgJAAkACQCADDgQBBQIAAQsgBEF+ai8BAEFQakH//wNxQQpJDQMMBAsgBEF+ai8BAEErRg0CDAMLIARBfmovAQBBLUYNAQwCCwJAIAJB/QBGDQAgAkEpRw0BQQAoAtgIQQAvAcgIQQJ0aigCABAYRQ0BDAILQQAoAtgIQQAvAcgIIgNBAnRqKAIAEBkNASABIANqLQAADQELIAQQGg0AIAJFDQBBASEEIAJBL0ZBAC0A0AhBAEdxRQ0BCxAbQQAhBAtBACAEOgDQCAwNC0EALwHKCEH//wNGQQAvAcgIRXFBAC0AsAhFcSEDDA8LIAUOCgwLAQsLCwsCBwQMCyAFDgoCCgoHCgkKCgoIAgsQHAwJCxAdDAgLEB4MBwtBAC8ByAgiAg0BCxAfQQAhAwwIC0EAIAJBf2oiBDsByAhBACgCpAgiAkUNBCACKAIUQQAoAtgIIARB//8DcUECdGooAgBHDQQCQCACKAIEDQAgAiADNgIECyACIAM2AgwMBAtBAEEALwHICCICQQFqOwHICEEAKALYCCACQQJ0akEAKALMCDYCAAwDCyADEBNFDQIgAi8BCkHzAEcNAiACLwEIQfMARw0CIAIvAQZB4QBHDQIgAi8BBEHsAEcNAgJAAkAgAi8BDCIEQXdqIgJBF0sNAEEBIAJ0QZ+AgARxDQELIARBoAFHDQMLQQBBAToA3AgMAgsgAxATRQ0BIAJBBGpB7QBB8ABB7wBB8gBB9AAQFEUNARAVDAELQQAvAcgIDQAgAxATRQ0AIAJBBGpB+ABB8ABB7wBB8gBB9AAQFEUNABAWC0EAQQAoAuAINgLMCAtBACgC4AghAgwACwsgAUGA8ABqJAAgAwtQAQR/QQAoAuAIQQJqIQBBACgC5AghAQJAA0AgACICQX5qIAFPDQEgAkECaiEAIAIvAQBBdmoiA0EDSw0AIAMOBAEAAAEBCwtBACACNgLgCAuhAQEDf0EAQQAoAuAIIgFBAmo2AuAIIAFBBmohAUEAKALkCCECA0ACQAJAAkAgAUF8aiACTw0AIAFBfmovAQAhAwJAAkAgAA0AIANBKkYNASADQXZqIgNBA0sNBCADDgQCBAQCAgsgA0EqRw0DCyABLwEAQS9HDQJBACABQX5qNgLgCAwBCyABQX5qIQELQQAgATYC4AgPCyABQQJqIQEMAAsLHQACQEEAKAKQCCAARw0AQQEPCyAAQX5qLwEAECALPwEBf0EAIQYCQCAALwEIIAVHDQAgAC8BBiAERw0AIAAvAQQgA0cNACAALwECIAJHDQAgAC8BACABRiEGCyAGC+MEAQR/QQBBACgC4AgiAEEMaiIBNgLgCAJAAkACQAJAAkBBARAoIgJBWWoiA0EHTQ0AIAJBIkYNAiACQfsARg0CDAELAkACQCADDggDAQIDAgICAAMLQQBBACgC4AhBAmo2AuAIQQEQKEHtAEcNA0EAKALgCCIDLwEGQeEARw0DIAMvAQRB9ABHDQMgAy8BAkHlAEcNA0EAKALMCC8BAEEuRg0DIAAgACADQQhqQQAoAogIEAEPC0EAKALYCEEALwHICCIDQQJ0aiAANgIAQQAgA0EBajsByAhBACgCzAgvAQBBLkYNAiAAQQAoAuAIQQJqQQAgABABQQBBACgC4AhBAmo2AuAIAkACQEEBECgiA0EiRg0AAkAgA0EnRw0AEB0MAgtBAEEAKALgCEF+ajYC4AgPCxAcC0EAQQAoAuAIQQJqNgLgCAJAQQEQKEFXaiIDQQNLDQACQAJAIAMOBAECAgABC0EAKAKkCEEAKALgCCIDNgIEQQAgA0ECajYC4AhBARAoGkEAKAKkCCIDQQE6ABggA0EAKALgCCICNgIQQQAgAkF+ajYC4AgPC0EAKAKkCCIDQQE6ABggA0EAKALgCCICNgIMIAMgAjYCBEEAQQAvAcgIQX9qOwHICA8LQQBBACgC4AhBfmo2AuAIDwtBACgC4AggAUYNAQtBAC8ByAgNAUEAKALgCCEDQQAoAuQIIQECQANAIAMgAU8NAQJAAkAgAy8BACICQSdGDQAgAkEiRw0BCyAAIAIQKQ8LQQAgA0ECaiIDNgLgCAwACwsQHwsPC0EAQQAoAuAIQX5qNgLgCAuyBgEEf0EAQQAoAuAIIgBBDGoiATYC4AhBARAoIQICQAJAAkACQAJAAkBBACgC4AgiAyABRw0AIAIQLEUNAQsCQAJAAkACQCACQZ9/aiIBQQtNDQACQAJAIAJBKkYNACACQfYARg0FIAJB+wBHDQNBACADQQJqNgLgCEEBECghA0EAKALgCCEBA0AgA0H//wNxECsaQQAoAuAIIQJBARAoGgJAIAEgAhAtIgNBLEcNAEEAQQAoAuAIQQJqNgLgCEEBECghAwtBACgC4AghAgJAIANB/QBGDQAgAiABRg0MIAIhASACQQAoAuQITQ0BDAwLC0EAIAJBAmo2AuAIDAELQQAgA0ECajYC4AhBARAoGkEAKALgCCICIAIQLRoLQQEQKCECDAELIAEODAQAAQYABQAAAAAAAgQLQQAoAuAIIQMCQCACQeYARw0AIAMvAQZB7QBHDQAgAy8BBEHvAEcNACADLwECQfIARw0AQQAgA0EIajYC4AggAEEBECgQKQ8LQQAgA0F+ajYC4AgMAgsCQCADLwEIQfMARw0AIAMvAQZB8wBHDQAgAy8BBEHhAEcNACADLwECQewARw0AIAMvAQoQIEUNAEEAIANBCmo2AuAIQQEQKCECQQAoAuAIIQMgAhArGiADQQAoAuAIEAJBAEEAKALgCEF+ajYC4AgPC0EAIANBBGoiAzYC4AgLQQAgA0EEaiICNgLgCEEAQQA6AMQIA0BBACACQQJqNgLgCEEBECghA0EAKALgCCECAkAgAxArQSByQfsARw0AQQBBACgC4AhBfmo2AuAIDwtBACgC4AgiAyACRg0BIAIgAxACAkBBARAoIgJBLEYNAAJAIAJBPUcNAEEAQQAoAuAIQX5qNgLgCA8LQQBBACgC4AhBfmo2AuAIDwtBACgC4AghAgwACwsPC0EAIANBCmo2AuAIQQEQKBpBACgC4AghAwtBACADQRBqNgLgCAJAQQEQKCICQSpHDQBBAEEAKALgCEECajYC4AhBARAoIQILQQAoAuAIIQMgAhArGiADQQAoAuAIEAJBAEEAKALgCEF+ajYC4AgPCyADIANBDmoQAg8LEB8LdQEBfwJAAkAgAEFfaiIBQQVLDQBBASABdEExcQ0BCyAAQUZqQf//A3FBBkkNACAAQVhqQf//A3FBB0kgAEEpR3ENAAJAIABBpX9qIgFBA0sNACABDgQBAAABAQsgAEH9AEcgAEGFf2pB//8DcUEESXEPC0EBCz0BAX9BASEBAkAgAEH3AEHoAEHpAEHsAEHlABAhDQAgAEHmAEHvAEHyABAiDQAgAEHpAEHmABAjIQELIAELrQEBA39BASEBAkACQAJAAkACQAJAAkAgAC8BACICQUVqIgNBA00NACACQZt/aiIDQQNNDQEgAkEpRg0DIAJB+QBHDQIgAEF+akHmAEHpAEHuAEHhAEHsAEHsABAkDwsgAw4EAgEBBQILIAMOBAIAAAMCC0EAIQELIAEPCyAAQX5qQeUAQewAQfMAECIPCyAAQX5qQeMAQeEAQfQAQeMAECUPCyAAQX5qLwEAQT1GC+0DAQJ/QQAhAQJAIAAvAQBBnH9qIgJBE0sNAAJAAkACQAJAAkACQAJAAkAgAg4UAAECCAgICAgICAMECAgFCAYICAcACyAAQX5qLwEAQZd/aiICQQNLDQcCQAJAIAIOBAAJCQEACyAAQXxqQfYAQe8AECMPCyAAQXxqQfkAQekAQeUAECIPCyAAQX5qLwEAQY1/aiICQQFLDQYCQAJAIAIOAgABAAsCQCAAQXxqLwEAIgJB4QBGDQAgAkHsAEcNCCAAQXpqQeUAECYPCyAAQXpqQeMAECYPCyAAQXxqQeQAQeUAQewAQeUAECUPCyAAQX5qLwEAQe8ARw0FIABBfGovAQBB5QBHDQUCQCAAQXpqLwEAIgJB8ABGDQAgAkHjAEcNBiAAQXhqQekAQe4AQfMAQfQAQeEAQe4AECQPCyAAQXhqQfQAQfkAECMPC0EBIQEgAEF+aiIAQekAECYNBCAAQfIAQeUAQfQAQfUAQfIAECEPCyAAQX5qQeQAECYPCyAAQX5qQeQAQeUAQeIAQfUAQecAQecAQeUAECcPCyAAQX5qQeEAQfcAQeEAQekAECUPCwJAIABBfmovAQAiAkHvAEYNACACQeUARw0BIABBfGpB7gAQJg8LIABBfGpB9ABB6ABB8gAQIiEBCyABC4MBAQN/A0BBAEEAKALgCCIAQQJqIgE2AuAIAkACQAJAIABBACgC5AhPDQAgAS8BACIBQaV/aiICQQFNDQICQCABQXZqIgBBA00NACABQS9HDQQMAgsgAA4EAAMDAAALEB8LDwsCQAJAIAIOAgEAAQtBACAAQQRqNgLgCAwBCxAuGgwACwuRAQEEf0EAKALgCCEAQQAoAuQIIQECQANAIAAiAkECaiEAIAIgAU8NAQJAIAAvAQAiA0HcAEYNAAJAIANBdmoiAkEDTQ0AIANBIkcNAkEAIAA2AuAIDwsgAg4EAgEBAgILIAJBBGohACACLwEEQQ1HDQAgAkEGaiAAIAIvAQZBCkYbIQAMAAsLQQAgADYC4AgQHwuRAQEEf0EAKALgCCEAQQAoAuQIIQECQANAIAAiAkECaiEAIAIgAU8NAQJAIAAvAQAiA0HcAEYNAAJAIANBdmoiAkEDTQ0AIANBJ0cNAkEAIAA2AuAIDwsgAg4EAgEBAgILIAJBBGohACACLwEEQQ1HDQAgAkEGaiAAIAIvAQZBCkYbIQAMAAsLQQAgADYC4AgQHwvJAQEFf0EAKALgCCEAQQAoAuQIIQEDQCAAIgJBAmohAAJAAkAgAiABTw0AIAAvAQAiA0Gkf2oiBEEETQ0BIANBJEcNAiACLwEEQfsARw0CQQBBAC8BxggiAEEBajsBxghBACgC1AggAEEBdGpBAC8Bygg7AQBBACACQQRqNgLgCEEAQQAvAcgIQQFqIgA7AcoIQQAgADsByAgPC0EAIAA2AuAIEB8PCwJAAkAgBA4FAQICAgABC0EAIAA2AuAIDwsgAkEEaiEADAALCzUBAX9BAEEBOgCwCEEAKALgCCEAQQBBACgC5AhBAmo2AuAIQQAgAEEAKAKQCGtBAXU2AsAICzQBAX9BASEBAkAgAEF3akH//wNxQQVJDQAgAEGAAXJBoAFGDQAgAEEuRyAAECxxIQELIAELSQEDf0EAIQYCQCAAQXhqIgdBACgCkAgiCEkNACAHIAEgAiADIAQgBRAURQ0AAkAgByAIRw0AQQEPCyAAQXZqLwEAECAhBgsgBgtZAQN/QQAhBAJAIABBfGoiBUEAKAKQCCIGSQ0AIAAvAQAgA0cNACAAQX5qLwEAIAJHDQAgBS8BACABRw0AAkAgBSAGRw0AQQEPCyAAQXpqLwEAECAhBAsgBAtMAQN/QQAhAwJAIABBfmoiBEEAKAKQCCIFSQ0AIAAvAQAgAkcNACAELwEAIAFHDQACQCAEIAVHDQBBAQ8LIABBfGovAQAQICEDCyADC0sBA39BACEHAkAgAEF2aiIIQQAoApAIIglJDQAgCCABIAIgAyAEIAUgBhAvRQ0AAkAgCCAJRw0AQQEPCyAAQXRqLwEAECAhBwsgBwtmAQN/QQAhBQJAIABBemoiBkEAKAKQCCIHSQ0AIAAvAQAgBEcNACAAQX5qLwEAIANHDQAgAEF8ai8BACACRw0AIAYvAQAgAUcNAAJAIAYgB0cNAEEBDwsgAEF4ai8BABAgIQULIAULPQECf0EAIQICQEEAKAKQCCIDIABLDQAgAC8BACABRw0AAkAgAyAARw0AQQEPCyAAQX5qLwEAECAhAgsgAgtNAQN/QQAhCAJAIABBdGoiCUEAKAKQCCIKSQ0AIAkgASACIAMgBCAFIAYgBxAwRQ0AAkAgCSAKRw0AQQEPCyAAQXJqLwEAECAhCAsgCAucAQEDf0EAKALgCCEBAkADQAJAAkAgAS8BACICQS9HDQACQCABLwECIgFBKkYNACABQS9HDQQQEQwCCyAAEBIMAQsCQAJAIABFDQAgAkF3aiIBQRdLDQFBASABdEGfgIAEcUUNAQwCCyACECpFDQMMAQsgAkGgAUcNAgtBAEEAKALgCCIDQQJqIgE2AuAIIANBACgC5AhJDQALCyACC9cDAQF/QQAoAuAIIQICQAJAIAFBIkYNAAJAIAFBJ0cNABAdDAILEB8PCxAcCyAAIAJBAmpBACgC4AhBACgChAgQAUEAQQAoAuAIQQJqNgLgCEEAECghAEEAKALgCCEBAkACQCAAQeEARw0AIAFBAmpB8wBB8wBB5QBB8gBB9AAQFA0BC0EAIAFBfmo2AuAIDwtBACABQQxqNgLgCAJAQQEQKEH7AEYNAEEAIAE2AuAIDwtBACgC4AgiAiEAA0BBACAAQQJqNgLgCAJAAkACQEEBECgiAEEiRg0AIABBJ0cNARAdQQBBACgC4AhBAmo2AuAIQQEQKCEADAILEBxBAEEAKALgCEECajYC4AhBARAoIQAMAQsgABArIQALAkAgAEE6Rg0AQQAgATYC4AgPC0EAQQAoAuAIQQJqNgLgCAJAAkBBARAoIgBBIkYNAAJAIABBJ0cNABAdDAILQQAgATYC4AgPCxAcC0EAQQAoAuAIQQJqNgLgCAJAAkBBARAoIgBBLEYNACAAQf0ARg0BQQAgATYC4AgPC0EAQQAoAuAIQQJqNgLgCEEBEChB/QBGDQBBACgC4AghAAwBCwtBACgCpAgiASACNgIQIAFBACgC4AhBAmo2AgwLMAEBfwJAAkAgAEF3aiIBQRdLDQBBASABdEGNgIAEcQ0BCyAAQaABRg0AQQAPC0EBC20BAn8CQAJAA0ACQCAAQf//A3EiAUF3aiICQRdLDQBBASACdEGfgIAEcQ0CCyABQaABRg0BIAAhAiABECwNAkEAIQJBAEEAKALgCCIAQQJqNgLgCCAALwECIgANAAwCCwsgACECCyACQf//A3ELaAECf0EBIQECQAJAIABBX2oiAkEFSw0AQQEgAnRBMXENAQsgAEH4/wNxQShGDQAgAEFGakH//wNxQQZJDQACQCAAQaV/aiICQQNLDQAgAkEBRw0BCyAAQYV/akH//wNxQQRJIQELIAELYAECfwJAQQAoAuAIIgIvAQAiA0HhAEcNAEEAIAJBBGo2AuAIQQEQKCECQQAoAuAIIQAgAhArGkEAKALgCCEBQQEQKCEDQQAoAuAIIQILAkAgAiAARg0AIAAgARACCyADC4kBAQV/QQAoAuAIIQBBACgC5AghAQN/IABBAmohAgJAAkAgACABTw0AIAIvAQAiA0Gkf2oiBEEBTQ0BIAIhACADQXZqIgNBA0sNAiACIQAgAw4EAAICAAALQQAgAjYC4AgQH0EADwsCQAJAIAQOAgEAAQtBACACNgLgCEHdAA8LIABBBGohAAwACwtJAQF/QQAhBwJAIAAvAQogBkcNACAALwEIIAVHDQAgAC8BBiAERw0AIAAvAQQgA0cNACAALwECIAJHDQAgAC8BACABRiEHCyAHC1MBAX9BACEIAkAgAC8BDCAHRw0AIAAvAQogBkcNACAALwEIIAVHDQAgAC8BBiAERw0AIAAvAQQgA0cNACAALwECIAJHDQAgAC8BACABRiEICyAICwsfAgBBgAgLAgAAAEGECAsQAQAAAAIAAAAABAAAcDgAAA==","undefined"!=typeof Buffer?Buffer.from(E,"base64"):Uint8Array.from(atob(E),A=>A.charCodeAt(0)))).then(WebAssembly.instantiate).then(({exports:A})=>{B=A;});var E;
28358
28359async function transformImportGlob(source, pos, importer, importIndex, root, normalizeUrl, ssr = false) {
28360 const isEager = source.slice(pos, pos + 21) === 'import.meta.globEager';
28361 const isEagerDefault = isEager && source.slice(pos + 21, pos + 28) === 'Default';
28362 const err = (msg) => {
28363 const e = new Error(`Invalid glob import syntax: ${msg}`);
28364 e.pos = pos;
28365 return e;
28366 };
28367 importer = cleanUrl(importer);
28368 const importerBasename = path__default.basename(importer);
28369 let [pattern, endIndex] = lexGlobPattern(source, pos);
28370 if (!pattern.startsWith('.') && !pattern.startsWith('/')) {
28371 throw err(`pattern must start with "." or "/" (relative to project root)`);
28372 }
28373 let base;
28374 let parentDepth = 0;
28375 const isAbsolute = pattern.startsWith('/');
28376 if (isAbsolute) {
28377 base = path__default.resolve(root);
28378 pattern = pattern.slice(1);
28379 }
28380 else {
28381 base = path__default.dirname(importer);
28382 while (pattern.startsWith('../')) {
28383 pattern = pattern.slice(3);
28384 base = path__default.resolve(base, '../');
28385 parentDepth++;
28386 }
28387 if (pattern.startsWith('./')) {
28388 pattern = pattern.slice(2);
28389 }
28390 }
28391 const files = out$1.sync(pattern, {
28392 cwd: base,
28393 ignore: ['**/node_modules/**']
28394 });
28395 const imports = [];
28396 let importsString = ``;
28397 let entries = ``;
28398 for (let i = 0; i < files.length; i++) {
28399 // skip importer itself
28400 if (files[i] === importerBasename)
28401 continue;
28402 const file = isAbsolute
28403 ? `/${files[i]}`
28404 : parentDepth
28405 ? `${'../'.repeat(parentDepth)}${files[i]}`
28406 : `./${files[i]}`;
28407 let importee = file;
28408 if (normalizeUrl) {
28409 [importee] = await normalizeUrl(file, pos);
28410 }
28411 imports.push(importee);
28412 const identifier = `__glob_${importIndex}_${i}`;
28413 if (isEager) {
28414 importsString += `import ${isEagerDefault ? `` : `* as `}${identifier} from ${JSON.stringify(importee)};`;
28415 entries += ` ${JSON.stringify(file)}: ${identifier},`;
28416 }
28417 else {
28418 let imp = `import(${JSON.stringify(importee)})`;
28419 if (!normalizeUrl && !ssr) {
28420 imp =
28421 `(${isModernFlag}` +
28422 `? ${preloadMethod}(()=>${imp},"${preloadMarker}")` +
28423 `: ${imp})`;
28424 }
28425 entries += ` ${JSON.stringify(file)}: () => ${imp},`;
28426 }
28427 }
28428 return {
28429 imports,
28430 importsString,
28431 exp: `{${entries}}`,
28432 endIndex,
28433 isEager,
28434 pattern,
28435 base
28436 };
28437}
28438function lexGlobPattern(code, pos) {
28439 let state = 0 /* inCall */;
28440 let pattern = '';
28441 let i = code.indexOf(`(`, pos) + 1;
28442 outer: for (; i < code.length; i++) {
28443 const char = code.charAt(i);
28444 switch (state) {
28445 case 0 /* inCall */:
28446 if (char === `'`) {
28447 state = 1 /* inSingleQuoteString */;
28448 }
28449 else if (char === `"`) {
28450 state = 2 /* inDoubleQuoteString */;
28451 }
28452 else if (char === '`') {
28453 state = 3 /* inTemplateString */;
28454 }
28455 else if (/\s/.test(char)) {
28456 continue;
28457 }
28458 else {
28459 error$4(i);
28460 }
28461 break;
28462 case 1 /* inSingleQuoteString */:
28463 if (char === `'`) {
28464 break outer;
28465 }
28466 else {
28467 pattern += char;
28468 }
28469 break;
28470 case 2 /* inDoubleQuoteString */:
28471 if (char === `"`) {
28472 break outer;
28473 }
28474 else {
28475 pattern += char;
28476 }
28477 break;
28478 case 3 /* inTemplateString */:
28479 if (char === '`') {
28480 break outer;
28481 }
28482 else {
28483 pattern += char;
28484 }
28485 break;
28486 default:
28487 throw new Error('unknown import.meta.glob lexer state');
28488 }
28489 }
28490 return [pattern, code.indexOf(`)`, i) + 1];
28491}
28492function error$4(pos) {
28493 const err = new Error(`import.meta.glob() can only accept string literals.`);
28494 err.pos = pos;
28495 throw err;
28496}
28497
28498/**
28499 * A flag for injected helpers. This flag will be set to `false` if the output
28500 * target is not native es - so that injected helper logic can be conditionally
28501 * dropped.
28502 */
28503const isModernFlag = `__VITE_IS_MODERN__`;
28504const preloadMethod = `__vitePreload`;
28505const preloadMarker = `__VITE_PRELOAD__`;
28506const preloadHelperId = 'vite/preload-helper';
28507const preloadCode = `let scriptRel;const seen = {};export const ${preloadMethod} = ${preload.toString()}`;
28508const preloadMarkerRE = new RegExp(`"${preloadMarker}"`, 'g');
28509/**
28510 * Helper for preloading CSS and direct imports of async chunks in parallel to
28511 * the async chunk itself.
28512 */
28513function preload(baseModule, deps) {
28514 // @ts-ignore
28515 if (!__VITE_IS_MODERN__ || !deps) {
28516 return baseModule();
28517 }
28518 // @ts-ignore
28519 if (scriptRel === undefined) {
28520 // @ts-ignore
28521 const relList = document.createElement('link').relList;
28522 // @ts-ignore
28523 scriptRel =
28524 relList && relList.supports && relList.supports('modulepreload')
28525 ? 'modulepreload'
28526 : 'preload';
28527 }
28528 return Promise.all(deps.map((dep) => {
28529 // @ts-ignore
28530 if (dep in seen)
28531 return;
28532 // @ts-ignore
28533 seen[dep] = true;
28534 const isCss = dep.endsWith('.css');
28535 const cssSelector = isCss ? '[rel="stylesheet"]' : '';
28536 // @ts-ignore check if the file is already preloaded by SSR markup
28537 if (document.querySelector(`link[href="${dep}"]${cssSelector}`)) {
28538 return;
28539 }
28540 // @ts-ignore
28541 const link = document.createElement('link');
28542 // @ts-ignore
28543 link.rel = isCss ? 'stylesheet' : scriptRel;
28544 if (!isCss) {
28545 link.as = 'script';
28546 link.crossOrigin = '';
28547 }
28548 link.href = dep;
28549 // @ts-ignore
28550 document.head.appendChild(link);
28551 if (isCss) {
28552 return new Promise((res, rej) => {
28553 link.addEventListener('load', res);
28554 link.addEventListener('error', rej);
28555 });
28556 }
28557 })).then(() => baseModule());
28558}
28559/**
28560 * Build only. During serve this is performed as part of ./importAnalysis.
28561 */
28562function buildImportAnalysisPlugin(config) {
28563 const ssr = !!config.build.ssr;
28564 return {
28565 name: 'vite:import-analysis',
28566 resolveId(id) {
28567 if (id === preloadHelperId) {
28568 return id;
28569 }
28570 },
28571 load(id) {
28572 if (id === preloadHelperId) {
28573 return preloadCode;
28574 }
28575 },
28576 async transform(source, importer) {
28577 if (importer.includes('node_modules') &&
28578 !source.includes('import.meta.glob')) {
28579 return;
28580 }
28581 await init;
28582 let imports = [];
28583 try {
28584 imports = parse$e(source)[0];
28585 }
28586 catch (e) {
28587 this.error(e, e.idx);
28588 }
28589 if (!imports.length) {
28590 return null;
28591 }
28592 let s;
28593 const str = () => s || (s = new MagicString(source));
28594 let needPreloadHelper = false;
28595 for (let index = 0; index < imports.length; index++) {
28596 const { s: start, e: end, ss: expStart, d: dynamicIndex } = imports[index];
28597 const isGlob = source.slice(start, end) === 'import.meta' &&
28598 source.slice(end, end + 5) === '.glob';
28599 // import.meta.glob
28600 if (isGlob) {
28601 const { importsString, exp, endIndex, isEager } = await transformImportGlob(source, start, importer, index, config.root, undefined, ssr);
28602 str().prepend(importsString);
28603 str().overwrite(expStart, endIndex, exp);
28604 if (!isEager) {
28605 needPreloadHelper = true;
28606 }
28607 continue;
28608 }
28609 if (dynamicIndex > -1 && !ssr) {
28610 needPreloadHelper = true;
28611 const dynamicEnd = source.indexOf(`)`, end) + 1;
28612 const original = source.slice(dynamicIndex, dynamicEnd);
28613 const replacement = `${preloadMethod}(() => ${original},${isModernFlag}?"${preloadMarker}":void 0)`;
28614 str().overwrite(dynamicIndex, dynamicEnd, replacement);
28615 }
28616 }
28617 if (needPreloadHelper &&
28618 !ssr &&
28619 !source.includes(`const ${preloadMethod} =`)) {
28620 str().prepend(`import { ${preloadMethod} } from "${preloadHelperId}";`);
28621 }
28622 if (s) {
28623 return {
28624 code: s.toString(),
28625 map: config.build.sourcemap ? s.generateMap({ hires: true }) : null
28626 };
28627 }
28628 },
28629 renderChunk(code, _, { format }) {
28630 // make sure we only perform the preload logic in modern builds.
28631 if (code.indexOf(isModernFlag) > -1) {
28632 const re = new RegExp(isModernFlag, 'g');
28633 const isModern = String(format === 'es');
28634 if (config.build.sourcemap) {
28635 const s = new MagicString(code);
28636 let match;
28637 while ((match = re.exec(code))) {
28638 s.overwrite(match.index, match.index + isModernFlag.length, isModern);
28639 }
28640 return {
28641 code: s.toString(),
28642 map: s.generateMap({ hires: true })
28643 };
28644 }
28645 else {
28646 return code.replace(re, isModern);
28647 }
28648 }
28649 return null;
28650 },
28651 generateBundle({ format }, bundle) {
28652 if (format !== 'es' || ssr) {
28653 return;
28654 }
28655 const isPolyfillEnabled = config.build.polyfillDynamicImport;
28656 for (const file in bundle) {
28657 const chunk = bundle[file];
28658 // can't use chunk.dynamicImports.length here since some modules e.g.
28659 // dynamic import to constant json may get inlined.
28660 if (chunk.type === 'chunk' && chunk.code.indexOf(preloadMarker) > -1) {
28661 const code = chunk.code;
28662 let imports;
28663 try {
28664 imports = parse$e(code)[0].filter((i) => i.d > -1);
28665 }
28666 catch (e) {
28667 this.error(e, e.idx);
28668 }
28669 if (imports.length) {
28670 const s = new MagicString(code);
28671 for (let index = 0; index < imports.length; index++) {
28672 const { s: start, e: end, d: dynamicIndex } = imports[index];
28673 // if dynamic import polyfill is used, rewrite the import to
28674 // use the polyfilled function.
28675 if (isPolyfillEnabled) {
28676 s.overwrite(dynamicIndex, dynamicIndex + 6, `__import__`);
28677 }
28678 // check the chunk being imported
28679 const url = code.slice(start, end);
28680 const deps = new Set();
28681 if (url[0] === `"` && url[url.length - 1] === `"`) {
28682 const ownerFilename = chunk.fileName;
28683 // literal import - trace direct imports and add to deps
28684 const analyzed = new Set();
28685 const addDeps = (filename) => {
28686 if (filename === ownerFilename)
28687 return;
28688 if (analyzed.has(filename))
28689 return;
28690 analyzed.add(filename);
28691 const chunk = bundle[filename];
28692 if (chunk) {
28693 deps.add(config.base + chunk.fileName);
28694 const cssFiles = chunkToEmittedCssFileMap.get(chunk);
28695 if (cssFiles) {
28696 cssFiles.forEach((file) => {
28697 deps.add(config.base + file);
28698 });
28699 }
28700 chunk.imports.forEach(addDeps);
28701 }
28702 };
28703 const normalizedFile = path__default.posix.join(path__default.posix.dirname(chunk.fileName), url.slice(1, -1));
28704 addDeps(normalizedFile);
28705 }
28706 const markPos = code.indexOf(preloadMarker, end);
28707 if (markPos > 0) {
28708 s.overwrite(markPos - 1, markPos + preloadMarker.length + 1,
28709 // the dep list includes the main chunk, so only need to
28710 // preload when there are actual other deps.
28711 deps.size > 1
28712 ? `[${[...deps].map((d) => JSON.stringify(d)).join(',')}]`
28713 : `void 0`);
28714 }
28715 }
28716 chunk.code = s.toString();
28717 // TODO source map
28718 }
28719 // there may still be markers due to inlined dynamic imports, remove
28720 // all the markers regardless
28721 chunk.code = chunk.code.replace(preloadMarkerRE, 'void 0');
28722 }
28723 }
28724 }
28725 };
28726}
28727
28728const polyfillId = 'vite/dynamic-import-polyfill';
28729function resolveModulePath(config) {
28730 const { base, build: { assetsDir } } = config;
28731 // #2918 path.posix.join returns a wrong path when config.base is a URL
28732 if (/^(https?:)?(\/\/)/i.test(base)) {
28733 return `${base.replace(/\/$/, '')}/${assetsDir}/`;
28734 }
28735 return path__default.posix.join(base, assetsDir, '/');
28736}
28737function dynamicImportPolyfillPlugin(config) {
28738 const enabled = config.build.polyfillDynamicImport;
28739 const skip = !enabled || config.command === 'serve' || config.build.ssr;
28740 let polyfillString;
28741 return {
28742 name: 'vite:dynamic-import-polyfill',
28743 resolveId(id) {
28744 if (id === polyfillId) {
28745 return id;
28746 }
28747 },
28748 load(id) {
28749 if (id === polyfillId) {
28750 if (!enabled && config.command === 'build') {
28751 config.logger.warnOnce(`\n'vite/dynamic-import-polyfill' is no longer needed if you target modern browsers`);
28752 }
28753 if (skip) {
28754 return '';
28755 }
28756 // return a placeholder here and defer the injection to renderChunk
28757 // so that we can selectively skip the injection based on output format
28758 if (!polyfillString) {
28759 polyfillString =
28760 `const p = ${polyfill.toString()};` +
28761 `${isModernFlag}&&p(${JSON.stringify(resolveModulePath(config))});`;
28762 }
28763 return polyfillString;
28764 }
28765 },
28766 renderDynamicImport({ format }) {
28767 if (skip || format !== 'es') {
28768 return null;
28769 }
28770 if (!polyfillString) {
28771 throw new Error(`Vite's dynamic import polyfill is enabled but was never imported. This ` +
28772 `should only happen when using custom non-html rollup inputs. Make ` +
28773 `sure to add \`import "${polyfillId}"\` as the first statement in ` +
28774 `your custom entry.`);
28775 }
28776 // we do not actually return anything here because rewriting here would
28777 // make it impossible to use es-module-lexer on the rendered chunks, which
28778 // we need for import graph optimization in ./importAnalysisBuild.
28779 }
28780 };
28781}
28782function polyfill(modulePath = '.', importFunctionName = '__import__') {
28783 try {
28784 self[importFunctionName] = new Function('u', `return import(u)`);
28785 }
28786 catch (error) {
28787 const baseURL = new URL(modulePath, location);
28788 const cleanup = (script) => {
28789 URL.revokeObjectURL(script.src);
28790 script.remove();
28791 };
28792 self[importFunctionName] = (url) => new Promise((resolve, reject) => {
28793 const absURL = new URL(url, baseURL);
28794 // If the module has already been imported, resolve immediately.
28795 if (self[importFunctionName].moduleMap[absURL]) {
28796 return resolve(self[importFunctionName].moduleMap[absURL]);
28797 }
28798 const moduleBlob = new Blob([
28799 `import * as m from '${absURL}';`,
28800 `${importFunctionName}.moduleMap['${absURL}']=m;`
28801 ], { type: 'text/javascript' });
28802 const script = Object.assign(document.createElement('script'), {
28803 type: 'module',
28804 src: URL.createObjectURL(moduleBlob),
28805 onerror() {
28806 reject(new Error(`Failed to import: ${url}`));
28807 cleanup(script);
28808 },
28809 onload() {
28810 resolve(self[importFunctionName].moduleMap[absURL]);
28811 cleanup(script);
28812 }
28813 });
28814 document.head.appendChild(script);
28815 });
28816 self[importFunctionName].moduleMap = {};
28817 }
28818}
28819
28820const htmlProxyRE = /\?html-proxy&index=(\d+)\.js$/;
28821const isHTMLProxy = (id) => htmlProxyRE.test(id);
28822const htmlCommentRE = /<!--[\s\S]*?-->/g;
28823const scriptModuleRE$1 = /(<script\b[^>]*type\s*=\s*(?:"module"|'module')[^>]*>)(.*?)<\/script>/gims;
28824function htmlInlineScriptProxyPlugin() {
28825 return {
28826 name: 'vite:html',
28827 resolveId(id) {
28828 if (htmlProxyRE.test(id)) {
28829 return id;
28830 }
28831 },
28832 load(id) {
28833 const proxyMatch = id.match(htmlProxyRE);
28834 if (proxyMatch) {
28835 const index = Number(proxyMatch[1]);
28836 const file = cleanUrl(id);
28837 const html = fs__default.readFileSync(file, 'utf-8').replace(htmlCommentRE, '');
28838 let match;
28839 scriptModuleRE$1.lastIndex = 0;
28840 for (let i = 0; i <= index; i++) {
28841 match = scriptModuleRE$1.exec(html);
28842 }
28843 if (match) {
28844 return match[2];
28845 }
28846 else {
28847 throw new Error(`No matching html proxy module found from ${id}`);
28848 }
28849 }
28850 }
28851 };
28852}
28853// this extends the config in @vue/compiler-sfc with <link href>
28854const assetAttrsConfig = {
28855 link: ['href'],
28856 video: ['src', 'poster'],
28857 source: ['src', 'srcset'],
28858 img: ['src', 'srcset'],
28859 image: ['xlink:href', 'href'],
28860 use: ['xlink:href', 'href']
28861};
28862async function traverseHtml(html, filePath, visitor) {
28863 // lazy load compiler
28864 const { parse, transform } = await Promise.resolve().then(function () { return require('./dep-7db2a04d.js'); }).then(function (n) { return n.compilerDom_cjs; });
28865 // @vue/compiler-core doesn't like lowercase doctypes
28866 html = html.replace(/<!doctype\s/i, '<!DOCTYPE ');
28867 try {
28868 const ast = parse(html, { comments: true });
28869 transform(ast, {
28870 nodeTransforms: [visitor]
28871 });
28872 }
28873 catch (e) {
28874 const parseError = {
28875 loc: filePath,
28876 frame: '',
28877 ...formatParseError(e, filePath, html)
28878 };
28879 throw new Error(`Unable to parse ${JSON.stringify(parseError.loc)}\n${parseError.frame}`);
28880 }
28881}
28882function getScriptInfo(node) {
28883 let src;
28884 let isModule = false;
28885 for (let i = 0; i < node.props.length; i++) {
28886 const p = node.props[i];
28887 if (p.type === 6 /* ATTRIBUTE */) {
28888 if (p.name === 'src') {
28889 src = p;
28890 }
28891 else if (p.name === 'type' && p.value && p.value.content === 'module') {
28892 isModule = true;
28893 }
28894 }
28895 }
28896 return { src, isModule };
28897}
28898function formatParseError(e, id, html) {
28899 // normalize the error to rollup format
28900 if (e.loc) {
28901 e.frame = generateCodeFrame(html, e.loc.start.offset);
28902 e.loc = {
28903 file: id,
28904 line: e.loc.start.line,
28905 column: e.loc.start.column
28906 };
28907 }
28908 return e;
28909}
28910/**
28911 * Compiles index.html into an entry js module
28912 */
28913function buildHtmlPlugin(config) {
28914 const [preHooks, postHooks] = resolveHtmlTransforms(config.plugins);
28915 const processedHtml = new Map();
28916 const isExcludedUrl = (url) => url.startsWith('#') ||
28917 isExternalUrl(url) ||
28918 isDataUrl(url) ||
28919 checkPublicFile(url, config);
28920 return {
28921 name: 'vite:build-html',
28922 async transform(html, id) {
28923 if (id.endsWith('.html')) {
28924 const publicPath = `/${slash$3(path__default.relative(config.root, id))}`;
28925 // pre-transform
28926 html = await applyHtmlTransforms(html, preHooks, {
28927 path: publicPath,
28928 filename: id
28929 });
28930 let js = '';
28931 const s = new MagicString(html);
28932 const assetUrls = [];
28933 let inlineModuleIndex = -1;
28934 await traverseHtml(html, id, (node) => {
28935 if (node.type !== 1 /* ELEMENT */) {
28936 return;
28937 }
28938 let shouldRemove = false;
28939 // script tags
28940 if (node.tag === 'script') {
28941 const { src, isModule } = getScriptInfo(node);
28942 const url = src && src.value && src.value.content;
28943 if (url && checkPublicFile(url, config)) {
28944 // referencing public dir url, prefix with base
28945 s.overwrite(src.value.loc.start.offset, src.value.loc.end.offset, `"${config.base + url.slice(1)}"`);
28946 }
28947 if (isModule) {
28948 inlineModuleIndex++;
28949 if (url && !isExcludedUrl(url)) {
28950 // <script type="module" src="..."/>
28951 // add it as an import
28952 js += `\nimport ${JSON.stringify(url)}`;
28953 shouldRemove = true;
28954 }
28955 else if (node.children.length) {
28956 // <script type="module">...</script>
28957 js += `\nimport "${id}?html-proxy&index=${inlineModuleIndex}.js"`;
28958 shouldRemove = true;
28959 }
28960 }
28961 }
28962 // For asset references in index.html, also generate an import
28963 // statement for each - this will be handled by the asset plugin
28964 const assetAttrs = assetAttrsConfig[node.tag];
28965 if (assetAttrs) {
28966 for (const p of node.props) {
28967 if (p.type === 6 /* ATTRIBUTE */ &&
28968 p.value &&
28969 assetAttrs.includes(p.name)) {
28970 const url = p.value.content;
28971 if (!isExcludedUrl(url)) {
28972 if (node.tag === 'link' && isCSSRequest(url)) {
28973 // CSS references, convert to import
28974 js += `\nimport ${JSON.stringify(url)}`;
28975 shouldRemove = true;
28976 }
28977 else {
28978 assetUrls.push(p);
28979 }
28980 }
28981 else if (checkPublicFile(url, config)) {
28982 s.overwrite(p.value.loc.start.offset, p.value.loc.end.offset, `"${config.base + url.slice(1)}"`);
28983 }
28984 }
28985 }
28986 }
28987 if (shouldRemove) {
28988 // remove the script tag from the html. we are going to inject new
28989 // ones in the end.
28990 s.remove(node.loc.start.offset, node.loc.end.offset);
28991 }
28992 });
28993 // for each encountered asset url, rewrite original html so that it
28994 // references the post-build location.
28995 for (const attr of assetUrls) {
28996 const value = attr.value;
28997 try {
28998 const url = attr.name === 'srcset'
28999 ? await processSrcSet(value.content, ({ url }) => urlToBuiltUrl(url, id, config, this))
29000 : await urlToBuiltUrl(value.content, id, config, this);
29001 s.overwrite(value.loc.start.offset, value.loc.end.offset, `"${url}"`);
29002 }
29003 catch (e) {
29004 // #1885 preload may be pointing to urls that do not exist
29005 // locally on disk
29006 if (e.code !== 'ENOENT') {
29007 throw e;
29008 }
29009 }
29010 }
29011 processedHtml.set(id, s.toString());
29012 // inject dynamic import polyfill
29013 if (config.build.polyfillDynamicImport) {
29014 js = `import "${polyfillId}";\n${js}`;
29015 }
29016 return js;
29017 }
29018 },
29019 async generateBundle(_, bundle) {
29020 const analyzedChunk = new Map();
29021 const getPreloadLinksForChunk = (chunk, seen = new Set()) => {
29022 const tags = [];
29023 chunk.imports.forEach((file) => {
29024 const importee = bundle[file];
29025 if ((importee === null || importee === void 0 ? void 0 : importee.type) === 'chunk' && !seen.has(file)) {
29026 seen.add(file);
29027 tags.push({
29028 tag: 'link',
29029 attrs: {
29030 rel: 'modulepreload',
29031 href: toPublicPath(file, config)
29032 }
29033 });
29034 tags.push(...getPreloadLinksForChunk(importee, seen));
29035 }
29036 });
29037 return tags;
29038 };
29039 const getCssTagsForChunk = (chunk, seen = new Set()) => {
29040 const tags = [];
29041 if (!analyzedChunk.has(chunk)) {
29042 analyzedChunk.set(chunk, 1);
29043 chunk.imports.forEach((file) => {
29044 const importee = bundle[file];
29045 if ((importee === null || importee === void 0 ? void 0 : importee.type) === 'chunk') {
29046 tags.push(...getCssTagsForChunk(importee, seen));
29047 }
29048 });
29049 }
29050 const cssFiles = chunkToEmittedCssFileMap.get(chunk);
29051 if (cssFiles) {
29052 cssFiles.forEach((file) => {
29053 if (!seen.has(file)) {
29054 seen.add(file);
29055 tags.push({
29056 tag: 'link',
29057 attrs: {
29058 rel: 'stylesheet',
29059 href: toPublicPath(file, config)
29060 }
29061 });
29062 }
29063 });
29064 }
29065 return tags;
29066 };
29067 for (const [id, html] of processedHtml) {
29068 // resolve asset url references
29069 let result = html.replace(assetUrlRE, (_, fileHash, postfix = '') => {
29070 return config.base + getAssetFilename(fileHash, config) + postfix;
29071 });
29072 // find corresponding entry chunk
29073 const chunk = Object.values(bundle).find((chunk) => chunk.type === 'chunk' &&
29074 chunk.isEntry &&
29075 chunk.facadeModuleId === id);
29076 // inject chunk asset links
29077 if (chunk) {
29078 const assetTags = [
29079 // js entry chunk for this page
29080 {
29081 tag: 'script',
29082 attrs: {
29083 type: 'module',
29084 crossorigin: true,
29085 src: toPublicPath(chunk.fileName, config)
29086 }
29087 },
29088 // preload for imports
29089 ...getPreloadLinksForChunk(chunk),
29090 ...getCssTagsForChunk(chunk)
29091 ];
29092 result = injectToHead(result, assetTags);
29093 }
29094 // inject css link when cssCodeSplit is false
29095 if (!config.build.cssCodeSplit) {
29096 const cssChunk = Object.values(bundle).find((chunk) => chunk.type === 'asset' && chunk.name === 'style.css');
29097 if (cssChunk) {
29098 result = injectToHead(result, [
29099 {
29100 tag: 'link',
29101 attrs: {
29102 rel: 'stylesheet',
29103 href: toPublicPath(cssChunk.fileName, config)
29104 }
29105 }
29106 ]);
29107 }
29108 }
29109 const shortEmitName = path__default.posix.relative(config.root, id);
29110 result = await applyHtmlTransforms(result, postHooks, {
29111 path: '/' + shortEmitName,
29112 filename: id,
29113 bundle,
29114 chunk
29115 });
29116 this.emitFile({
29117 type: 'asset',
29118 fileName: shortEmitName,
29119 source: result
29120 });
29121 }
29122 }
29123 };
29124}
29125function resolveHtmlTransforms(plugins) {
29126 const preHooks = [];
29127 const postHooks = [];
29128 for (const plugin of plugins) {
29129 const hook = plugin.transformIndexHtml;
29130 if (hook) {
29131 if (typeof hook === 'function') {
29132 postHooks.push(hook);
29133 }
29134 else if (hook.enforce === 'pre') {
29135 preHooks.push(hook.transform);
29136 }
29137 else {
29138 postHooks.push(hook.transform);
29139 }
29140 }
29141 }
29142 return [preHooks, postHooks];
29143}
29144async function applyHtmlTransforms(html, hooks, ctx) {
29145 const headTags = [];
29146 const headPrependTags = [];
29147 const bodyTags = [];
29148 const bodyPrependTags = [];
29149 for (const hook of hooks) {
29150 const res = await hook(html, ctx);
29151 if (!res) {
29152 continue;
29153 }
29154 if (typeof res === 'string') {
29155 html = res;
29156 }
29157 else {
29158 let tags;
29159 if (Array.isArray(res)) {
29160 tags = res;
29161 }
29162 else {
29163 html = res.html || html;
29164 tags = res.tags;
29165 }
29166 for (const tag of tags) {
29167 if (tag.injectTo === 'body') {
29168 bodyTags.push(tag);
29169 }
29170 else if (tag.injectTo === 'body-prepend') {
29171 bodyPrependTags.push(tag);
29172 }
29173 else if (tag.injectTo === 'head') {
29174 headTags.push(tag);
29175 }
29176 else {
29177 headPrependTags.push(tag);
29178 }
29179 }
29180 }
29181 }
29182 // inject tags
29183 if (headPrependTags.length) {
29184 html = injectToHead(html, headPrependTags, true);
29185 }
29186 if (headTags.length) {
29187 html = injectToHead(html, headTags);
29188 }
29189 if (bodyPrependTags.length) {
29190 html = injectToBody(html, bodyPrependTags, true);
29191 }
29192 if (bodyTags.length) {
29193 html = injectToBody(html, bodyTags);
29194 }
29195 return html;
29196}
29197function toPublicPath(filename, config) {
29198 return isExternalUrl(filename) ? filename : config.base + filename;
29199}
29200const headInjectRE = /<\/head>/;
29201const headPrependInjectRE = [/<head>/, /<!doctype html>/i];
29202function injectToHead(html, tags, prepend = false) {
29203 const tagsHtml = serializeTags(tags);
29204 if (prepend) {
29205 // inject after head or doctype
29206 for (const re of headPrependInjectRE) {
29207 if (re.test(html)) {
29208 return html.replace(re, `$&\n${tagsHtml}`);
29209 }
29210 }
29211 }
29212 else {
29213 // inject before head close
29214 if (headInjectRE.test(html)) {
29215 return html.replace(headInjectRE, `${tagsHtml}\n$&`);
29216 }
29217 }
29218 // if no <head> tag is present, just prepend
29219 return tagsHtml + `\n` + html;
29220}
29221const bodyInjectRE = /<\/body>/;
29222const bodyPrependInjectRE = /<body>/;
29223function injectToBody(html, tags, prepend = false) {
29224 if (prepend) {
29225 // inject after body open
29226 const tagsHtml = `\n` + serializeTags(tags);
29227 if (bodyPrependInjectRE.test(html)) {
29228 return html.replace(bodyPrependInjectRE, `$&\n${tagsHtml}`);
29229 }
29230 // if no body, prepend
29231 return tagsHtml + `\n` + html;
29232 }
29233 else {
29234 // inject before body close
29235 const tagsHtml = `\n` + serializeTags(tags);
29236 if (bodyInjectRE.test(html)) {
29237 return html.replace(bodyInjectRE, `${tagsHtml}\n$&`);
29238 }
29239 // if no body, append
29240 return html + `\n` + tagsHtml;
29241 }
29242}
29243const unaryTags = new Set(['link', 'meta', 'base']);
29244function serializeTag({ tag, attrs, children }) {
29245 if (unaryTags.has(tag)) {
29246 return `<${tag}${serializeAttrs(attrs)}>`;
29247 }
29248 else {
29249 return `<${tag}${serializeAttrs(attrs)}>${serializeTags(children)}</${tag}>`;
29250 }
29251}
29252function serializeTags(tags) {
29253 if (typeof tags === 'string') {
29254 return tags;
29255 }
29256 else if (tags) {
29257 return tags.map(serializeTag).join(`\n `);
29258 }
29259 return '';
29260}
29261function serializeAttrs(attrs) {
29262 let res = '';
29263 for (const key in attrs) {
29264 if (typeof attrs[key] === 'boolean') {
29265 res += attrs[key] ? ` ${key}` : ``;
29266 }
29267 else {
29268 res += ` ${key}=${JSON.stringify(attrs[key])}`;
29269 }
29270 }
29271 return res;
29272}
29273
29274const debug$b = createDebugger('vite:esbuild');
29275async function transformWithEsbuild(code, filename, options, inMap) {
29276 // if the id ends with a valid ext, use it (e.g. vue blocks)
29277 // otherwise, cleanup the query before checking the ext
29278 const ext = path__default.extname(/\.\w+$/.test(filename) ? filename : cleanUrl(filename));
29279 let loader = ext.slice(1);
29280 if (loader === 'cjs' || loader === 'mjs') {
29281 loader = 'js';
29282 }
29283 const resolvedOptions = {
29284 loader: loader,
29285 sourcemap: true,
29286 // ensure source file name contains full query
29287 sourcefile: filename,
29288 ...options
29289 };
29290 delete resolvedOptions.include;
29291 delete resolvedOptions.exclude;
29292 delete resolvedOptions.jsxInject;
29293 try {
29294 const result = await esbuild.transform(code, resolvedOptions);
29295 if (inMap) {
29296 const nextMap = JSON.parse(result.map);
29297 nextMap.sourcesContent = [];
29298 return {
29299 ...result,
29300 map: combineSourcemaps(filename, [
29301 nextMap,
29302 inMap
29303 ])
29304 };
29305 }
29306 else {
29307 return {
29308 ...result,
29309 map: JSON.parse(result.map)
29310 };
29311 }
29312 }
29313 catch (e) {
29314 debug$b(`esbuild error with options used: `, resolvedOptions);
29315 // patch error information
29316 if (e.errors) {
29317 e.frame = '';
29318 e.errors.forEach((m) => {
29319 e.frame += `\n` + prettifyMessage(m, code);
29320 });
29321 e.loc = e.errors[0].location;
29322 }
29323 throw e;
29324 }
29325}
29326function esbuildPlugin(options = {}) {
29327 const filter = createFilter$1(options.include || /\.(tsx?|jsx)$/, options.exclude || /\.js$/);
29328 return {
29329 name: 'vite:esbuild',
29330 async transform(code, id) {
29331 if (filter(id) || filter(cleanUrl(id))) {
29332 const result = await transformWithEsbuild(code, id, options);
29333 if (result.warnings.length) {
29334 result.warnings.forEach((m) => {
29335 this.warn(prettifyMessage(m, code));
29336 });
29337 }
29338 if (options.jsxInject && /\.(?:j|t)sx\b/.test(id)) {
29339 result.code = options.jsxInject + ';' + result.code;
29340 }
29341 return {
29342 code: result.code,
29343 map: result.map
29344 };
29345 }
29346 }
29347 };
29348}
29349const buildEsbuildPlugin = (config) => {
29350 return {
29351 name: 'vite:esbuild-transpile',
29352 async renderChunk(code, chunk, opts) {
29353 // @ts-ignore injected by @vitejs/plugin-legacy
29354 if (opts.__vite_skip_esbuild__) {
29355 return null;
29356 }
29357 const target = config.build.target;
29358 const minify = config.build.minify === 'esbuild';
29359 if ((!target || target === 'esnext') && !minify) {
29360 return null;
29361 }
29362 return transformWithEsbuild(code, chunk.fileName, {
29363 target: target || undefined,
29364 minify
29365 });
29366 }
29367 };
29368};
29369function prettifyMessage(m, code) {
29370 let res = source.yellow(m.text);
29371 if (m.location) {
29372 const lines = code.split(/\r?\n/g);
29373 const line = Number(m.location.line);
29374 const column = Number(m.location.column);
29375 const offset = lines
29376 .slice(0, line - 1)
29377 .map((l) => l.length)
29378 .reduce((total, l) => total + l + 1, 0) + column;
29379 res += `\n` + generateCodeFrame(code, offset, offset + 1);
29380 }
29381 return res + `\n`;
29382}
29383
29384var dist = {};
29385
29386var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
29387 return (mod && mod.__esModule) ? mod : { "default": mod };
29388};
29389Object.defineProperty(dist, "__esModule", { value: true });
29390var Worker_1 = dist.Worker = void 0;
29391const os_1 = __importDefault(require$$0__default$1);
29392const worker_threads_1 = require$$1__default;
29393class Worker {
29394 constructor(fn, options = {}) {
29395 this.code = genWorkerCode(fn);
29396 this.max = options.max || Math.max(1, os_1.default.cpus().length - 1);
29397 this.pool = [];
29398 this.idlePool = [];
29399 this.queue = [];
29400 }
29401 async run(...args) {
29402 const worker = await this._getAvailableWorker();
29403 return new Promise((resolve, reject) => {
29404 worker.currentResolve = resolve;
29405 worker.currentReject = reject;
29406 worker.postMessage(args);
29407 });
29408 }
29409 stop() {
29410 this.pool.forEach((w) => w.unref());
29411 this.queue.forEach(([_, reject]) => reject(new Error('Main worker pool stopped before a worker was available.')));
29412 this.pool = [];
29413 this.idlePool = [];
29414 this.queue = [];
29415 }
29416 async _getAvailableWorker() {
29417 // has idle one?
29418 if (this.idlePool.length) {
29419 return this.idlePool.shift();
29420 }
29421 // can spawn more?
29422 if (this.pool.length < this.max) {
29423 const worker = new worker_threads_1.Worker(this.code, { eval: true });
29424 worker.on('message', (res) => {
29425 worker.currentResolve && worker.currentResolve(res);
29426 worker.currentResolve = null;
29427 this._assignDoneWorker(worker);
29428 });
29429 worker.on('error', (err) => {
29430 worker.currentReject && worker.currentReject(err);
29431 worker.currentReject = null;
29432 });
29433 worker.on('exit', (code) => {
29434 const i = this.pool.indexOf(worker);
29435 if (i > -1)
29436 this.pool.splice(i, 1);
29437 if (code !== 0 && worker.currentReject) {
29438 worker.currentReject(new Error(`Wroker stopped with non-0 exit code ${code}`));
29439 worker.currentReject = null;
29440 }
29441 });
29442 this.pool.push(worker);
29443 return worker;
29444 }
29445 // no one is available, we have to wait
29446 let resolve;
29447 let reject;
29448 const onWorkerAvailablePromise = new Promise((r, rj) => {
29449 resolve = r;
29450 reject = rj;
29451 });
29452 this.queue.push([resolve, reject]);
29453 return onWorkerAvailablePromise;
29454 }
29455 _assignDoneWorker(worker) {
29456 // someone's waiting already?
29457 if (this.queue.length) {
29458 const [resolve] = this.queue.shift();
29459 resolve(worker);
29460 return;
29461 }
29462 // take a rest.
29463 this.idlePool.push(worker);
29464 }
29465}
29466Worker_1 = dist.Worker = Worker;
29467function genWorkerCode(fn) {
29468 return `
29469const doWork = ${fn.toString()}
29470
29471const { parentPort } = require('worker_threads')
29472
29473parentPort.on('message', async (args) => {
29474 const res = await doWork(...args)
29475 parentPort.postMessage(res)
29476})
29477 `;
29478}
29479
29480function terserPlugin(options) {
29481 const worker = new Worker_1((basedir, code, options) => {
29482 // when vite is linked, the worker thread won't share the same resolve
29483 // root with vite itself, so we have to pass in the basedir and resolve
29484 // terser first.
29485 // eslint-disable-next-line node/no-restricted-require
29486 const terserPath = require.resolve('vite/dist/node/terser', {
29487 paths: [basedir]
29488 });
29489 return require(terserPath).minify(code, options);
29490 });
29491 return {
29492 name: 'vite:terser',
29493 async renderChunk(code, _chunk, outputOptions) {
29494 const res = await worker.run(__dirname, code, {
29495 safari10: true,
29496 ...options,
29497 sourceMap: !!outputOptions.sourcemap,
29498 module: outputOptions.format.startsWith('es'),
29499 toplevel: outputOptions.format === 'cjs'
29500 });
29501 return {
29502 code: res.code,
29503 map: res.map
29504 };
29505 },
29506 closeBundle() {
29507 worker.stop();
29508 }
29509 };
29510}
29511
29512function manifestPlugin(config) {
29513 const manifest = {};
29514 let outputCount;
29515 return {
29516 name: 'vite:manifest',
29517 buildStart() {
29518 outputCount = 0;
29519 },
29520 generateBundle({ format }, bundle) {
29521 var _a;
29522 function getChunkName(chunk) {
29523 if (chunk.facadeModuleId) {
29524 let name = normalizePath$4(path__default.relative(config.root, chunk.facadeModuleId));
29525 if (format === 'system' && !chunk.name.includes('-legacy')) {
29526 const ext = path__default.extname(name);
29527 name = name.slice(0, -ext.length) + `-legacy` + ext;
29528 }
29529 return name;
29530 }
29531 else {
29532 return `_` + path__default.basename(chunk.fileName);
29533 }
29534 }
29535 function getInternalImports(imports) {
29536 const filteredImports = [];
29537 for (const file of imports) {
29538 if (bundle[file] === undefined) {
29539 continue;
29540 }
29541 filteredImports.push(getChunkName(bundle[file]));
29542 }
29543 return filteredImports;
29544 }
29545 function createChunk(chunk) {
29546 const manifestChunk = {
29547 file: chunk.fileName
29548 };
29549 if (chunk.facadeModuleId) {
29550 manifestChunk.src = getChunkName(chunk);
29551 }
29552 if (chunk.isEntry) {
29553 manifestChunk.isEntry = true;
29554 }
29555 if (chunk.isDynamicEntry) {
29556 manifestChunk.isDynamicEntry = true;
29557 }
29558 if (chunk.imports.length) {
29559 const internalImports = getInternalImports(chunk.imports);
29560 if (internalImports.length > 0) {
29561 manifestChunk.imports = internalImports;
29562 }
29563 }
29564 if (chunk.dynamicImports.length) {
29565 const internalImports = getInternalImports(chunk.dynamicImports);
29566 if (internalImports.length > 0) {
29567 manifestChunk.dynamicImports = internalImports;
29568 }
29569 }
29570 const cssFiles = chunkToEmittedCssFileMap.get(chunk);
29571 if (cssFiles) {
29572 manifestChunk.css = [...cssFiles];
29573 }
29574 const assets = chunkToEmittedAssetsMap.get(chunk);
29575 if (assets)
29576 [(manifestChunk.assets = [...assets])];
29577 return manifestChunk;
29578 }
29579 for (const file in bundle) {
29580 const chunk = bundle[file];
29581 if (chunk.type === 'chunk') {
29582 manifest[getChunkName(chunk)] = createChunk(chunk);
29583 }
29584 }
29585 outputCount++;
29586 const output = (_a = config.build.rollupOptions) === null || _a === void 0 ? void 0 : _a.output;
29587 const outputLength = Array.isArray(output) ? output.length : 1;
29588 if (outputCount >= outputLength) {
29589 this.emitFile({
29590 fileName: `manifest.json`,
29591 type: 'asset',
29592 source: JSON.stringify(manifest, null, 2)
29593 });
29594 }
29595 }
29596 };
29597}
29598
29599function walk$2(ast, { enter, leave }) {
29600 return visit(ast, null, enter, leave);
29601}
29602
29603let should_skip = false;
29604let should_remove = false;
29605let replacement = null;
29606const context = {
29607 skip: () => should_skip = true,
29608 remove: () => should_remove = true,
29609 replace: (node) => replacement = node
29610};
29611
29612function replace(parent, prop, index, node) {
29613 if (parent) {
29614 if (index !== null) {
29615 parent[prop][index] = node;
29616 } else {
29617 parent[prop] = node;
29618 }
29619 }
29620}
29621
29622function remove(parent, prop, index) {
29623 if (parent) {
29624 if (index !== null) {
29625 parent[prop].splice(index, 1);
29626 } else {
29627 delete parent[prop];
29628 }
29629 }
29630}
29631
29632function visit(
29633 node,
29634 parent,
29635 enter,
29636 leave,
29637 prop,
29638 index
29639) {
29640 if (node) {
29641 if (enter) {
29642 const _should_skip = should_skip;
29643 const _should_remove = should_remove;
29644 const _replacement = replacement;
29645 should_skip = false;
29646 should_remove = false;
29647 replacement = null;
29648
29649 enter.call(context, node, parent, prop, index);
29650
29651 if (replacement) {
29652 node = replacement;
29653 replace(parent, prop, index, node);
29654 }
29655
29656 if (should_remove) {
29657 remove(parent, prop, index);
29658 }
29659
29660 const skipped = should_skip;
29661 const removed = should_remove;
29662
29663 should_skip = _should_skip;
29664 should_remove = _should_remove;
29665 replacement = _replacement;
29666
29667 if (skipped) return node;
29668 if (removed) return null;
29669 }
29670
29671 for (const key in node) {
29672 const value = (node )[key];
29673
29674 if (typeof value !== 'object') {
29675 continue;
29676 }
29677
29678 else if (Array.isArray(value)) {
29679 for (let j = 0, k = 0; j < value.length; j += 1, k += 1) {
29680 if (value[j] !== null && typeof value[j].type === 'string') {
29681 if (!visit(value[j], node, enter, leave, key, k)) {
29682 // removed
29683 j--;
29684 }
29685 }
29686 }
29687 }
29688
29689 else if (value !== null && typeof value.type === 'string') {
29690 visit(value, node, enter, leave, key, null);
29691 }
29692 }
29693
29694 if (leave) {
29695 const _replacement = replacement;
29696 const _should_remove = should_remove;
29697 replacement = null;
29698 should_remove = false;
29699
29700 leave.call(context, node, parent, prop, index);
29701
29702 if (replacement) {
29703 node = replacement;
29704 replace(parent, prop, index, node);
29705 }
29706
29707 if (should_remove) {
29708 remove(parent, prop, index);
29709 }
29710
29711 const removed = should_remove;
29712
29713 replacement = _replacement;
29714 should_remove = _should_remove;
29715
29716 if (removed) return null;
29717 }
29718 }
29719
29720 return node;
29721}
29722
29723const extractors = {
29724 ArrayPattern(names, param) {
29725 for (const element of param.elements) {
29726 if (element)
29727 extractors[element.type](names, element);
29728 }
29729 },
29730 AssignmentPattern(names, param) {
29731 extractors[param.left.type](names, param.left);
29732 },
29733 Identifier(names, param) {
29734 names.push(param.name);
29735 },
29736 MemberExpression() { },
29737 ObjectPattern(names, param) {
29738 for (const prop of param.properties) {
29739 // @ts-ignore Typescript reports that this is not a valid type
29740 if (prop.type === 'RestElement') {
29741 extractors.RestElement(names, prop);
29742 }
29743 else {
29744 extractors[prop.value.type](names, prop.value);
29745 }
29746 }
29747 },
29748 RestElement(names, param) {
29749 extractors[param.argument.type](names, param.argument);
29750 }
29751};
29752const extractAssignedNames = function extractAssignedNames(param) {
29753 const names = [];
29754 extractors[param.type](names, param);
29755 return names;
29756};
29757
29758const blockDeclarations = {
29759 const: true,
29760 let: true
29761};
29762class Scope$1 {
29763 constructor(options = {}) {
29764 this.parent = options.parent;
29765 this.isBlockScope = !!options.block;
29766 this.declarations = Object.create(null);
29767 if (options.params) {
29768 options.params.forEach((param) => {
29769 extractAssignedNames(param).forEach((name) => {
29770 this.declarations[name] = true;
29771 });
29772 });
29773 }
29774 }
29775 addDeclaration(node, isBlockDeclaration, isVar) {
29776 if (!isBlockDeclaration && this.isBlockScope) {
29777 // it's a `var` or function node, and this
29778 // is a block scope, so we need to go up
29779 this.parent.addDeclaration(node, isBlockDeclaration, isVar);
29780 }
29781 else if (node.id) {
29782 extractAssignedNames(node.id).forEach((name) => {
29783 this.declarations[name] = true;
29784 });
29785 }
29786 }
29787 contains(name) {
29788 return this.declarations[name] || (this.parent ? this.parent.contains(name) : false);
29789 }
29790}
29791const attachScopes = function attachScopes(ast, propertyName = 'scope') {
29792 let scope = new Scope$1();
29793 walk$2(ast, {
29794 enter(n, parent) {
29795 const node = n;
29796 // function foo () {...}
29797 // class Foo {...}
29798 if (/(Function|Class)Declaration/.test(node.type)) {
29799 scope.addDeclaration(node, false, false);
29800 }
29801 // var foo = 1
29802 if (node.type === 'VariableDeclaration') {
29803 const { kind } = node;
29804 const isBlockDeclaration = blockDeclarations[kind];
29805 // don't add const/let declarations in the body of a for loop #113
29806 const parentType = parent ? parent.type : '';
29807 if (!(isBlockDeclaration && /ForOfStatement/.test(parentType))) {
29808 node.declarations.forEach((declaration) => {
29809 scope.addDeclaration(declaration, isBlockDeclaration, true);
29810 });
29811 }
29812 }
29813 let newScope;
29814 // create new function scope
29815 if (/Function/.test(node.type)) {
29816 const func = node;
29817 newScope = new Scope$1({
29818 parent: scope,
29819 block: false,
29820 params: func.params
29821 });
29822 // named function expressions - the name is considered
29823 // part of the function's scope
29824 if (func.type === 'FunctionExpression' && func.id) {
29825 newScope.addDeclaration(func, false, false);
29826 }
29827 }
29828 // create new block scope
29829 if (node.type === 'BlockStatement' && !/Function/.test(parent.type)) {
29830 newScope = new Scope$1({
29831 parent: scope,
29832 block: true
29833 });
29834 }
29835 // catch clause has its own block scope
29836 if (node.type === 'CatchClause') {
29837 newScope = new Scope$1({
29838 parent: scope,
29839 params: node.param ? [node.param] : [],
29840 block: true
29841 });
29842 }
29843 if (newScope) {
29844 Object.defineProperty(node, propertyName, {
29845 value: newScope,
29846 configurable: true
29847 });
29848 scope = newScope;
29849 }
29850 },
29851 leave(n) {
29852 const node = n;
29853 if (node[propertyName])
29854 scope = scope.parent;
29855 }
29856 });
29857 return scope;
29858};
29859
29860// Helper since Typescript can't detect readonly arrays with Array.isArray
29861function isArray$2(arg) {
29862 return Array.isArray(arg);
29863}
29864function ensureArray(thing) {
29865 if (isArray$2(thing))
29866 return thing;
29867 if (thing == null)
29868 return [];
29869 return [thing];
29870}
29871
29872function getMatcherString(id, resolutionBase) {
29873 if (resolutionBase === false) {
29874 return id;
29875 }
29876 // resolve('') is valid and will default to process.cwd()
29877 const basePath = path$A.resolve(resolutionBase || '')
29878 .split(path$A.sep)
29879 .join('/')
29880 // escape all possible (posix + win) path characters that might interfere with regex
29881 .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
29882 // Note that we use posix.join because:
29883 // 1. the basePath has been normalized to use /
29884 // 2. the incoming glob (id) matcher, also uses /
29885 // otherwise Node will force backslash (\) on windows
29886 return path$A.posix.join(basePath, id);
29887}
29888const createFilter = function createFilter(include, exclude, options) {
29889 const resolutionBase = options && options.resolve;
29890 const getMatcher = (id) => id instanceof RegExp
29891 ? id
29892 : {
29893 test: (what) => {
29894 // this refactor is a tad overly verbose but makes for easy debugging
29895 const pattern = getMatcherString(id, resolutionBase);
29896 const fn = picomatch$4(pattern, { dot: true });
29897 const result = fn(what);
29898 return result;
29899 }
29900 };
29901 const includeMatchers = ensureArray(include).map(getMatcher);
29902 const excludeMatchers = ensureArray(exclude).map(getMatcher);
29903 return function result(id) {
29904 if (typeof id !== 'string')
29905 return false;
29906 if (/\0/.test(id))
29907 return false;
29908 const pathId = id.split(path$A.sep).join('/');
29909 for (let i = 0; i < excludeMatchers.length; ++i) {
29910 const matcher = excludeMatchers[i];
29911 if (matcher.test(pathId))
29912 return false;
29913 }
29914 for (let i = 0; i < includeMatchers.length; ++i) {
29915 const matcher = includeMatchers[i];
29916 if (matcher.test(pathId))
29917 return true;
29918 }
29919 return !includeMatchers.length;
29920 };
29921};
29922
29923const reservedWords$1 = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public';
29924const builtins = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl';
29925const forbiddenIdentifiers = new Set(`${reservedWords$1} ${builtins}`.split(' '));
29926forbiddenIdentifiers.add('');
29927const makeLegalIdentifier = function makeLegalIdentifier(str) {
29928 let identifier = str
29929 .replace(/-(\w)/g, (_, letter) => letter.toUpperCase())
29930 .replace(/[^$_a-zA-Z0-9]/g, '_');
29931 if (/\d/.test(identifier[0]) || forbiddenIdentifiers.has(identifier)) {
29932 identifier = `_${identifier}`;
29933 }
29934 return identifier || '_';
29935};
29936
29937var path$n = path__default;
29938
29939var commondir = function (basedir, relfiles) {
29940 if (relfiles) {
29941 var files = relfiles.map(function (r) {
29942 return path$n.resolve(basedir, r);
29943 });
29944 }
29945 else {
29946 var files = basedir;
29947 }
29948
29949 var res = files.slice(1).reduce(function (ps, file) {
29950 if (!file.match(/^([A-Za-z]:)?\/|\\/)) {
29951 throw new Error('relative path without a basedir');
29952 }
29953
29954 var xs = file.split(/\/+|\\+/);
29955 for (
29956 var i = 0;
29957 ps[i] === xs[i] && i < Math.min(ps.length, xs.length);
29958 i++
29959 );
29960 return ps.slice(0, i);
29961 }, files[0].split(/\/+|\\+/));
29962
29963 // Windows correctly handles paths with forward-slashes
29964 return res.length > 1 ? res.join('/') : '/'
29965};
29966
29967var old$1 = {};
29968
29969// Copyright Joyent, Inc. and other Node contributors.
29970//
29971// Permission is hereby granted, free of charge, to any person obtaining a
29972// copy of this software and associated documentation files (the
29973// "Software"), to deal in the Software without restriction, including
29974// without limitation the rights to use, copy, modify, merge, publish,
29975// distribute, sublicense, and/or sell copies of the Software, and to permit
29976// persons to whom the Software is furnished to do so, subject to the
29977// following conditions:
29978//
29979// The above copyright notice and this permission notice shall be included
29980// in all copies or substantial portions of the Software.
29981//
29982// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
29983// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
29984// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
29985// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
29986// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
29987// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
29988// USE OR OTHER DEALINGS IN THE SOFTWARE.
29989
29990var pathModule = path__default;
29991var isWindows$3 = process.platform === 'win32';
29992var fs$k = fs__default;
29993
29994// JavaScript implementation of realpath, ported from node pre-v6
29995
29996var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
29997
29998function rethrow() {
29999 // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and
30000 // is fairly slow to generate.
30001 var callback;
30002 if (DEBUG) {
30003 var backtrace = new Error;
30004 callback = debugCallback;
30005 } else
30006 callback = missingCallback;
30007
30008 return callback;
30009
30010 function debugCallback(err) {
30011 if (err) {
30012 backtrace.message = err.message;
30013 err = backtrace;
30014 missingCallback(err);
30015 }
30016 }
30017
30018 function missingCallback(err) {
30019 if (err) {
30020 if (process.throwDeprecation)
30021 throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs
30022 else if (!process.noDeprecation) {
30023 var msg = 'fs: missing callback ' + (err.stack || err.message);
30024 if (process.traceDeprecation)
30025 console.trace(msg);
30026 else
30027 console.error(msg);
30028 }
30029 }
30030 }
30031}
30032
30033function maybeCallback(cb) {
30034 return typeof cb === 'function' ? cb : rethrow();
30035}
30036
30037// Regexp that finds the next partion of a (partial) path
30038// result is [base_with_slash, base], e.g. ['somedir/', 'somedir']
30039if (isWindows$3) {
30040 var nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
30041} else {
30042 var nextPartRe = /(.*?)(?:[\/]+|$)/g;
30043}
30044
30045// Regex to find the device root, including trailing slash. E.g. 'c:\\'.
30046if (isWindows$3) {
30047 var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
30048} else {
30049 var splitRootRe = /^[\/]*/;
30050}
30051
30052old$1.realpathSync = function realpathSync(p, cache) {
30053 // make p is absolute
30054 p = pathModule.resolve(p);
30055
30056 if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
30057 return cache[p];
30058 }
30059
30060 var original = p,
30061 seenLinks = {},
30062 knownHard = {};
30063
30064 // current character position in p
30065 var pos;
30066 // the partial path so far, including a trailing slash if any
30067 var current;
30068 // the partial path without a trailing slash (except when pointing at a root)
30069 var base;
30070 // the partial path scanned in the previous round, with slash
30071 var previous;
30072
30073 start();
30074
30075 function start() {
30076 // Skip over roots
30077 var m = splitRootRe.exec(p);
30078 pos = m[0].length;
30079 current = m[0];
30080 base = m[0];
30081 previous = '';
30082
30083 // On windows, check that the root exists. On unix there is no need.
30084 if (isWindows$3 && !knownHard[base]) {
30085 fs$k.lstatSync(base);
30086 knownHard[base] = true;
30087 }
30088 }
30089
30090 // walk down the path, swapping out linked pathparts for their real
30091 // values
30092 // NB: p.length changes.
30093 while (pos < p.length) {
30094 // find the next part
30095 nextPartRe.lastIndex = pos;
30096 var result = nextPartRe.exec(p);
30097 previous = current;
30098 current += result[0];
30099 base = previous + result[1];
30100 pos = nextPartRe.lastIndex;
30101
30102 // continue if not a symlink
30103 if (knownHard[base] || (cache && cache[base] === base)) {
30104 continue;
30105 }
30106
30107 var resolvedLink;
30108 if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
30109 // some known symbolic link. no need to stat again.
30110 resolvedLink = cache[base];
30111 } else {
30112 var stat = fs$k.lstatSync(base);
30113 if (!stat.isSymbolicLink()) {
30114 knownHard[base] = true;
30115 if (cache) cache[base] = base;
30116 continue;
30117 }
30118
30119 // read the link if it wasn't read before
30120 // dev/ino always return 0 on windows, so skip the check.
30121 var linkTarget = null;
30122 if (!isWindows$3) {
30123 var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
30124 if (seenLinks.hasOwnProperty(id)) {
30125 linkTarget = seenLinks[id];
30126 }
30127 }
30128 if (linkTarget === null) {
30129 fs$k.statSync(base);
30130 linkTarget = fs$k.readlinkSync(base);
30131 }
30132 resolvedLink = pathModule.resolve(previous, linkTarget);
30133 // track this, if given a cache.
30134 if (cache) cache[base] = resolvedLink;
30135 if (!isWindows$3) seenLinks[id] = linkTarget;
30136 }
30137
30138 // resolve the link, then start over
30139 p = pathModule.resolve(resolvedLink, p.slice(pos));
30140 start();
30141 }
30142
30143 if (cache) cache[original] = p;
30144
30145 return p;
30146};
30147
30148
30149old$1.realpath = function realpath(p, cache, cb) {
30150 if (typeof cb !== 'function') {
30151 cb = maybeCallback(cache);
30152 cache = null;
30153 }
30154
30155 // make p is absolute
30156 p = pathModule.resolve(p);
30157
30158 if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
30159 return process.nextTick(cb.bind(null, null, cache[p]));
30160 }
30161
30162 var original = p,
30163 seenLinks = {},
30164 knownHard = {};
30165
30166 // current character position in p
30167 var pos;
30168 // the partial path so far, including a trailing slash if any
30169 var current;
30170 // the partial path without a trailing slash (except when pointing at a root)
30171 var base;
30172 // the partial path scanned in the previous round, with slash
30173 var previous;
30174
30175 start();
30176
30177 function start() {
30178 // Skip over roots
30179 var m = splitRootRe.exec(p);
30180 pos = m[0].length;
30181 current = m[0];
30182 base = m[0];
30183 previous = '';
30184
30185 // On windows, check that the root exists. On unix there is no need.
30186 if (isWindows$3 && !knownHard[base]) {
30187 fs$k.lstat(base, function(err) {
30188 if (err) return cb(err);
30189 knownHard[base] = true;
30190 LOOP();
30191 });
30192 } else {
30193 process.nextTick(LOOP);
30194 }
30195 }
30196
30197 // walk down the path, swapping out linked pathparts for their real
30198 // values
30199 function LOOP() {
30200 // stop if scanned past end of path
30201 if (pos >= p.length) {
30202 if (cache) cache[original] = p;
30203 return cb(null, p);
30204 }
30205
30206 // find the next part
30207 nextPartRe.lastIndex = pos;
30208 var result = nextPartRe.exec(p);
30209 previous = current;
30210 current += result[0];
30211 base = previous + result[1];
30212 pos = nextPartRe.lastIndex;
30213
30214 // continue if not a symlink
30215 if (knownHard[base] || (cache && cache[base] === base)) {
30216 return process.nextTick(LOOP);
30217 }
30218
30219 if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
30220 // known symbolic link. no need to stat again.
30221 return gotResolvedLink(cache[base]);
30222 }
30223
30224 return fs$k.lstat(base, gotStat);
30225 }
30226
30227 function gotStat(err, stat) {
30228 if (err) return cb(err);
30229
30230 // if not a symlink, skip to the next path part
30231 if (!stat.isSymbolicLink()) {
30232 knownHard[base] = true;
30233 if (cache) cache[base] = base;
30234 return process.nextTick(LOOP);
30235 }
30236
30237 // stat & read the link if not read before
30238 // call gotTarget as soon as the link target is known
30239 // dev/ino always return 0 on windows, so skip the check.
30240 if (!isWindows$3) {
30241 var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
30242 if (seenLinks.hasOwnProperty(id)) {
30243 return gotTarget(null, seenLinks[id], base);
30244 }
30245 }
30246 fs$k.stat(base, function(err) {
30247 if (err) return cb(err);
30248
30249 fs$k.readlink(base, function(err, target) {
30250 if (!isWindows$3) seenLinks[id] = target;
30251 gotTarget(err, target);
30252 });
30253 });
30254 }
30255
30256 function gotTarget(err, target, base) {
30257 if (err) return cb(err);
30258
30259 var resolvedLink = pathModule.resolve(previous, target);
30260 if (cache) cache[base] = resolvedLink;
30261 gotResolvedLink(resolvedLink);
30262 }
30263
30264 function gotResolvedLink(resolvedLink) {
30265 // resolve the link, then start over
30266 p = pathModule.resolve(resolvedLink, p.slice(pos));
30267 start();
30268 }
30269};
30270
30271var fs_realpath = realpath$2;
30272realpath$2.realpath = realpath$2;
30273realpath$2.sync = realpathSync;
30274realpath$2.realpathSync = realpathSync;
30275realpath$2.monkeypatch = monkeypatch;
30276realpath$2.unmonkeypatch = unmonkeypatch;
30277
30278var fs$j = fs__default;
30279var origRealpath = fs$j.realpath;
30280var origRealpathSync = fs$j.realpathSync;
30281
30282var version$1 = process.version;
30283var ok = /^v[0-5]\./.test(version$1);
30284var old = old$1;
30285
30286function newError (er) {
30287 return er && er.syscall === 'realpath' && (
30288 er.code === 'ELOOP' ||
30289 er.code === 'ENOMEM' ||
30290 er.code === 'ENAMETOOLONG'
30291 )
30292}
30293
30294function realpath$2 (p, cache, cb) {
30295 if (ok) {
30296 return origRealpath(p, cache, cb)
30297 }
30298
30299 if (typeof cache === 'function') {
30300 cb = cache;
30301 cache = null;
30302 }
30303 origRealpath(p, cache, function (er, result) {
30304 if (newError(er)) {
30305 old.realpath(p, cache, cb);
30306 } else {
30307 cb(er, result);
30308 }
30309 });
30310}
30311
30312function realpathSync (p, cache) {
30313 if (ok) {
30314 return origRealpathSync(p, cache)
30315 }
30316
30317 try {
30318 return origRealpathSync(p, cache)
30319 } catch (er) {
30320 if (newError(er)) {
30321 return old.realpathSync(p, cache)
30322 } else {
30323 throw er
30324 }
30325 }
30326}
30327
30328function monkeypatch () {
30329 fs$j.realpath = realpath$2;
30330 fs$j.realpathSync = realpathSync;
30331}
30332
30333function unmonkeypatch () {
30334 fs$j.realpath = origRealpath;
30335 fs$j.realpathSync = origRealpathSync;
30336}
30337
30338var concatMap$1 = function (xs, fn) {
30339 var res = [];
30340 for (var i = 0; i < xs.length; i++) {
30341 var x = fn(xs[i], i);
30342 if (isArray$1(x)) res.push.apply(res, x);
30343 else res.push(x);
30344 }
30345 return res;
30346};
30347
30348var isArray$1 = Array.isArray || function (xs) {
30349 return Object.prototype.toString.call(xs) === '[object Array]';
30350};
30351
30352var balancedMatch = balanced$1;
30353function balanced$1(a, b, str) {
30354 if (a instanceof RegExp) a = maybeMatch(a, str);
30355 if (b instanceof RegExp) b = maybeMatch(b, str);
30356
30357 var r = range(a, b, str);
30358
30359 return r && {
30360 start: r[0],
30361 end: r[1],
30362 pre: str.slice(0, r[0]),
30363 body: str.slice(r[0] + a.length, r[1]),
30364 post: str.slice(r[1] + b.length)
30365 };
30366}
30367
30368function maybeMatch(reg, str) {
30369 var m = str.match(reg);
30370 return m ? m[0] : null;
30371}
30372
30373balanced$1.range = range;
30374function range(a, b, str) {
30375 var begs, beg, left, right, result;
30376 var ai = str.indexOf(a);
30377 var bi = str.indexOf(b, ai + 1);
30378 var i = ai;
30379
30380 if (ai >= 0 && bi > 0) {
30381 if(a===b) {
30382 return [ai, bi];
30383 }
30384 begs = [];
30385 left = str.length;
30386
30387 while (i >= 0 && !result) {
30388 if (i == ai) {
30389 begs.push(i);
30390 ai = str.indexOf(a, i + 1);
30391 } else if (begs.length == 1) {
30392 result = [ begs.pop(), bi ];
30393 } else {
30394 beg = begs.pop();
30395 if (beg < left) {
30396 left = beg;
30397 right = bi;
30398 }
30399
30400 bi = str.indexOf(b, i + 1);
30401 }
30402
30403 i = ai < bi && ai >= 0 ? ai : bi;
30404 }
30405
30406 if (begs.length) {
30407 result = [ left, right ];
30408 }
30409 }
30410
30411 return result;
30412}
30413
30414var concatMap = concatMap$1;
30415var balanced = balancedMatch;
30416
30417var braceExpansion = expandTop;
30418
30419var escSlash = '\0SLASH'+Math.random()+'\0';
30420var escOpen = '\0OPEN'+Math.random()+'\0';
30421var escClose = '\0CLOSE'+Math.random()+'\0';
30422var escComma = '\0COMMA'+Math.random()+'\0';
30423var escPeriod = '\0PERIOD'+Math.random()+'\0';
30424
30425function numeric(str) {
30426 return parseInt(str, 10) == str
30427 ? parseInt(str, 10)
30428 : str.charCodeAt(0);
30429}
30430
30431function escapeBraces(str) {
30432 return str.split('\\\\').join(escSlash)
30433 .split('\\{').join(escOpen)
30434 .split('\\}').join(escClose)
30435 .split('\\,').join(escComma)
30436 .split('\\.').join(escPeriod);
30437}
30438
30439function unescapeBraces(str) {
30440 return str.split(escSlash).join('\\')
30441 .split(escOpen).join('{')
30442 .split(escClose).join('}')
30443 .split(escComma).join(',')
30444 .split(escPeriod).join('.');
30445}
30446
30447
30448// Basically just str.split(","), but handling cases
30449// where we have nested braced sections, which should be
30450// treated as individual members, like {a,{b,c},d}
30451function parseCommaParts(str) {
30452 if (!str)
30453 return [''];
30454
30455 var parts = [];
30456 var m = balanced('{', '}', str);
30457
30458 if (!m)
30459 return str.split(',');
30460
30461 var pre = m.pre;
30462 var body = m.body;
30463 var post = m.post;
30464 var p = pre.split(',');
30465
30466 p[p.length-1] += '{' + body + '}';
30467 var postParts = parseCommaParts(post);
30468 if (post.length) {
30469 p[p.length-1] += postParts.shift();
30470 p.push.apply(p, postParts);
30471 }
30472
30473 parts.push.apply(parts, p);
30474
30475 return parts;
30476}
30477
30478function expandTop(str) {
30479 if (!str)
30480 return [];
30481
30482 // I don't know why Bash 4.3 does this, but it does.
30483 // Anything starting with {} will have the first two bytes preserved
30484 // but *only* at the top level, so {},a}b will not expand to anything,
30485 // but a{},b}c will be expanded to [a}c,abc].
30486 // One could argue that this is a bug in Bash, but since the goal of
30487 // this module is to match Bash's rules, we escape a leading {}
30488 if (str.substr(0, 2) === '{}') {
30489 str = '\\{\\}' + str.substr(2);
30490 }
30491
30492 return expand$1(escapeBraces(str), true).map(unescapeBraces);
30493}
30494
30495function embrace(str) {
30496 return '{' + str + '}';
30497}
30498function isPadded(el) {
30499 return /^-?0\d/.test(el);
30500}
30501
30502function lte(i, y) {
30503 return i <= y;
30504}
30505function gte(i, y) {
30506 return i >= y;
30507}
30508
30509function expand$1(str, isTop) {
30510 var expansions = [];
30511
30512 var m = balanced('{', '}', str);
30513 if (!m || /\$$/.test(m.pre)) return [str];
30514
30515 var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
30516 var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
30517 var isSequence = isNumericSequence || isAlphaSequence;
30518 var isOptions = m.body.indexOf(',') >= 0;
30519 if (!isSequence && !isOptions) {
30520 // {a},b}
30521 if (m.post.match(/,.*\}/)) {
30522 str = m.pre + '{' + m.body + escClose + m.post;
30523 return expand$1(str);
30524 }
30525 return [str];
30526 }
30527
30528 var n;
30529 if (isSequence) {
30530 n = m.body.split(/\.\./);
30531 } else {
30532 n = parseCommaParts(m.body);
30533 if (n.length === 1) {
30534 // x{{a,b}}y ==> x{a}y x{b}y
30535 n = expand$1(n[0], false).map(embrace);
30536 if (n.length === 1) {
30537 var post = m.post.length
30538 ? expand$1(m.post, false)
30539 : [''];
30540 return post.map(function(p) {
30541 return m.pre + n[0] + p;
30542 });
30543 }
30544 }
30545 }
30546
30547 // at this point, n is the parts, and we know it's not a comma set
30548 // with a single entry.
30549
30550 // no need to expand pre, since it is guaranteed to be free of brace-sets
30551 var pre = m.pre;
30552 var post = m.post.length
30553 ? expand$1(m.post, false)
30554 : [''];
30555
30556 var N;
30557
30558 if (isSequence) {
30559 var x = numeric(n[0]);
30560 var y = numeric(n[1]);
30561 var width = Math.max(n[0].length, n[1].length);
30562 var incr = n.length == 3
30563 ? Math.abs(numeric(n[2]))
30564 : 1;
30565 var test = lte;
30566 var reverse = y < x;
30567 if (reverse) {
30568 incr *= -1;
30569 test = gte;
30570 }
30571 var pad = n.some(isPadded);
30572
30573 N = [];
30574
30575 for (var i = x; test(i, y); i += incr) {
30576 var c;
30577 if (isAlphaSequence) {
30578 c = String.fromCharCode(i);
30579 if (c === '\\')
30580 c = '';
30581 } else {
30582 c = String(i);
30583 if (pad) {
30584 var need = width - c.length;
30585 if (need > 0) {
30586 var z = new Array(need + 1).join('0');
30587 if (i < 0)
30588 c = '-' + z + c.slice(1);
30589 else
30590 c = z + c;
30591 }
30592 }
30593 }
30594 N.push(c);
30595 }
30596 } else {
30597 N = concatMap(n, function(el) { return expand$1(el, false) });
30598 }
30599
30600 for (var j = 0; j < N.length; j++) {
30601 for (var k = 0; k < post.length; k++) {
30602 var expansion = pre + N[j] + post[k];
30603 if (!isTop || isSequence || expansion)
30604 expansions.push(expansion);
30605 }
30606 }
30607
30608 return expansions;
30609}
30610
30611var minimatch_1 = minimatch$3;
30612minimatch$3.Minimatch = Minimatch$1;
30613
30614var path$m = { sep: '/' };
30615try {
30616 path$m = path__default;
30617} catch (er) {}
30618
30619var GLOBSTAR$2 = minimatch$3.GLOBSTAR = Minimatch$1.GLOBSTAR = {};
30620var expand = braceExpansion;
30621
30622var plTypes = {
30623 '!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
30624 '?': { open: '(?:', close: ')?' },
30625 '+': { open: '(?:', close: ')+' },
30626 '*': { open: '(?:', close: ')*' },
30627 '@': { open: '(?:', close: ')' }
30628};
30629
30630// any single thing other than /
30631// don't need to escape / when using new RegExp()
30632var qmark = '[^/]';
30633
30634// * => any number of characters
30635var star = qmark + '*?';
30636
30637// ** when dots are allowed. Anything goes, except .. and .
30638// not (^ or / followed by one or two dots followed by $ or /),
30639// followed by anything, any number of times.
30640var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?';
30641
30642// not a ^ or / followed by a dot,
30643// followed by anything, any number of times.
30644var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?';
30645
30646// characters that need to be escaped in RegExp.
30647var reSpecials = charSet('().*{}+?[]^$\\!');
30648
30649// "abc" -> { a:true, b:true, c:true }
30650function charSet (s) {
30651 return s.split('').reduce(function (set, c) {
30652 set[c] = true;
30653 return set
30654 }, {})
30655}
30656
30657// normalizes slashes.
30658var slashSplit = /\/+/;
30659
30660minimatch$3.filter = filter;
30661function filter (pattern, options) {
30662 options = options || {};
30663 return function (p, i, list) {
30664 return minimatch$3(p, pattern, options)
30665 }
30666}
30667
30668function ext (a, b) {
30669 a = a || {};
30670 b = b || {};
30671 var t = {};
30672 Object.keys(b).forEach(function (k) {
30673 t[k] = b[k];
30674 });
30675 Object.keys(a).forEach(function (k) {
30676 t[k] = a[k];
30677 });
30678 return t
30679}
30680
30681minimatch$3.defaults = function (def) {
30682 if (!def || !Object.keys(def).length) return minimatch$3
30683
30684 var orig = minimatch$3;
30685
30686 var m = function minimatch (p, pattern, options) {
30687 return orig.minimatch(p, pattern, ext(def, options))
30688 };
30689
30690 m.Minimatch = function Minimatch (pattern, options) {
30691 return new orig.Minimatch(pattern, ext(def, options))
30692 };
30693
30694 return m
30695};
30696
30697Minimatch$1.defaults = function (def) {
30698 if (!def || !Object.keys(def).length) return Minimatch$1
30699 return minimatch$3.defaults(def).Minimatch
30700};
30701
30702function minimatch$3 (p, pattern, options) {
30703 if (typeof pattern !== 'string') {
30704 throw new TypeError('glob pattern string required')
30705 }
30706
30707 if (!options) options = {};
30708
30709 // shortcut: comments match nothing.
30710 if (!options.nocomment && pattern.charAt(0) === '#') {
30711 return false
30712 }
30713
30714 // "" only matches ""
30715 if (pattern.trim() === '') return p === ''
30716
30717 return new Minimatch$1(pattern, options).match(p)
30718}
30719
30720function Minimatch$1 (pattern, options) {
30721 if (!(this instanceof Minimatch$1)) {
30722 return new Minimatch$1(pattern, options)
30723 }
30724
30725 if (typeof pattern !== 'string') {
30726 throw new TypeError('glob pattern string required')
30727 }
30728
30729 if (!options) options = {};
30730 pattern = pattern.trim();
30731
30732 // windows support: need to use /, not \
30733 if (path$m.sep !== '/') {
30734 pattern = pattern.split(path$m.sep).join('/');
30735 }
30736
30737 this.options = options;
30738 this.set = [];
30739 this.pattern = pattern;
30740 this.regexp = null;
30741 this.negate = false;
30742 this.comment = false;
30743 this.empty = false;
30744
30745 // make the set of regexps etc.
30746 this.make();
30747}
30748
30749Minimatch$1.prototype.debug = function () {};
30750
30751Minimatch$1.prototype.make = make;
30752function make () {
30753 // don't do it more than once.
30754 if (this._made) return
30755
30756 var pattern = this.pattern;
30757 var options = this.options;
30758
30759 // empty patterns and comments match nothing.
30760 if (!options.nocomment && pattern.charAt(0) === '#') {
30761 this.comment = true;
30762 return
30763 }
30764 if (!pattern) {
30765 this.empty = true;
30766 return
30767 }
30768
30769 // step 1: figure out negation, etc.
30770 this.parseNegate();
30771
30772 // step 2: expand braces
30773 var set = this.globSet = this.braceExpand();
30774
30775 if (options.debug) this.debug = console.error;
30776
30777 this.debug(this.pattern, set);
30778
30779 // step 3: now we have a set, so turn each one into a series of path-portion
30780 // matching patterns.
30781 // These will be regexps, except in the case of "**", which is
30782 // set to the GLOBSTAR object for globstar behavior,
30783 // and will not contain any / characters
30784 set = this.globParts = set.map(function (s) {
30785 return s.split(slashSplit)
30786 });
30787
30788 this.debug(this.pattern, set);
30789
30790 // glob --> regexps
30791 set = set.map(function (s, si, set) {
30792 return s.map(this.parse, this)
30793 }, this);
30794
30795 this.debug(this.pattern, set);
30796
30797 // filter out everything that didn't compile properly.
30798 set = set.filter(function (s) {
30799 return s.indexOf(false) === -1
30800 });
30801
30802 this.debug(this.pattern, set);
30803
30804 this.set = set;
30805}
30806
30807Minimatch$1.prototype.parseNegate = parseNegate;
30808function parseNegate () {
30809 var pattern = this.pattern;
30810 var negate = false;
30811 var options = this.options;
30812 var negateOffset = 0;
30813
30814 if (options.nonegate) return
30815
30816 for (var i = 0, l = pattern.length
30817 ; i < l && pattern.charAt(i) === '!'
30818 ; i++) {
30819 negate = !negate;
30820 negateOffset++;
30821 }
30822
30823 if (negateOffset) this.pattern = pattern.substr(negateOffset);
30824 this.negate = negate;
30825}
30826
30827// Brace expansion:
30828// a{b,c}d -> abd acd
30829// a{b,}c -> abc ac
30830// a{0..3}d -> a0d a1d a2d a3d
30831// a{b,c{d,e}f}g -> abg acdfg acefg
30832// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
30833//
30834// Invalid sets are not expanded.
30835// a{2..}b -> a{2..}b
30836// a{b}c -> a{b}c
30837minimatch$3.braceExpand = function (pattern, options) {
30838 return braceExpand(pattern, options)
30839};
30840
30841Minimatch$1.prototype.braceExpand = braceExpand;
30842
30843function braceExpand (pattern, options) {
30844 if (!options) {
30845 if (this instanceof Minimatch$1) {
30846 options = this.options;
30847 } else {
30848 options = {};
30849 }
30850 }
30851
30852 pattern = typeof pattern === 'undefined'
30853 ? this.pattern : pattern;
30854
30855 if (typeof pattern === 'undefined') {
30856 throw new TypeError('undefined pattern')
30857 }
30858
30859 if (options.nobrace ||
30860 !pattern.match(/\{.*\}/)) {
30861 // shortcut. no need to expand.
30862 return [pattern]
30863 }
30864
30865 return expand(pattern)
30866}
30867
30868// parse a component of the expanded set.
30869// At this point, no pattern may contain "/" in it
30870// so we're going to return a 2d array, where each entry is the full
30871// pattern, split on '/', and then turned into a regular expression.
30872// A regexp is made at the end which joins each array with an
30873// escaped /, and another full one which joins each regexp with |.
30874//
30875// Following the lead of Bash 4.1, note that "**" only has special meaning
30876// when it is the *only* thing in a path portion. Otherwise, any series
30877// of * is equivalent to a single *. Globstar behavior is enabled by
30878// default, and can be disabled by setting options.noglobstar.
30879Minimatch$1.prototype.parse = parse$d;
30880var SUBPARSE = {};
30881function parse$d (pattern, isSub) {
30882 if (pattern.length > 1024 * 64) {
30883 throw new TypeError('pattern is too long')
30884 }
30885
30886 var options = this.options;
30887
30888 // shortcuts
30889 if (!options.noglobstar && pattern === '**') return GLOBSTAR$2
30890 if (pattern === '') return ''
30891
30892 var re = '';
30893 var hasMagic = !!options.nocase;
30894 var escaping = false;
30895 // ? => one single character
30896 var patternListStack = [];
30897 var negativeLists = [];
30898 var stateChar;
30899 var inClass = false;
30900 var reClassStart = -1;
30901 var classStart = -1;
30902 // . and .. never match anything that doesn't start with .,
30903 // even when options.dot is set.
30904 var patternStart = pattern.charAt(0) === '.' ? '' // anything
30905 // not (start or / followed by . or .. followed by / or end)
30906 : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
30907 : '(?!\\.)';
30908 var self = this;
30909
30910 function clearStateChar () {
30911 if (stateChar) {
30912 // we had some state-tracking character
30913 // that wasn't consumed by this pass.
30914 switch (stateChar) {
30915 case '*':
30916 re += star;
30917 hasMagic = true;
30918 break
30919 case '?':
30920 re += qmark;
30921 hasMagic = true;
30922 break
30923 default:
30924 re += '\\' + stateChar;
30925 break
30926 }
30927 self.debug('clearStateChar %j %j', stateChar, re);
30928 stateChar = false;
30929 }
30930 }
30931
30932 for (var i = 0, len = pattern.length, c
30933 ; (i < len) && (c = pattern.charAt(i))
30934 ; i++) {
30935 this.debug('%s\t%s %s %j', pattern, i, re, c);
30936
30937 // skip over any that are escaped.
30938 if (escaping && reSpecials[c]) {
30939 re += '\\' + c;
30940 escaping = false;
30941 continue
30942 }
30943
30944 switch (c) {
30945 case '/':
30946 // completely not allowed, even escaped.
30947 // Should already be path-split by now.
30948 return false
30949
30950 case '\\':
30951 clearStateChar();
30952 escaping = true;
30953 continue
30954
30955 // the various stateChar values
30956 // for the "extglob" stuff.
30957 case '?':
30958 case '*':
30959 case '+':
30960 case '@':
30961 case '!':
30962 this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c);
30963
30964 // all of those are literals inside a class, except that
30965 // the glob [!a] means [^a] in regexp
30966 if (inClass) {
30967 this.debug(' in class');
30968 if (c === '!' && i === classStart + 1) c = '^';
30969 re += c;
30970 continue
30971 }
30972
30973 // if we already have a stateChar, then it means
30974 // that there was something like ** or +? in there.
30975 // Handle the stateChar, then proceed with this one.
30976 self.debug('call clearStateChar %j', stateChar);
30977 clearStateChar();
30978 stateChar = c;
30979 // if extglob is disabled, then +(asdf|foo) isn't a thing.
30980 // just clear the statechar *now*, rather than even diving into
30981 // the patternList stuff.
30982 if (options.noext) clearStateChar();
30983 continue
30984
30985 case '(':
30986 if (inClass) {
30987 re += '(';
30988 continue
30989 }
30990
30991 if (!stateChar) {
30992 re += '\\(';
30993 continue
30994 }
30995
30996 patternListStack.push({
30997 type: stateChar,
30998 start: i - 1,
30999 reStart: re.length,
31000 open: plTypes[stateChar].open,
31001 close: plTypes[stateChar].close
31002 });
31003 // negation is (?:(?!js)[^/]*)
31004 re += stateChar === '!' ? '(?:(?!(?:' : '(?:';
31005 this.debug('plType %j %j', stateChar, re);
31006 stateChar = false;
31007 continue
31008
31009 case ')':
31010 if (inClass || !patternListStack.length) {
31011 re += '\\)';
31012 continue
31013 }
31014
31015 clearStateChar();
31016 hasMagic = true;
31017 var pl = patternListStack.pop();
31018 // negation is (?:(?!js)[^/]*)
31019 // The others are (?:<pattern>)<type>
31020 re += pl.close;
31021 if (pl.type === '!') {
31022 negativeLists.push(pl);
31023 }
31024 pl.reEnd = re.length;
31025 continue
31026
31027 case '|':
31028 if (inClass || !patternListStack.length || escaping) {
31029 re += '\\|';
31030 escaping = false;
31031 continue
31032 }
31033
31034 clearStateChar();
31035 re += '|';
31036 continue
31037
31038 // these are mostly the same in regexp and glob
31039 case '[':
31040 // swallow any state-tracking char before the [
31041 clearStateChar();
31042
31043 if (inClass) {
31044 re += '\\' + c;
31045 continue
31046 }
31047
31048 inClass = true;
31049 classStart = i;
31050 reClassStart = re.length;
31051 re += c;
31052 continue
31053
31054 case ']':
31055 // a right bracket shall lose its special
31056 // meaning and represent itself in
31057 // a bracket expression if it occurs
31058 // first in the list. -- POSIX.2 2.8.3.2
31059 if (i === classStart + 1 || !inClass) {
31060 re += '\\' + c;
31061 escaping = false;
31062 continue
31063 }
31064
31065 // handle the case where we left a class open.
31066 // "[z-a]" is valid, equivalent to "\[z-a\]"
31067 if (inClass) {
31068 // split where the last [ was, make sure we don't have
31069 // an invalid re. if so, re-walk the contents of the
31070 // would-be class to re-translate any characters that
31071 // were passed through as-is
31072 // TODO: It would probably be faster to determine this
31073 // without a try/catch and a new RegExp, but it's tricky
31074 // to do safely. For now, this is safe and works.
31075 var cs = pattern.substring(classStart + 1, i);
31076 try {
31077 } catch (er) {
31078 // not a valid class!
31079 var sp = this.parse(cs, SUBPARSE);
31080 re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]';
31081 hasMagic = hasMagic || sp[1];
31082 inClass = false;
31083 continue
31084 }
31085 }
31086
31087 // finish up the class.
31088 hasMagic = true;
31089 inClass = false;
31090 re += c;
31091 continue
31092
31093 default:
31094 // swallow any state char that wasn't consumed
31095 clearStateChar();
31096
31097 if (escaping) {
31098 // no need
31099 escaping = false;
31100 } else if (reSpecials[c]
31101 && !(c === '^' && inClass)) {
31102 re += '\\';
31103 }
31104
31105 re += c;
31106
31107 } // switch
31108 } // for
31109
31110 // handle the case where we left a class open.
31111 // "[abc" is valid, equivalent to "\[abc"
31112 if (inClass) {
31113 // split where the last [ was, and escape it
31114 // this is a huge pita. We now have to re-walk
31115 // the contents of the would-be class to re-translate
31116 // any characters that were passed through as-is
31117 cs = pattern.substr(classStart + 1);
31118 sp = this.parse(cs, SUBPARSE);
31119 re = re.substr(0, reClassStart) + '\\[' + sp[0];
31120 hasMagic = hasMagic || sp[1];
31121 }
31122
31123 // handle the case where we had a +( thing at the *end*
31124 // of the pattern.
31125 // each pattern list stack adds 3 chars, and we need to go through
31126 // and escape any | chars that were passed through as-is for the regexp.
31127 // Go through and escape them, taking care not to double-escape any
31128 // | chars that were already escaped.
31129 for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
31130 var tail = re.slice(pl.reStart + pl.open.length);
31131 this.debug('setting tail', re, pl);
31132 // maybe some even number of \, then maybe 1 \, followed by a |
31133 tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
31134 if (!$2) {
31135 // the | isn't already escaped, so escape it.
31136 $2 = '\\';
31137 }
31138
31139 // need to escape all those slashes *again*, without escaping the
31140 // one that we need for escaping the | character. As it works out,
31141 // escaping an even number of slashes can be done by simply repeating
31142 // it exactly after itself. That's why this trick works.
31143 //
31144 // I am sorry that you have to see this.
31145 return $1 + $1 + $2 + '|'
31146 });
31147
31148 this.debug('tail=%j\n %s', tail, tail, pl, re);
31149 var t = pl.type === '*' ? star
31150 : pl.type === '?' ? qmark
31151 : '\\' + pl.type;
31152
31153 hasMagic = true;
31154 re = re.slice(0, pl.reStart) + t + '\\(' + tail;
31155 }
31156
31157 // handle trailing things that only matter at the very end.
31158 clearStateChar();
31159 if (escaping) {
31160 // trailing \\
31161 re += '\\\\';
31162 }
31163
31164 // only need to apply the nodot start if the re starts with
31165 // something that could conceivably capture a dot
31166 var addPatternStart = false;
31167 switch (re.charAt(0)) {
31168 case '.':
31169 case '[':
31170 case '(': addPatternStart = true;
31171 }
31172
31173 // Hack to work around lack of negative lookbehind in JS
31174 // A pattern like: *.!(x).!(y|z) needs to ensure that a name
31175 // like 'a.xyz.yz' doesn't match. So, the first negative
31176 // lookahead, has to look ALL the way ahead, to the end of
31177 // the pattern.
31178 for (var n = negativeLists.length - 1; n > -1; n--) {
31179 var nl = negativeLists[n];
31180
31181 var nlBefore = re.slice(0, nl.reStart);
31182 var nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
31183 var nlLast = re.slice(nl.reEnd - 8, nl.reEnd);
31184 var nlAfter = re.slice(nl.reEnd);
31185
31186 nlLast += nlAfter;
31187
31188 // Handle nested stuff like *(*.js|!(*.json)), where open parens
31189 // mean that we should *not* include the ) in the bit that is considered
31190 // "after" the negated section.
31191 var openParensBefore = nlBefore.split('(').length - 1;
31192 var cleanAfter = nlAfter;
31193 for (i = 0; i < openParensBefore; i++) {
31194 cleanAfter = cleanAfter.replace(/\)[+*?]?/, '');
31195 }
31196 nlAfter = cleanAfter;
31197
31198 var dollar = '';
31199 if (nlAfter === '' && isSub !== SUBPARSE) {
31200 dollar = '$';
31201 }
31202 var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast;
31203 re = newRe;
31204 }
31205
31206 // if the re is not "" at this point, then we need to make sure
31207 // it doesn't match against an empty path part.
31208 // Otherwise a/* will match a/, which it should not.
31209 if (re !== '' && hasMagic) {
31210 re = '(?=.)' + re;
31211 }
31212
31213 if (addPatternStart) {
31214 re = patternStart + re;
31215 }
31216
31217 // parsing just a piece of a larger pattern.
31218 if (isSub === SUBPARSE) {
31219 return [re, hasMagic]
31220 }
31221
31222 // skip the regexp for non-magical patterns
31223 // unescape anything in it, though, so that it'll be
31224 // an exact match against a file etc.
31225 if (!hasMagic) {
31226 return globUnescape(pattern)
31227 }
31228
31229 var flags = options.nocase ? 'i' : '';
31230 try {
31231 var regExp = new RegExp('^' + re + '$', flags);
31232 } catch (er) {
31233 // If it was an invalid regular expression, then it can't match
31234 // anything. This trick looks for a character after the end of
31235 // the string, which is of course impossible, except in multi-line
31236 // mode, but it's not a /m regex.
31237 return new RegExp('$.')
31238 }
31239
31240 regExp._glob = pattern;
31241 regExp._src = re;
31242
31243 return regExp
31244}
31245
31246minimatch$3.makeRe = function (pattern, options) {
31247 return new Minimatch$1(pattern, options || {}).makeRe()
31248};
31249
31250Minimatch$1.prototype.makeRe = makeRe$1;
31251function makeRe$1 () {
31252 if (this.regexp || this.regexp === false) return this.regexp
31253
31254 // at this point, this.set is a 2d array of partial
31255 // pattern strings, or "**".
31256 //
31257 // It's better to use .match(). This function shouldn't
31258 // be used, really, but it's pretty convenient sometimes,
31259 // when you just want to work with a regex.
31260 var set = this.set;
31261
31262 if (!set.length) {
31263 this.regexp = false;
31264 return this.regexp
31265 }
31266 var options = this.options;
31267
31268 var twoStar = options.noglobstar ? star
31269 : options.dot ? twoStarDot
31270 : twoStarNoDot;
31271 var flags = options.nocase ? 'i' : '';
31272
31273 var re = set.map(function (pattern) {
31274 return pattern.map(function (p) {
31275 return (p === GLOBSTAR$2) ? twoStar
31276 : (typeof p === 'string') ? regExpEscape(p)
31277 : p._src
31278 }).join('\\\/')
31279 }).join('|');
31280
31281 // must match entire pattern
31282 // ending in a * or ** will make it less strict.
31283 re = '^(?:' + re + ')$';
31284
31285 // can match anything, as long as it's not this.
31286 if (this.negate) re = '^(?!' + re + ').*$';
31287
31288 try {
31289 this.regexp = new RegExp(re, flags);
31290 } catch (ex) {
31291 this.regexp = false;
31292 }
31293 return this.regexp
31294}
31295
31296minimatch$3.match = function (list, pattern, options) {
31297 options = options || {};
31298 var mm = new Minimatch$1(pattern, options);
31299 list = list.filter(function (f) {
31300 return mm.match(f)
31301 });
31302 if (mm.options.nonull && !list.length) {
31303 list.push(pattern);
31304 }
31305 return list
31306};
31307
31308Minimatch$1.prototype.match = match;
31309function match (f, partial) {
31310 this.debug('match', f, this.pattern);
31311 // short-circuit in the case of busted things.
31312 // comments, etc.
31313 if (this.comment) return false
31314 if (this.empty) return f === ''
31315
31316 if (f === '/' && partial) return true
31317
31318 var options = this.options;
31319
31320 // windows: need to use /, not \
31321 if (path$m.sep !== '/') {
31322 f = f.split(path$m.sep).join('/');
31323 }
31324
31325 // treat the test path as a set of pathparts.
31326 f = f.split(slashSplit);
31327 this.debug(this.pattern, 'split', f);
31328
31329 // just ONE of the pattern sets in this.set needs to match
31330 // in order for it to be valid. If negating, then just one
31331 // match means that we have failed.
31332 // Either way, return on the first hit.
31333
31334 var set = this.set;
31335 this.debug(this.pattern, 'set', set);
31336
31337 // Find the basename of the path by looking for the last non-empty segment
31338 var filename;
31339 var i;
31340 for (i = f.length - 1; i >= 0; i--) {
31341 filename = f[i];
31342 if (filename) break
31343 }
31344
31345 for (i = 0; i < set.length; i++) {
31346 var pattern = set[i];
31347 var file = f;
31348 if (options.matchBase && pattern.length === 1) {
31349 file = [filename];
31350 }
31351 var hit = this.matchOne(file, pattern, partial);
31352 if (hit) {
31353 if (options.flipNegate) return true
31354 return !this.negate
31355 }
31356 }
31357
31358 // didn't get any hits. this is success if it's a negative
31359 // pattern, failure otherwise.
31360 if (options.flipNegate) return false
31361 return this.negate
31362}
31363
31364// set partial to true to test if, for example,
31365// "/a/b" matches the start of "/*/b/*/d"
31366// Partial means, if you run out of file before you run
31367// out of pattern, then that's fine, as long as all
31368// the parts match.
31369Minimatch$1.prototype.matchOne = function (file, pattern, partial) {
31370 var options = this.options;
31371
31372 this.debug('matchOne',
31373 { 'this': this, file: file, pattern: pattern });
31374
31375 this.debug('matchOne', file.length, pattern.length);
31376
31377 for (var fi = 0,
31378 pi = 0,
31379 fl = file.length,
31380 pl = pattern.length
31381 ; (fi < fl) && (pi < pl)
31382 ; fi++, pi++) {
31383 this.debug('matchOne loop');
31384 var p = pattern[pi];
31385 var f = file[fi];
31386
31387 this.debug(pattern, p, f);
31388
31389 // should be impossible.
31390 // some invalid regexp stuff in the set.
31391 if (p === false) return false
31392
31393 if (p === GLOBSTAR$2) {
31394 this.debug('GLOBSTAR', [pattern, p, f]);
31395
31396 // "**"
31397 // a/**/b/**/c would match the following:
31398 // a/b/x/y/z/c
31399 // a/x/y/z/b/c
31400 // a/b/x/b/x/c
31401 // a/b/c
31402 // To do this, take the rest of the pattern after
31403 // the **, and see if it would match the file remainder.
31404 // If so, return success.
31405 // If not, the ** "swallows" a segment, and try again.
31406 // This is recursively awful.
31407 //
31408 // a/**/b/**/c matching a/b/x/y/z/c
31409 // - a matches a
31410 // - doublestar
31411 // - matchOne(b/x/y/z/c, b/**/c)
31412 // - b matches b
31413 // - doublestar
31414 // - matchOne(x/y/z/c, c) -> no
31415 // - matchOne(y/z/c, c) -> no
31416 // - matchOne(z/c, c) -> no
31417 // - matchOne(c, c) yes, hit
31418 var fr = fi;
31419 var pr = pi + 1;
31420 if (pr === pl) {
31421 this.debug('** at the end');
31422 // a ** at the end will just swallow the rest.
31423 // We have found a match.
31424 // however, it will not swallow /.x, unless
31425 // options.dot is set.
31426 // . and .. are *never* matched by **, for explosively
31427 // exponential reasons.
31428 for (; fi < fl; fi++) {
31429 if (file[fi] === '.' || file[fi] === '..' ||
31430 (!options.dot && file[fi].charAt(0) === '.')) return false
31431 }
31432 return true
31433 }
31434
31435 // ok, let's see if we can swallow whatever we can.
31436 while (fr < fl) {
31437 var swallowee = file[fr];
31438
31439 this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
31440
31441 // XXX remove this slice. Just pass the start index.
31442 if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
31443 this.debug('globstar found match!', fr, fl, swallowee);
31444 // found a match.
31445 return true
31446 } else {
31447 // can't swallow "." or ".." ever.
31448 // can only swallow ".foo" when explicitly asked.
31449 if (swallowee === '.' || swallowee === '..' ||
31450 (!options.dot && swallowee.charAt(0) === '.')) {
31451 this.debug('dot detected!', file, fr, pattern, pr);
31452 break
31453 }
31454
31455 // ** swallows a segment, and continue.
31456 this.debug('globstar swallow a segment, and continue');
31457 fr++;
31458 }
31459 }
31460
31461 // no match was found.
31462 // However, in partial mode, we can't say this is necessarily over.
31463 // If there's more *pattern* left, then
31464 if (partial) {
31465 // ran out of file
31466 this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
31467 if (fr === fl) return true
31468 }
31469 return false
31470 }
31471
31472 // something other than **
31473 // non-magic patterns just have to match exactly
31474 // patterns with magic have been turned into regexps.
31475 var hit;
31476 if (typeof p === 'string') {
31477 if (options.nocase) {
31478 hit = f.toLowerCase() === p.toLowerCase();
31479 } else {
31480 hit = f === p;
31481 }
31482 this.debug('string match', p, f, hit);
31483 } else {
31484 hit = f.match(p);
31485 this.debug('pattern match', p, f, hit);
31486 }
31487
31488 if (!hit) return false
31489 }
31490
31491 // Note: ending in / means that we'll get a final ""
31492 // at the end of the pattern. This can only match a
31493 // corresponding "" at the end of the file.
31494 // If the file ends in /, then it can only match a
31495 // a pattern that ends in /, unless the pattern just
31496 // doesn't have any more for it. But, a/b/ should *not*
31497 // match "a/b/*", even though "" matches against the
31498 // [^/]*? pattern, except in partial mode, where it might
31499 // simply not be reached yet.
31500 // However, a/b/ should still satisfy a/*
31501
31502 // now either we fell off the end of the pattern, or we're done.
31503 if (fi === fl && pi === pl) {
31504 // ran out of pattern and filename at the same time.
31505 // an exact hit!
31506 return true
31507 } else if (fi === fl) {
31508 // ran out of file, but still had pattern left.
31509 // this is ok if we're doing the match as part of
31510 // a glob fs traversal.
31511 return partial
31512 } else if (pi === pl) {
31513 // ran out of pattern, still have file left.
31514 // this is only acceptable if we're on the very last
31515 // empty segment of a file with a trailing slash.
31516 // a/* should match a/b/
31517 var emptyFileEnd = (fi === fl - 1) && (file[fi] === '');
31518 return emptyFileEnd
31519 }
31520
31521 // should be unreachable.
31522 throw new Error('wtf?')
31523};
31524
31525// replace stuff like \* with *
31526function globUnescape (s) {
31527 return s.replace(/\\(.)/g, '$1')
31528}
31529
31530function regExpEscape (s) {
31531 return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
31532}
31533
31534var inherits$1 = {exports: {}};
31535
31536var inherits_browser = {exports: {}};
31537
31538if (typeof Object.create === 'function') {
31539 // implementation from standard node.js 'util' module
31540 inherits_browser.exports = function inherits(ctor, superCtor) {
31541 if (superCtor) {
31542 ctor.super_ = superCtor;
31543 ctor.prototype = Object.create(superCtor.prototype, {
31544 constructor: {
31545 value: ctor,
31546 enumerable: false,
31547 writable: true,
31548 configurable: true
31549 }
31550 });
31551 }
31552 };
31553} else {
31554 // old school shim for old browsers
31555 inherits_browser.exports = function inherits(ctor, superCtor) {
31556 if (superCtor) {
31557 ctor.super_ = superCtor;
31558 var TempCtor = function () {};
31559 TempCtor.prototype = superCtor.prototype;
31560 ctor.prototype = new TempCtor();
31561 ctor.prototype.constructor = ctor;
31562 }
31563 };
31564}
31565
31566try {
31567 var util = require$$0__default$3;
31568 /* istanbul ignore next */
31569 if (typeof util.inherits !== 'function') throw '';
31570 inherits$1.exports = util.inherits;
31571} catch (e) {
31572 /* istanbul ignore next */
31573 inherits$1.exports = inherits_browser.exports;
31574}
31575
31576var pathIsAbsolute = {exports: {}};
31577
31578function posix(path) {
31579 return path.charAt(0) === '/';
31580}
31581
31582function win32(path) {
31583 // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56
31584 var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
31585 var result = splitDeviceRe.exec(path);
31586 var device = result[1] || '';
31587 var isUnc = Boolean(device && device.charAt(1) !== ':');
31588
31589 // UNC paths are always absolute
31590 return Boolean(result[2] || isUnc);
31591}
31592
31593pathIsAbsolute.exports = process.platform === 'win32' ? win32 : posix;
31594pathIsAbsolute.exports.posix = posix;
31595pathIsAbsolute.exports.win32 = win32;
31596
31597var common$7 = {};
31598
31599common$7.setopts = setopts$2;
31600common$7.ownProp = ownProp$2;
31601common$7.makeAbs = makeAbs;
31602common$7.finish = finish;
31603common$7.mark = mark;
31604common$7.isIgnored = isIgnored$2;
31605common$7.childrenIgnored = childrenIgnored$2;
31606
31607function ownProp$2 (obj, field) {
31608 return Object.prototype.hasOwnProperty.call(obj, field)
31609}
31610
31611var path$l = path__default;
31612var minimatch$2 = minimatch_1;
31613var isAbsolute$2 = pathIsAbsolute.exports;
31614var Minimatch = minimatch$2.Minimatch;
31615
31616function alphasort (a, b) {
31617 return a.localeCompare(b, 'en')
31618}
31619
31620function setupIgnores (self, options) {
31621 self.ignore = options.ignore || [];
31622
31623 if (!Array.isArray(self.ignore))
31624 self.ignore = [self.ignore];
31625
31626 if (self.ignore.length) {
31627 self.ignore = self.ignore.map(ignoreMap);
31628 }
31629}
31630
31631// ignore patterns are always in dot:true mode.
31632function ignoreMap (pattern) {
31633 var gmatcher = null;
31634 if (pattern.slice(-3) === '/**') {
31635 var gpattern = pattern.replace(/(\/\*\*)+$/, '');
31636 gmatcher = new Minimatch(gpattern, { dot: true });
31637 }
31638
31639 return {
31640 matcher: new Minimatch(pattern, { dot: true }),
31641 gmatcher: gmatcher
31642 }
31643}
31644
31645function setopts$2 (self, pattern, options) {
31646 if (!options)
31647 options = {};
31648
31649 // base-matching: just use globstar for that.
31650 if (options.matchBase && -1 === pattern.indexOf("/")) {
31651 if (options.noglobstar) {
31652 throw new Error("base matching requires globstar")
31653 }
31654 pattern = "**/" + pattern;
31655 }
31656
31657 self.silent = !!options.silent;
31658 self.pattern = pattern;
31659 self.strict = options.strict !== false;
31660 self.realpath = !!options.realpath;
31661 self.realpathCache = options.realpathCache || Object.create(null);
31662 self.follow = !!options.follow;
31663 self.dot = !!options.dot;
31664 self.mark = !!options.mark;
31665 self.nodir = !!options.nodir;
31666 if (self.nodir)
31667 self.mark = true;
31668 self.sync = !!options.sync;
31669 self.nounique = !!options.nounique;
31670 self.nonull = !!options.nonull;
31671 self.nosort = !!options.nosort;
31672 self.nocase = !!options.nocase;
31673 self.stat = !!options.stat;
31674 self.noprocess = !!options.noprocess;
31675 self.absolute = !!options.absolute;
31676
31677 self.maxLength = options.maxLength || Infinity;
31678 self.cache = options.cache || Object.create(null);
31679 self.statCache = options.statCache || Object.create(null);
31680 self.symlinks = options.symlinks || Object.create(null);
31681
31682 setupIgnores(self, options);
31683
31684 self.changedCwd = false;
31685 var cwd = process.cwd();
31686 if (!ownProp$2(options, "cwd"))
31687 self.cwd = cwd;
31688 else {
31689 self.cwd = path$l.resolve(options.cwd);
31690 self.changedCwd = self.cwd !== cwd;
31691 }
31692
31693 self.root = options.root || path$l.resolve(self.cwd, "/");
31694 self.root = path$l.resolve(self.root);
31695 if (process.platform === "win32")
31696 self.root = self.root.replace(/\\/g, "/");
31697
31698 // TODO: is an absolute `cwd` supposed to be resolved against `root`?
31699 // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test')
31700 self.cwdAbs = isAbsolute$2(self.cwd) ? self.cwd : makeAbs(self, self.cwd);
31701 if (process.platform === "win32")
31702 self.cwdAbs = self.cwdAbs.replace(/\\/g, "/");
31703 self.nomount = !!options.nomount;
31704
31705 // disable comments and negation in Minimatch.
31706 // Note that they are not supported in Glob itself anyway.
31707 options.nonegate = true;
31708 options.nocomment = true;
31709
31710 self.minimatch = new Minimatch(pattern, options);
31711 self.options = self.minimatch.options;
31712}
31713
31714function finish (self) {
31715 var nou = self.nounique;
31716 var all = nou ? [] : Object.create(null);
31717
31718 for (var i = 0, l = self.matches.length; i < l; i ++) {
31719 var matches = self.matches[i];
31720 if (!matches || Object.keys(matches).length === 0) {
31721 if (self.nonull) {
31722 // do like the shell, and spit out the literal glob
31723 var literal = self.minimatch.globSet[i];
31724 if (nou)
31725 all.push(literal);
31726 else
31727 all[literal] = true;
31728 }
31729 } else {
31730 // had matches
31731 var m = Object.keys(matches);
31732 if (nou)
31733 all.push.apply(all, m);
31734 else
31735 m.forEach(function (m) {
31736 all[m] = true;
31737 });
31738 }
31739 }
31740
31741 if (!nou)
31742 all = Object.keys(all);
31743
31744 if (!self.nosort)
31745 all = all.sort(alphasort);
31746
31747 // at *some* point we statted all of these
31748 if (self.mark) {
31749 for (var i = 0; i < all.length; i++) {
31750 all[i] = self._mark(all[i]);
31751 }
31752 if (self.nodir) {
31753 all = all.filter(function (e) {
31754 var notDir = !(/\/$/.test(e));
31755 var c = self.cache[e] || self.cache[makeAbs(self, e)];
31756 if (notDir && c)
31757 notDir = c !== 'DIR' && !Array.isArray(c);
31758 return notDir
31759 });
31760 }
31761 }
31762
31763 if (self.ignore.length)
31764 all = all.filter(function(m) {
31765 return !isIgnored$2(self, m)
31766 });
31767
31768 self.found = all;
31769}
31770
31771function mark (self, p) {
31772 var abs = makeAbs(self, p);
31773 var c = self.cache[abs];
31774 var m = p;
31775 if (c) {
31776 var isDir = c === 'DIR' || Array.isArray(c);
31777 var slash = p.slice(-1) === '/';
31778
31779 if (isDir && !slash)
31780 m += '/';
31781 else if (!isDir && slash)
31782 m = m.slice(0, -1);
31783
31784 if (m !== p) {
31785 var mabs = makeAbs(self, m);
31786 self.statCache[mabs] = self.statCache[abs];
31787 self.cache[mabs] = self.cache[abs];
31788 }
31789 }
31790
31791 return m
31792}
31793
31794// lotta situps...
31795function makeAbs (self, f) {
31796 var abs = f;
31797 if (f.charAt(0) === '/') {
31798 abs = path$l.join(self.root, f);
31799 } else if (isAbsolute$2(f) || f === '') {
31800 abs = f;
31801 } else if (self.changedCwd) {
31802 abs = path$l.resolve(self.cwd, f);
31803 } else {
31804 abs = path$l.resolve(f);
31805 }
31806
31807 if (process.platform === 'win32')
31808 abs = abs.replace(/\\/g, '/');
31809
31810 return abs
31811}
31812
31813
31814// Return true, if pattern ends with globstar '**', for the accompanying parent directory.
31815// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents
31816function isIgnored$2 (self, path) {
31817 if (!self.ignore.length)
31818 return false
31819
31820 return self.ignore.some(function(item) {
31821 return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path))
31822 })
31823}
31824
31825function childrenIgnored$2 (self, path) {
31826 if (!self.ignore.length)
31827 return false
31828
31829 return self.ignore.some(function(item) {
31830 return !!(item.gmatcher && item.gmatcher.match(path))
31831 })
31832}
31833
31834var sync$5 = globSync$1;
31835globSync$1.GlobSync = GlobSync$1;
31836
31837var fs$i = fs__default;
31838var rp$1 = fs_realpath;
31839var minimatch$1 = minimatch_1;
31840var path$k = path__default;
31841var assert$3 = require$$6__default;
31842var isAbsolute$1 = pathIsAbsolute.exports;
31843var common$6 = common$7;
31844var setopts$1 = common$6.setopts;
31845var ownProp$1 = common$6.ownProp;
31846var childrenIgnored$1 = common$6.childrenIgnored;
31847var isIgnored$1 = common$6.isIgnored;
31848
31849function globSync$1 (pattern, options) {
31850 if (typeof options === 'function' || arguments.length === 3)
31851 throw new TypeError('callback provided to sync glob\n'+
31852 'See: https://github.com/isaacs/node-glob/issues/167')
31853
31854 return new GlobSync$1(pattern, options).found
31855}
31856
31857function GlobSync$1 (pattern, options) {
31858 if (!pattern)
31859 throw new Error('must provide pattern')
31860
31861 if (typeof options === 'function' || arguments.length === 3)
31862 throw new TypeError('callback provided to sync glob\n'+
31863 'See: https://github.com/isaacs/node-glob/issues/167')
31864
31865 if (!(this instanceof GlobSync$1))
31866 return new GlobSync$1(pattern, options)
31867
31868 setopts$1(this, pattern, options);
31869
31870 if (this.noprocess)
31871 return this
31872
31873 var n = this.minimatch.set.length;
31874 this.matches = new Array(n);
31875 for (var i = 0; i < n; i ++) {
31876 this._process(this.minimatch.set[i], i, false);
31877 }
31878 this._finish();
31879}
31880
31881GlobSync$1.prototype._finish = function () {
31882 assert$3(this instanceof GlobSync$1);
31883 if (this.realpath) {
31884 var self = this;
31885 this.matches.forEach(function (matchset, index) {
31886 var set = self.matches[index] = Object.create(null);
31887 for (var p in matchset) {
31888 try {
31889 p = self._makeAbs(p);
31890 var real = rp$1.realpathSync(p, self.realpathCache);
31891 set[real] = true;
31892 } catch (er) {
31893 if (er.syscall === 'stat')
31894 set[self._makeAbs(p)] = true;
31895 else
31896 throw er
31897 }
31898 }
31899 });
31900 }
31901 common$6.finish(this);
31902};
31903
31904
31905GlobSync$1.prototype._process = function (pattern, index, inGlobStar) {
31906 assert$3(this instanceof GlobSync$1);
31907
31908 // Get the first [n] parts of pattern that are all strings.
31909 var n = 0;
31910 while (typeof pattern[n] === 'string') {
31911 n ++;
31912 }
31913 // now n is the index of the first one that is *not* a string.
31914
31915 // See if there's anything else
31916 var prefix;
31917 switch (n) {
31918 // if not, then this is rather simple
31919 case pattern.length:
31920 this._processSimple(pattern.join('/'), index);
31921 return
31922
31923 case 0:
31924 // pattern *starts* with some non-trivial item.
31925 // going to readdir(cwd), but not include the prefix in matches.
31926 prefix = null;
31927 break
31928
31929 default:
31930 // pattern has some string bits in the front.
31931 // whatever it starts with, whether that's 'absolute' like /foo/bar,
31932 // or 'relative' like '../baz'
31933 prefix = pattern.slice(0, n).join('/');
31934 break
31935 }
31936
31937 var remain = pattern.slice(n);
31938
31939 // get the list of entries.
31940 var read;
31941 if (prefix === null)
31942 read = '.';
31943 else if (isAbsolute$1(prefix) || isAbsolute$1(pattern.join('/'))) {
31944 if (!prefix || !isAbsolute$1(prefix))
31945 prefix = '/' + prefix;
31946 read = prefix;
31947 } else
31948 read = prefix;
31949
31950 var abs = this._makeAbs(read);
31951
31952 //if ignored, skip processing
31953 if (childrenIgnored$1(this, read))
31954 return
31955
31956 var isGlobStar = remain[0] === minimatch$1.GLOBSTAR;
31957 if (isGlobStar)
31958 this._processGlobStar(prefix, read, abs, remain, index, inGlobStar);
31959 else
31960 this._processReaddir(prefix, read, abs, remain, index, inGlobStar);
31961};
31962
31963
31964GlobSync$1.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {
31965 var entries = this._readdir(abs, inGlobStar);
31966
31967 // if the abs isn't a dir, then nothing can match!
31968 if (!entries)
31969 return
31970
31971 // It will only match dot entries if it starts with a dot, or if
31972 // dot is set. Stuff like @(.foo|.bar) isn't allowed.
31973 var pn = remain[0];
31974 var negate = !!this.minimatch.negate;
31975 var rawGlob = pn._glob;
31976 var dotOk = this.dot || rawGlob.charAt(0) === '.';
31977
31978 var matchedEntries = [];
31979 for (var i = 0; i < entries.length; i++) {
31980 var e = entries[i];
31981 if (e.charAt(0) !== '.' || dotOk) {
31982 var m;
31983 if (negate && !prefix) {
31984 m = !e.match(pn);
31985 } else {
31986 m = e.match(pn);
31987 }
31988 if (m)
31989 matchedEntries.push(e);
31990 }
31991 }
31992
31993 var len = matchedEntries.length;
31994 // If there are no matched entries, then nothing matches.
31995 if (len === 0)
31996 return
31997
31998 // if this is the last remaining pattern bit, then no need for
31999 // an additional stat *unless* the user has specified mark or
32000 // stat explicitly. We know they exist, since readdir returned
32001 // them.
32002
32003 if (remain.length === 1 && !this.mark && !this.stat) {
32004 if (!this.matches[index])
32005 this.matches[index] = Object.create(null);
32006
32007 for (var i = 0; i < len; i ++) {
32008 var e = matchedEntries[i];
32009 if (prefix) {
32010 if (prefix.slice(-1) !== '/')
32011 e = prefix + '/' + e;
32012 else
32013 e = prefix + e;
32014 }
32015
32016 if (e.charAt(0) === '/' && !this.nomount) {
32017 e = path$k.join(this.root, e);
32018 }
32019 this._emitMatch(index, e);
32020 }
32021 // This was the last one, and no stats were needed
32022 return
32023 }
32024
32025 // now test all matched entries as stand-ins for that part
32026 // of the pattern.
32027 remain.shift();
32028 for (var i = 0; i < len; i ++) {
32029 var e = matchedEntries[i];
32030 var newPattern;
32031 if (prefix)
32032 newPattern = [prefix, e];
32033 else
32034 newPattern = [e];
32035 this._process(newPattern.concat(remain), index, inGlobStar);
32036 }
32037};
32038
32039
32040GlobSync$1.prototype._emitMatch = function (index, e) {
32041 if (isIgnored$1(this, e))
32042 return
32043
32044 var abs = this._makeAbs(e);
32045
32046 if (this.mark)
32047 e = this._mark(e);
32048
32049 if (this.absolute) {
32050 e = abs;
32051 }
32052
32053 if (this.matches[index][e])
32054 return
32055
32056 if (this.nodir) {
32057 var c = this.cache[abs];
32058 if (c === 'DIR' || Array.isArray(c))
32059 return
32060 }
32061
32062 this.matches[index][e] = true;
32063
32064 if (this.stat)
32065 this._stat(e);
32066};
32067
32068
32069GlobSync$1.prototype._readdirInGlobStar = function (abs) {
32070 // follow all symlinked directories forever
32071 // just proceed as if this is a non-globstar situation
32072 if (this.follow)
32073 return this._readdir(abs, false)
32074
32075 var entries;
32076 var lstat;
32077 try {
32078 lstat = fs$i.lstatSync(abs);
32079 } catch (er) {
32080 if (er.code === 'ENOENT') {
32081 // lstat failed, doesn't exist
32082 return null
32083 }
32084 }
32085
32086 var isSym = lstat && lstat.isSymbolicLink();
32087 this.symlinks[abs] = isSym;
32088
32089 // If it's not a symlink or a dir, then it's definitely a regular file.
32090 // don't bother doing a readdir in that case.
32091 if (!isSym && lstat && !lstat.isDirectory())
32092 this.cache[abs] = 'FILE';
32093 else
32094 entries = this._readdir(abs, false);
32095
32096 return entries
32097};
32098
32099GlobSync$1.prototype._readdir = function (abs, inGlobStar) {
32100
32101 if (inGlobStar && !ownProp$1(this.symlinks, abs))
32102 return this._readdirInGlobStar(abs)
32103
32104 if (ownProp$1(this.cache, abs)) {
32105 var c = this.cache[abs];
32106 if (!c || c === 'FILE')
32107 return null
32108
32109 if (Array.isArray(c))
32110 return c
32111 }
32112
32113 try {
32114 return this._readdirEntries(abs, fs$i.readdirSync(abs))
32115 } catch (er) {
32116 this._readdirError(abs, er);
32117 return null
32118 }
32119};
32120
32121GlobSync$1.prototype._readdirEntries = function (abs, entries) {
32122 // if we haven't asked to stat everything, then just
32123 // assume that everything in there exists, so we can avoid
32124 // having to stat it a second time.
32125 if (!this.mark && !this.stat) {
32126 for (var i = 0; i < entries.length; i ++) {
32127 var e = entries[i];
32128 if (abs === '/')
32129 e = abs + e;
32130 else
32131 e = abs + '/' + e;
32132 this.cache[e] = true;
32133 }
32134 }
32135
32136 this.cache[abs] = entries;
32137
32138 // mark and cache dir-ness
32139 return entries
32140};
32141
32142GlobSync$1.prototype._readdirError = function (f, er) {
32143 // handle errors, and cache the information
32144 switch (er.code) {
32145 case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
32146 case 'ENOTDIR': // totally normal. means it *does* exist.
32147 var abs = this._makeAbs(f);
32148 this.cache[abs] = 'FILE';
32149 if (abs === this.cwdAbs) {
32150 var error = new Error(er.code + ' invalid cwd ' + this.cwd);
32151 error.path = this.cwd;
32152 error.code = er.code;
32153 throw error
32154 }
32155 break
32156
32157 case 'ENOENT': // not terribly unusual
32158 case 'ELOOP':
32159 case 'ENAMETOOLONG':
32160 case 'UNKNOWN':
32161 this.cache[this._makeAbs(f)] = false;
32162 break
32163
32164 default: // some unusual error. Treat as failure.
32165 this.cache[this._makeAbs(f)] = false;
32166 if (this.strict)
32167 throw er
32168 if (!this.silent)
32169 console.error('glob error', er);
32170 break
32171 }
32172};
32173
32174GlobSync$1.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {
32175
32176 var entries = this._readdir(abs, inGlobStar);
32177
32178 // no entries means not a dir, so it can never have matches
32179 // foo.txt/** doesn't match foo.txt
32180 if (!entries)
32181 return
32182
32183 // test without the globstar, and with every child both below
32184 // and replacing the globstar.
32185 var remainWithoutGlobStar = remain.slice(1);
32186 var gspref = prefix ? [ prefix ] : [];
32187 var noGlobStar = gspref.concat(remainWithoutGlobStar);
32188
32189 // the noGlobStar pattern exits the inGlobStar state
32190 this._process(noGlobStar, index, false);
32191
32192 var len = entries.length;
32193 var isSym = this.symlinks[abs];
32194
32195 // If it's a symlink, and we're in a globstar, then stop
32196 if (isSym && inGlobStar)
32197 return
32198
32199 for (var i = 0; i < len; i++) {
32200 var e = entries[i];
32201 if (e.charAt(0) === '.' && !this.dot)
32202 continue
32203
32204 // these two cases enter the inGlobStar state
32205 var instead = gspref.concat(entries[i], remainWithoutGlobStar);
32206 this._process(instead, index, true);
32207
32208 var below = gspref.concat(entries[i], remain);
32209 this._process(below, index, true);
32210 }
32211};
32212
32213GlobSync$1.prototype._processSimple = function (prefix, index) {
32214 // XXX review this. Shouldn't it be doing the mounting etc
32215 // before doing stat? kinda weird?
32216 var exists = this._stat(prefix);
32217
32218 if (!this.matches[index])
32219 this.matches[index] = Object.create(null);
32220
32221 // If it doesn't exist, then just mark the lack of results
32222 if (!exists)
32223 return
32224
32225 if (prefix && isAbsolute$1(prefix) && !this.nomount) {
32226 var trail = /[\/\\]$/.test(prefix);
32227 if (prefix.charAt(0) === '/') {
32228 prefix = path$k.join(this.root, prefix);
32229 } else {
32230 prefix = path$k.resolve(this.root, prefix);
32231 if (trail)
32232 prefix += '/';
32233 }
32234 }
32235
32236 if (process.platform === 'win32')
32237 prefix = prefix.replace(/\\/g, '/');
32238
32239 // Mark this as a match
32240 this._emitMatch(index, prefix);
32241};
32242
32243// Returns either 'DIR', 'FILE', or false
32244GlobSync$1.prototype._stat = function (f) {
32245 var abs = this._makeAbs(f);
32246 var needDir = f.slice(-1) === '/';
32247
32248 if (f.length > this.maxLength)
32249 return false
32250
32251 if (!this.stat && ownProp$1(this.cache, abs)) {
32252 var c = this.cache[abs];
32253
32254 if (Array.isArray(c))
32255 c = 'DIR';
32256
32257 // It exists, but maybe not how we need it
32258 if (!needDir || c === 'DIR')
32259 return c
32260
32261 if (needDir && c === 'FILE')
32262 return false
32263
32264 // otherwise we have to stat, because maybe c=true
32265 // if we know it exists, but not what it is.
32266 }
32267 var stat = this.statCache[abs];
32268 if (!stat) {
32269 var lstat;
32270 try {
32271 lstat = fs$i.lstatSync(abs);
32272 } catch (er) {
32273 if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
32274 this.statCache[abs] = false;
32275 return false
32276 }
32277 }
32278
32279 if (lstat && lstat.isSymbolicLink()) {
32280 try {
32281 stat = fs$i.statSync(abs);
32282 } catch (er) {
32283 stat = lstat;
32284 }
32285 } else {
32286 stat = lstat;
32287 }
32288 }
32289
32290 this.statCache[abs] = stat;
32291
32292 var c = true;
32293 if (stat)
32294 c = stat.isDirectory() ? 'DIR' : 'FILE';
32295
32296 this.cache[abs] = this.cache[abs] || c;
32297
32298 if (needDir && c === 'FILE')
32299 return false
32300
32301 return c
32302};
32303
32304GlobSync$1.prototype._mark = function (p) {
32305 return common$6.mark(this, p)
32306};
32307
32308GlobSync$1.prototype._makeAbs = function (f) {
32309 return common$6.makeAbs(this, f)
32310};
32311
32312// Returns a wrapper function that returns a wrapped callback
32313// The wrapper function should do some stuff, and return a
32314// presumably different callback function.
32315// This makes sure that own properties are retained, so that
32316// decorations and such are not lost along the way.
32317var wrappy_1 = wrappy$2;
32318function wrappy$2 (fn, cb) {
32319 if (fn && cb) return wrappy$2(fn)(cb)
32320
32321 if (typeof fn !== 'function')
32322 throw new TypeError('need wrapper function')
32323
32324 Object.keys(fn).forEach(function (k) {
32325 wrapper[k] = fn[k];
32326 });
32327
32328 return wrapper
32329
32330 function wrapper() {
32331 var args = new Array(arguments.length);
32332 for (var i = 0; i < args.length; i++) {
32333 args[i] = arguments[i];
32334 }
32335 var ret = fn.apply(this, args);
32336 var cb = args[args.length-1];
32337 if (typeof ret === 'function' && ret !== cb) {
32338 Object.keys(cb).forEach(function (k) {
32339 ret[k] = cb[k];
32340 });
32341 }
32342 return ret
32343 }
32344}
32345
32346var once$3 = {exports: {}};
32347
32348var wrappy$1 = wrappy_1;
32349once$3.exports = wrappy$1(once$2);
32350once$3.exports.strict = wrappy$1(onceStrict);
32351
32352once$2.proto = once$2(function () {
32353 Object.defineProperty(Function.prototype, 'once', {
32354 value: function () {
32355 return once$2(this)
32356 },
32357 configurable: true
32358 });
32359
32360 Object.defineProperty(Function.prototype, 'onceStrict', {
32361 value: function () {
32362 return onceStrict(this)
32363 },
32364 configurable: true
32365 });
32366});
32367
32368function once$2 (fn) {
32369 var f = function () {
32370 if (f.called) return f.value
32371 f.called = true;
32372 return f.value = fn.apply(this, arguments)
32373 };
32374 f.called = false;
32375 return f
32376}
32377
32378function onceStrict (fn) {
32379 var f = function () {
32380 if (f.called)
32381 throw new Error(f.onceError)
32382 f.called = true;
32383 return f.value = fn.apply(this, arguments)
32384 };
32385 var name = fn.name || 'Function wrapped with `once`';
32386 f.onceError = name + " shouldn't be called more than once";
32387 f.called = false;
32388 return f
32389}
32390
32391var wrappy = wrappy_1;
32392var reqs = Object.create(null);
32393var once$1 = once$3.exports;
32394
32395var inflight_1 = wrappy(inflight$1);
32396
32397function inflight$1 (key, cb) {
32398 if (reqs[key]) {
32399 reqs[key].push(cb);
32400 return null
32401 } else {
32402 reqs[key] = [cb];
32403 return makeres(key)
32404 }
32405}
32406
32407function makeres (key) {
32408 return once$1(function RES () {
32409 var cbs = reqs[key];
32410 var len = cbs.length;
32411 var args = slice(arguments);
32412
32413 // XXX It's somewhat ambiguous whether a new callback added in this
32414 // pass should be queued for later execution if something in the
32415 // list of callbacks throws, or if it should just be discarded.
32416 // However, it's such an edge case that it hardly matters, and either
32417 // choice is likely as surprising as the other.
32418 // As it happens, we do go ahead and schedule it for later execution.
32419 try {
32420 for (var i = 0; i < len; i++) {
32421 cbs[i].apply(null, args);
32422 }
32423 } finally {
32424 if (cbs.length > len) {
32425 // added more in the interim.
32426 // de-zalgo, just in case, but don't call again.
32427 cbs.splice(0, len);
32428 process.nextTick(function () {
32429 RES.apply(null, args);
32430 });
32431 } else {
32432 delete reqs[key];
32433 }
32434 }
32435 })
32436}
32437
32438function slice (args) {
32439 var length = args.length;
32440 var array = [];
32441
32442 for (var i = 0; i < length; i++) array[i] = args[i];
32443 return array
32444}
32445
32446// Approach:
32447//
32448// 1. Get the minimatch set
32449// 2. For each pattern in the set, PROCESS(pattern, false)
32450// 3. Store matches per-set, then uniq them
32451//
32452// PROCESS(pattern, inGlobStar)
32453// Get the first [n] items from pattern that are all strings
32454// Join these together. This is PREFIX.
32455// If there is no more remaining, then stat(PREFIX) and
32456// add to matches if it succeeds. END.
32457//
32458// If inGlobStar and PREFIX is symlink and points to dir
32459// set ENTRIES = []
32460// else readdir(PREFIX) as ENTRIES
32461// If fail, END
32462//
32463// with ENTRIES
32464// If pattern[n] is GLOBSTAR
32465// // handle the case where the globstar match is empty
32466// // by pruning it out, and testing the resulting pattern
32467// PROCESS(pattern[0..n] + pattern[n+1 .. $], false)
32468// // handle other cases.
32469// for ENTRY in ENTRIES (not dotfiles)
32470// // attach globstar + tail onto the entry
32471// // Mark that this entry is a globstar match
32472// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)
32473//
32474// else // not globstar
32475// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
32476// Test ENTRY against pattern[n]
32477// If fails, continue
32478// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
32479//
32480// Caveat:
32481// Cache all stats and readdirs results to minimize syscall. Since all
32482// we ever care about is existence and directory-ness, we can just keep
32483// `true` for files, and [children,...] for directories, or `false` for
32484// things that don't exist.
32485
32486var glob_1 = glob;
32487
32488var fs$h = fs__default;
32489var rp = fs_realpath;
32490var minimatch = minimatch_1;
32491var inherits = inherits$1.exports;
32492var EE$1 = require$$0__default$6.EventEmitter;
32493var path$j = path__default;
32494var assert$2 = require$$6__default;
32495var isAbsolute = pathIsAbsolute.exports;
32496var globSync = sync$5;
32497var common$5 = common$7;
32498var setopts = common$5.setopts;
32499var ownProp = common$5.ownProp;
32500var inflight = inflight_1;
32501var childrenIgnored = common$5.childrenIgnored;
32502var isIgnored = common$5.isIgnored;
32503
32504var once = once$3.exports;
32505
32506function glob (pattern, options, cb) {
32507 if (typeof options === 'function') cb = options, options = {};
32508 if (!options) options = {};
32509
32510 if (options.sync) {
32511 if (cb)
32512 throw new TypeError('callback provided to sync glob')
32513 return globSync(pattern, options)
32514 }
32515
32516 return new Glob(pattern, options, cb)
32517}
32518
32519glob.sync = globSync;
32520var GlobSync = glob.GlobSync = globSync.GlobSync;
32521
32522// old api surface
32523glob.glob = glob;
32524
32525function extend (origin, add) {
32526 if (add === null || typeof add !== 'object') {
32527 return origin
32528 }
32529
32530 var keys = Object.keys(add);
32531 var i = keys.length;
32532 while (i--) {
32533 origin[keys[i]] = add[keys[i]];
32534 }
32535 return origin
32536}
32537
32538glob.hasMagic = function (pattern, options_) {
32539 var options = extend({}, options_);
32540 options.noprocess = true;
32541
32542 var g = new Glob(pattern, options);
32543 var set = g.minimatch.set;
32544
32545 if (!pattern)
32546 return false
32547
32548 if (set.length > 1)
32549 return true
32550
32551 for (var j = 0; j < set[0].length; j++) {
32552 if (typeof set[0][j] !== 'string')
32553 return true
32554 }
32555
32556 return false
32557};
32558
32559glob.Glob = Glob;
32560inherits(Glob, EE$1);
32561function Glob (pattern, options, cb) {
32562 if (typeof options === 'function') {
32563 cb = options;
32564 options = null;
32565 }
32566
32567 if (options && options.sync) {
32568 if (cb)
32569 throw new TypeError('callback provided to sync glob')
32570 return new GlobSync(pattern, options)
32571 }
32572
32573 if (!(this instanceof Glob))
32574 return new Glob(pattern, options, cb)
32575
32576 setopts(this, pattern, options);
32577 this._didRealPath = false;
32578
32579 // process each pattern in the minimatch set
32580 var n = this.minimatch.set.length;
32581
32582 // The matches are stored as {<filename>: true,...} so that
32583 // duplicates are automagically pruned.
32584 // Later, we do an Object.keys() on these.
32585 // Keep them as a list so we can fill in when nonull is set.
32586 this.matches = new Array(n);
32587
32588 if (typeof cb === 'function') {
32589 cb = once(cb);
32590 this.on('error', cb);
32591 this.on('end', function (matches) {
32592 cb(null, matches);
32593 });
32594 }
32595
32596 var self = this;
32597 this._processing = 0;
32598
32599 this._emitQueue = [];
32600 this._processQueue = [];
32601 this.paused = false;
32602
32603 if (this.noprocess)
32604 return this
32605
32606 if (n === 0)
32607 return done()
32608
32609 var sync = true;
32610 for (var i = 0; i < n; i ++) {
32611 this._process(this.minimatch.set[i], i, false, done);
32612 }
32613 sync = false;
32614
32615 function done () {
32616 --self._processing;
32617 if (self._processing <= 0) {
32618 if (sync) {
32619 process.nextTick(function () {
32620 self._finish();
32621 });
32622 } else {
32623 self._finish();
32624 }
32625 }
32626 }
32627}
32628
32629Glob.prototype._finish = function () {
32630 assert$2(this instanceof Glob);
32631 if (this.aborted)
32632 return
32633
32634 if (this.realpath && !this._didRealpath)
32635 return this._realpath()
32636
32637 common$5.finish(this);
32638 this.emit('end', this.found);
32639};
32640
32641Glob.prototype._realpath = function () {
32642 if (this._didRealpath)
32643 return
32644
32645 this._didRealpath = true;
32646
32647 var n = this.matches.length;
32648 if (n === 0)
32649 return this._finish()
32650
32651 var self = this;
32652 for (var i = 0; i < this.matches.length; i++)
32653 this._realpathSet(i, next);
32654
32655 function next () {
32656 if (--n === 0)
32657 self._finish();
32658 }
32659};
32660
32661Glob.prototype._realpathSet = function (index, cb) {
32662 var matchset = this.matches[index];
32663 if (!matchset)
32664 return cb()
32665
32666 var found = Object.keys(matchset);
32667 var self = this;
32668 var n = found.length;
32669
32670 if (n === 0)
32671 return cb()
32672
32673 var set = this.matches[index] = Object.create(null);
32674 found.forEach(function (p, i) {
32675 // If there's a problem with the stat, then it means that
32676 // one or more of the links in the realpath couldn't be
32677 // resolved. just return the abs value in that case.
32678 p = self._makeAbs(p);
32679 rp.realpath(p, self.realpathCache, function (er, real) {
32680 if (!er)
32681 set[real] = true;
32682 else if (er.syscall === 'stat')
32683 set[p] = true;
32684 else
32685 self.emit('error', er); // srsly wtf right here
32686
32687 if (--n === 0) {
32688 self.matches[index] = set;
32689 cb();
32690 }
32691 });
32692 });
32693};
32694
32695Glob.prototype._mark = function (p) {
32696 return common$5.mark(this, p)
32697};
32698
32699Glob.prototype._makeAbs = function (f) {
32700 return common$5.makeAbs(this, f)
32701};
32702
32703Glob.prototype.abort = function () {
32704 this.aborted = true;
32705 this.emit('abort');
32706};
32707
32708Glob.prototype.pause = function () {
32709 if (!this.paused) {
32710 this.paused = true;
32711 this.emit('pause');
32712 }
32713};
32714
32715Glob.prototype.resume = function () {
32716 if (this.paused) {
32717 this.emit('resume');
32718 this.paused = false;
32719 if (this._emitQueue.length) {
32720 var eq = this._emitQueue.slice(0);
32721 this._emitQueue.length = 0;
32722 for (var i = 0; i < eq.length; i ++) {
32723 var e = eq[i];
32724 this._emitMatch(e[0], e[1]);
32725 }
32726 }
32727 if (this._processQueue.length) {
32728 var pq = this._processQueue.slice(0);
32729 this._processQueue.length = 0;
32730 for (var i = 0; i < pq.length; i ++) {
32731 var p = pq[i];
32732 this._processing--;
32733 this._process(p[0], p[1], p[2], p[3]);
32734 }
32735 }
32736 }
32737};
32738
32739Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
32740 assert$2(this instanceof Glob);
32741 assert$2(typeof cb === 'function');
32742
32743 if (this.aborted)
32744 return
32745
32746 this._processing++;
32747 if (this.paused) {
32748 this._processQueue.push([pattern, index, inGlobStar, cb]);
32749 return
32750 }
32751
32752 //console.error('PROCESS %d', this._processing, pattern)
32753
32754 // Get the first [n] parts of pattern that are all strings.
32755 var n = 0;
32756 while (typeof pattern[n] === 'string') {
32757 n ++;
32758 }
32759 // now n is the index of the first one that is *not* a string.
32760
32761 // see if there's anything else
32762 var prefix;
32763 switch (n) {
32764 // if not, then this is rather simple
32765 case pattern.length:
32766 this._processSimple(pattern.join('/'), index, cb);
32767 return
32768
32769 case 0:
32770 // pattern *starts* with some non-trivial item.
32771 // going to readdir(cwd), but not include the prefix in matches.
32772 prefix = null;
32773 break
32774
32775 default:
32776 // pattern has some string bits in the front.
32777 // whatever it starts with, whether that's 'absolute' like /foo/bar,
32778 // or 'relative' like '../baz'
32779 prefix = pattern.slice(0, n).join('/');
32780 break
32781 }
32782
32783 var remain = pattern.slice(n);
32784
32785 // get the list of entries.
32786 var read;
32787 if (prefix === null)
32788 read = '.';
32789 else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) {
32790 if (!prefix || !isAbsolute(prefix))
32791 prefix = '/' + prefix;
32792 read = prefix;
32793 } else
32794 read = prefix;
32795
32796 var abs = this._makeAbs(read);
32797
32798 //if ignored, skip _processing
32799 if (childrenIgnored(this, read))
32800 return cb()
32801
32802 var isGlobStar = remain[0] === minimatch.GLOBSTAR;
32803 if (isGlobStar)
32804 this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb);
32805 else
32806 this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb);
32807};
32808
32809Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
32810 var self = this;
32811 this._readdir(abs, inGlobStar, function (er, entries) {
32812 return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
32813 });
32814};
32815
32816Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
32817
32818 // if the abs isn't a dir, then nothing can match!
32819 if (!entries)
32820 return cb()
32821
32822 // It will only match dot entries if it starts with a dot, or if
32823 // dot is set. Stuff like @(.foo|.bar) isn't allowed.
32824 var pn = remain[0];
32825 var negate = !!this.minimatch.negate;
32826 var rawGlob = pn._glob;
32827 var dotOk = this.dot || rawGlob.charAt(0) === '.';
32828
32829 var matchedEntries = [];
32830 for (var i = 0; i < entries.length; i++) {
32831 var e = entries[i];
32832 if (e.charAt(0) !== '.' || dotOk) {
32833 var m;
32834 if (negate && !prefix) {
32835 m = !e.match(pn);
32836 } else {
32837 m = e.match(pn);
32838 }
32839 if (m)
32840 matchedEntries.push(e);
32841 }
32842 }
32843
32844 //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
32845
32846 var len = matchedEntries.length;
32847 // If there are no matched entries, then nothing matches.
32848 if (len === 0)
32849 return cb()
32850
32851 // if this is the last remaining pattern bit, then no need for
32852 // an additional stat *unless* the user has specified mark or
32853 // stat explicitly. We know they exist, since readdir returned
32854 // them.
32855
32856 if (remain.length === 1 && !this.mark && !this.stat) {
32857 if (!this.matches[index])
32858 this.matches[index] = Object.create(null);
32859
32860 for (var i = 0; i < len; i ++) {
32861 var e = matchedEntries[i];
32862 if (prefix) {
32863 if (prefix !== '/')
32864 e = prefix + '/' + e;
32865 else
32866 e = prefix + e;
32867 }
32868
32869 if (e.charAt(0) === '/' && !this.nomount) {
32870 e = path$j.join(this.root, e);
32871 }
32872 this._emitMatch(index, e);
32873 }
32874 // This was the last one, and no stats were needed
32875 return cb()
32876 }
32877
32878 // now test all matched entries as stand-ins for that part
32879 // of the pattern.
32880 remain.shift();
32881 for (var i = 0; i < len; i ++) {
32882 var e = matchedEntries[i];
32883 if (prefix) {
32884 if (prefix !== '/')
32885 e = prefix + '/' + e;
32886 else
32887 e = prefix + e;
32888 }
32889 this._process([e].concat(remain), index, inGlobStar, cb);
32890 }
32891 cb();
32892};
32893
32894Glob.prototype._emitMatch = function (index, e) {
32895 if (this.aborted)
32896 return
32897
32898 if (isIgnored(this, e))
32899 return
32900
32901 if (this.paused) {
32902 this._emitQueue.push([index, e]);
32903 return
32904 }
32905
32906 var abs = isAbsolute(e) ? e : this._makeAbs(e);
32907
32908 if (this.mark)
32909 e = this._mark(e);
32910
32911 if (this.absolute)
32912 e = abs;
32913
32914 if (this.matches[index][e])
32915 return
32916
32917 if (this.nodir) {
32918 var c = this.cache[abs];
32919 if (c === 'DIR' || Array.isArray(c))
32920 return
32921 }
32922
32923 this.matches[index][e] = true;
32924
32925 var st = this.statCache[abs];
32926 if (st)
32927 this.emit('stat', e, st);
32928
32929 this.emit('match', e);
32930};
32931
32932Glob.prototype._readdirInGlobStar = function (abs, cb) {
32933 if (this.aborted)
32934 return
32935
32936 // follow all symlinked directories forever
32937 // just proceed as if this is a non-globstar situation
32938 if (this.follow)
32939 return this._readdir(abs, false, cb)
32940
32941 var lstatkey = 'lstat\0' + abs;
32942 var self = this;
32943 var lstatcb = inflight(lstatkey, lstatcb_);
32944
32945 if (lstatcb)
32946 fs$h.lstat(abs, lstatcb);
32947
32948 function lstatcb_ (er, lstat) {
32949 if (er && er.code === 'ENOENT')
32950 return cb()
32951
32952 var isSym = lstat && lstat.isSymbolicLink();
32953 self.symlinks[abs] = isSym;
32954
32955 // If it's not a symlink or a dir, then it's definitely a regular file.
32956 // don't bother doing a readdir in that case.
32957 if (!isSym && lstat && !lstat.isDirectory()) {
32958 self.cache[abs] = 'FILE';
32959 cb();
32960 } else
32961 self._readdir(abs, false, cb);
32962 }
32963};
32964
32965Glob.prototype._readdir = function (abs, inGlobStar, cb) {
32966 if (this.aborted)
32967 return
32968
32969 cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb);
32970 if (!cb)
32971 return
32972
32973 //console.error('RD %j %j', +inGlobStar, abs)
32974 if (inGlobStar && !ownProp(this.symlinks, abs))
32975 return this._readdirInGlobStar(abs, cb)
32976
32977 if (ownProp(this.cache, abs)) {
32978 var c = this.cache[abs];
32979 if (!c || c === 'FILE')
32980 return cb()
32981
32982 if (Array.isArray(c))
32983 return cb(null, c)
32984 }
32985 fs$h.readdir(abs, readdirCb(this, abs, cb));
32986};
32987
32988function readdirCb (self, abs, cb) {
32989 return function (er, entries) {
32990 if (er)
32991 self._readdirError(abs, er, cb);
32992 else
32993 self._readdirEntries(abs, entries, cb);
32994 }
32995}
32996
32997Glob.prototype._readdirEntries = function (abs, entries, cb) {
32998 if (this.aborted)
32999 return
33000
33001 // if we haven't asked to stat everything, then just
33002 // assume that everything in there exists, so we can avoid
33003 // having to stat it a second time.
33004 if (!this.mark && !this.stat) {
33005 for (var i = 0; i < entries.length; i ++) {
33006 var e = entries[i];
33007 if (abs === '/')
33008 e = abs + e;
33009 else
33010 e = abs + '/' + e;
33011 this.cache[e] = true;
33012 }
33013 }
33014
33015 this.cache[abs] = entries;
33016 return cb(null, entries)
33017};
33018
33019Glob.prototype._readdirError = function (f, er, cb) {
33020 if (this.aborted)
33021 return
33022
33023 // handle errors, and cache the information
33024 switch (er.code) {
33025 case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
33026 case 'ENOTDIR': // totally normal. means it *does* exist.
33027 var abs = this._makeAbs(f);
33028 this.cache[abs] = 'FILE';
33029 if (abs === this.cwdAbs) {
33030 var error = new Error(er.code + ' invalid cwd ' + this.cwd);
33031 error.path = this.cwd;
33032 error.code = er.code;
33033 this.emit('error', error);
33034 this.abort();
33035 }
33036 break
33037
33038 case 'ENOENT': // not terribly unusual
33039 case 'ELOOP':
33040 case 'ENAMETOOLONG':
33041 case 'UNKNOWN':
33042 this.cache[this._makeAbs(f)] = false;
33043 break
33044
33045 default: // some unusual error. Treat as failure.
33046 this.cache[this._makeAbs(f)] = false;
33047 if (this.strict) {
33048 this.emit('error', er);
33049 // If the error is handled, then we abort
33050 // if not, we threw out of here
33051 this.abort();
33052 }
33053 if (!this.silent)
33054 console.error('glob error', er);
33055 break
33056 }
33057
33058 return cb()
33059};
33060
33061Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
33062 var self = this;
33063 this._readdir(abs, inGlobStar, function (er, entries) {
33064 self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb);
33065 });
33066};
33067
33068
33069Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
33070 //console.error('pgs2', prefix, remain[0], entries)
33071
33072 // no entries means not a dir, so it can never have matches
33073 // foo.txt/** doesn't match foo.txt
33074 if (!entries)
33075 return cb()
33076
33077 // test without the globstar, and with every child both below
33078 // and replacing the globstar.
33079 var remainWithoutGlobStar = remain.slice(1);
33080 var gspref = prefix ? [ prefix ] : [];
33081 var noGlobStar = gspref.concat(remainWithoutGlobStar);
33082
33083 // the noGlobStar pattern exits the inGlobStar state
33084 this._process(noGlobStar, index, false, cb);
33085
33086 var isSym = this.symlinks[abs];
33087 var len = entries.length;
33088
33089 // If it's a symlink, and we're in a globstar, then stop
33090 if (isSym && inGlobStar)
33091 return cb()
33092
33093 for (var i = 0; i < len; i++) {
33094 var e = entries[i];
33095 if (e.charAt(0) === '.' && !this.dot)
33096 continue
33097
33098 // these two cases enter the inGlobStar state
33099 var instead = gspref.concat(entries[i], remainWithoutGlobStar);
33100 this._process(instead, index, true, cb);
33101
33102 var below = gspref.concat(entries[i], remain);
33103 this._process(below, index, true, cb);
33104 }
33105
33106 cb();
33107};
33108
33109Glob.prototype._processSimple = function (prefix, index, cb) {
33110 // XXX review this. Shouldn't it be doing the mounting etc
33111 // before doing stat? kinda weird?
33112 var self = this;
33113 this._stat(prefix, function (er, exists) {
33114 self._processSimple2(prefix, index, er, exists, cb);
33115 });
33116};
33117Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
33118
33119 //console.error('ps2', prefix, exists)
33120
33121 if (!this.matches[index])
33122 this.matches[index] = Object.create(null);
33123
33124 // If it doesn't exist, then just mark the lack of results
33125 if (!exists)
33126 return cb()
33127
33128 if (prefix && isAbsolute(prefix) && !this.nomount) {
33129 var trail = /[\/\\]$/.test(prefix);
33130 if (prefix.charAt(0) === '/') {
33131 prefix = path$j.join(this.root, prefix);
33132 } else {
33133 prefix = path$j.resolve(this.root, prefix);
33134 if (trail)
33135 prefix += '/';
33136 }
33137 }
33138
33139 if (process.platform === 'win32')
33140 prefix = prefix.replace(/\\/g, '/');
33141
33142 // Mark this as a match
33143 this._emitMatch(index, prefix);
33144 cb();
33145};
33146
33147// Returns either 'DIR', 'FILE', or false
33148Glob.prototype._stat = function (f, cb) {
33149 var abs = this._makeAbs(f);
33150 var needDir = f.slice(-1) === '/';
33151
33152 if (f.length > this.maxLength)
33153 return cb()
33154
33155 if (!this.stat && ownProp(this.cache, abs)) {
33156 var c = this.cache[abs];
33157
33158 if (Array.isArray(c))
33159 c = 'DIR';
33160
33161 // It exists, but maybe not how we need it
33162 if (!needDir || c === 'DIR')
33163 return cb(null, c)
33164
33165 if (needDir && c === 'FILE')
33166 return cb()
33167
33168 // otherwise we have to stat, because maybe c=true
33169 // if we know it exists, but not what it is.
33170 }
33171 var stat = this.statCache[abs];
33172 if (stat !== undefined) {
33173 if (stat === false)
33174 return cb(null, stat)
33175 else {
33176 var type = stat.isDirectory() ? 'DIR' : 'FILE';
33177 if (needDir && type === 'FILE')
33178 return cb()
33179 else
33180 return cb(null, type, stat)
33181 }
33182 }
33183
33184 var self = this;
33185 var statcb = inflight('stat\0' + abs, lstatcb_);
33186 if (statcb)
33187 fs$h.lstat(abs, statcb);
33188
33189 function lstatcb_ (er, lstat) {
33190 if (lstat && lstat.isSymbolicLink()) {
33191 // If it's a symlink, then treat it as the target, unless
33192 // the target does not exist, then treat it as a file.
33193 return fs$h.stat(abs, function (er, stat) {
33194 if (er)
33195 self._stat2(f, abs, null, lstat, cb);
33196 else
33197 self._stat2(f, abs, er, stat, cb);
33198 })
33199 } else {
33200 self._stat2(f, abs, er, lstat, cb);
33201 }
33202 }
33203};
33204
33205Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
33206 if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
33207 this.statCache[abs] = false;
33208 return cb()
33209 }
33210
33211 var needDir = f.slice(-1) === '/';
33212 this.statCache[abs] = stat;
33213
33214 if (abs.slice(-1) === '/' && stat && !stat.isDirectory())
33215 return cb(null, false, stat)
33216
33217 var c = true;
33218 if (stat)
33219 c = stat.isDirectory() ? 'DIR' : 'FILE';
33220 this.cache[abs] = this.cache[abs] || c;
33221
33222 if (needDir && c === 'FILE')
33223 return cb()
33224
33225 return cb(null, c, stat)
33226};
33227
33228// @ts-check
33229/** @typedef { import('estree').BaseNode} BaseNode */
33230
33231/** @typedef {{
33232 skip: () => void;
33233 remove: () => void;
33234 replace: (node: BaseNode) => void;
33235}} WalkerContext */
33236
33237class WalkerBase {
33238 constructor() {
33239 /** @type {boolean} */
33240 this.should_skip = false;
33241
33242 /** @type {boolean} */
33243 this.should_remove = false;
33244
33245 /** @type {BaseNode | null} */
33246 this.replacement = null;
33247
33248 /** @type {WalkerContext} */
33249 this.context = {
33250 skip: () => (this.should_skip = true),
33251 remove: () => (this.should_remove = true),
33252 replace: (node) => (this.replacement = node)
33253 };
33254 }
33255
33256 /**
33257 *
33258 * @param {any} parent
33259 * @param {string} prop
33260 * @param {number} index
33261 * @param {BaseNode} node
33262 */
33263 replace(parent, prop, index, node) {
33264 if (parent) {
33265 if (index !== null) {
33266 parent[prop][index] = node;
33267 } else {
33268 parent[prop] = node;
33269 }
33270 }
33271 }
33272
33273 /**
33274 *
33275 * @param {any} parent
33276 * @param {string} prop
33277 * @param {number} index
33278 */
33279 remove(parent, prop, index) {
33280 if (parent) {
33281 if (index !== null) {
33282 parent[prop].splice(index, 1);
33283 } else {
33284 delete parent[prop];
33285 }
33286 }
33287 }
33288}
33289
33290// @ts-check
33291
33292/** @typedef { import('estree').BaseNode} BaseNode */
33293/** @typedef { import('./walker.js').WalkerContext} WalkerContext */
33294
33295/** @typedef {(
33296 * this: WalkerContext,
33297 * node: BaseNode,
33298 * parent: BaseNode,
33299 * key: string,
33300 * index: number
33301 * ) => void} SyncHandler */
33302
33303class SyncWalker extends WalkerBase {
33304 /**
33305 *
33306 * @param {SyncHandler} enter
33307 * @param {SyncHandler} leave
33308 */
33309 constructor(enter, leave) {
33310 super();
33311
33312 /** @type {SyncHandler} */
33313 this.enter = enter;
33314
33315 /** @type {SyncHandler} */
33316 this.leave = leave;
33317 }
33318
33319 /**
33320 *
33321 * @param {BaseNode} node
33322 * @param {BaseNode} parent
33323 * @param {string} [prop]
33324 * @param {number} [index]
33325 * @returns {BaseNode}
33326 */
33327 visit(node, parent, prop, index) {
33328 if (node) {
33329 if (this.enter) {
33330 const _should_skip = this.should_skip;
33331 const _should_remove = this.should_remove;
33332 const _replacement = this.replacement;
33333 this.should_skip = false;
33334 this.should_remove = false;
33335 this.replacement = null;
33336
33337 this.enter.call(this.context, node, parent, prop, index);
33338
33339 if (this.replacement) {
33340 node = this.replacement;
33341 this.replace(parent, prop, index, node);
33342 }
33343
33344 if (this.should_remove) {
33345 this.remove(parent, prop, index);
33346 }
33347
33348 const skipped = this.should_skip;
33349 const removed = this.should_remove;
33350
33351 this.should_skip = _should_skip;
33352 this.should_remove = _should_remove;
33353 this.replacement = _replacement;
33354
33355 if (skipped) return node;
33356 if (removed) return null;
33357 }
33358
33359 for (const key in node) {
33360 const value = node[key];
33361
33362 if (typeof value !== "object") {
33363 continue;
33364 } else if (Array.isArray(value)) {
33365 for (let i = 0; i < value.length; i += 1) {
33366 if (value[i] !== null && typeof value[i].type === 'string') {
33367 if (!this.visit(value[i], node, key, i)) {
33368 // removed
33369 i--;
33370 }
33371 }
33372 }
33373 } else if (value !== null && typeof value.type === "string") {
33374 this.visit(value, node, key, null);
33375 }
33376 }
33377
33378 if (this.leave) {
33379 const _replacement = this.replacement;
33380 const _should_remove = this.should_remove;
33381 this.replacement = null;
33382 this.should_remove = false;
33383
33384 this.leave.call(this.context, node, parent, prop, index);
33385
33386 if (this.replacement) {
33387 node = this.replacement;
33388 this.replace(parent, prop, index, node);
33389 }
33390
33391 if (this.should_remove) {
33392 this.remove(parent, prop, index);
33393 }
33394
33395 const removed = this.should_remove;
33396
33397 this.replacement = _replacement;
33398 this.should_remove = _should_remove;
33399
33400 if (removed) return null;
33401 }
33402 }
33403
33404 return node;
33405 }
33406}
33407
33408// @ts-check
33409
33410/** @typedef { import('estree').BaseNode} BaseNode */
33411/** @typedef { import('./sync.js').SyncHandler} SyncHandler */
33412/** @typedef { import('./async.js').AsyncHandler} AsyncHandler */
33413
33414/**
33415 *
33416 * @param {BaseNode} ast
33417 * @param {{
33418 * enter?: SyncHandler
33419 * leave?: SyncHandler
33420 * }} walker
33421 * @returns {BaseNode}
33422 */
33423function walk$1(ast, { enter, leave }) {
33424 const instance = new SyncWalker(enter, leave);
33425 return instance.visit(ast, null);
33426}
33427
33428function isReference(node, parent) {
33429 if (node.type === 'MemberExpression') {
33430 return !node.computed && isReference(node.object, node);
33431 }
33432 if (node.type === 'Identifier') {
33433 if (!parent)
33434 return true;
33435 switch (parent.type) {
33436 // disregard `bar` in `foo.bar`
33437 case 'MemberExpression': return parent.computed || node === parent.object;
33438 // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
33439 case 'MethodDefinition': return parent.computed;
33440 // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
33441 case 'FieldDefinition': return parent.computed || node === parent.value;
33442 // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
33443 case 'Property': return parent.computed || node === parent.value;
33444 // disregard the `bar` in `export { foo as bar }` or
33445 // the foo in `import { foo as bar }`
33446 case 'ExportSpecifier':
33447 case 'ImportSpecifier': return node === parent.local;
33448 // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
33449 case 'LabeledStatement':
33450 case 'BreakStatement':
33451 case 'ContinueStatement': return false;
33452 default: return true;
33453 }
33454 }
33455 return false;
33456}
33457
33458var peerDependencies = {
33459 rollup: "^2.38.3"
33460};
33461
33462function tryParse(parse, code, id) {
33463 try {
33464 return parse(code, { allowReturnOutsideFunction: true });
33465 } catch (err) {
33466 err.message += ` in ${id}`;
33467 throw err;
33468 }
33469}
33470
33471const firstpassGlobal = /\b(?:require|module|exports|global)\b/;
33472
33473const firstpassNoGlobal = /\b(?:require|module|exports)\b/;
33474
33475function hasCjsKeywords(code, ignoreGlobal) {
33476 const firstpass = ignoreGlobal ? firstpassNoGlobal : firstpassGlobal;
33477 return firstpass.test(code);
33478}
33479
33480/* eslint-disable no-underscore-dangle */
33481
33482function analyzeTopLevelStatements(parse, code, id) {
33483 const ast = tryParse(parse, code, id);
33484
33485 let isEsModule = false;
33486 let hasDefaultExport = false;
33487 let hasNamedExports = false;
33488
33489 for (const node of ast.body) {
33490 switch (node.type) {
33491 case 'ExportDefaultDeclaration':
33492 isEsModule = true;
33493 hasDefaultExport = true;
33494 break;
33495 case 'ExportNamedDeclaration':
33496 isEsModule = true;
33497 if (node.declaration) {
33498 hasNamedExports = true;
33499 } else {
33500 for (const specifier of node.specifiers) {
33501 if (specifier.exported.name === 'default') {
33502 hasDefaultExport = true;
33503 } else {
33504 hasNamedExports = true;
33505 }
33506 }
33507 }
33508 break;
33509 case 'ExportAllDeclaration':
33510 isEsModule = true;
33511 if (node.exported && node.exported.name === 'default') {
33512 hasDefaultExport = true;
33513 } else {
33514 hasNamedExports = true;
33515 }
33516 break;
33517 case 'ImportDeclaration':
33518 isEsModule = true;
33519 break;
33520 }
33521 }
33522
33523 return { isEsModule, hasDefaultExport, hasNamedExports, ast };
33524}
33525
33526const isWrappedId = (id, suffix) => id.endsWith(suffix);
33527const wrapId = (id, suffix) => `\0${id}${suffix}`;
33528const unwrapId = (wrappedId, suffix) => wrappedId.slice(1, -suffix.length);
33529
33530const PROXY_SUFFIX = '?commonjs-proxy';
33531const REQUIRE_SUFFIX = '?commonjs-require';
33532const EXTERNAL_SUFFIX = '?commonjs-external';
33533const EXPORTS_SUFFIX = '?commonjs-exports';
33534const MODULE_SUFFIX = '?commonjs-module';
33535
33536const DYNAMIC_REGISTER_SUFFIX = '?commonjs-dynamic-register';
33537const DYNAMIC_JSON_PREFIX = '\0commonjs-dynamic-json:';
33538const DYNAMIC_PACKAGES_ID = '\0commonjs-dynamic-packages';
33539
33540const HELPERS_ID = '\0commonjsHelpers.js';
33541
33542// `x['default']` is used instead of `x.default` for backward compatibility with ES3 browsers.
33543// Minifiers like uglify will usually transpile it back if compatibility with ES3 is not enabled.
33544// This will no longer be necessary once Rollup switches to ES6 output, likely
33545// in Rollup 3
33546
33547const HELPERS = `
33548export var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
33549
33550export function getDefaultExportFromCjs (x) {
33551 return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
33552}
33553
33554export function getDefaultExportFromNamespaceIfPresent (n) {
33555 return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n;
33556}
33557
33558export function getDefaultExportFromNamespaceIfNotNamed (n) {
33559 return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n;
33560}
33561
33562export function getAugmentedNamespace(n) {
33563 if (n.__esModule) return n;
33564 var a = Object.defineProperty({}, '__esModule', {value: true});
33565 Object.keys(n).forEach(function (k) {
33566 var d = Object.getOwnPropertyDescriptor(n, k);
33567 Object.defineProperty(a, k, d.get ? d : {
33568 enumerable: true,
33569 get: function () {
33570 return n[k];
33571 }
33572 });
33573 });
33574 return a;
33575}
33576`;
33577
33578const FAILED_REQUIRE_ERROR = `throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');`;
33579
33580const HELPER_NON_DYNAMIC = `
33581export function commonjsRequire (path) {
33582 ${FAILED_REQUIRE_ERROR}
33583}
33584`;
33585
33586const getDynamicHelpers = (ignoreDynamicRequires) => `
33587export function createModule(modulePath) {
33588 return {
33589 path: modulePath,
33590 exports: {},
33591 require: function (path, base) {
33592 return commonjsRequire(path, base == null ? modulePath : base);
33593 }
33594 };
33595}
33596
33597export function commonjsRegister (path, loader) {
33598 DYNAMIC_REQUIRE_LOADERS[path] = loader;
33599}
33600
33601const DYNAMIC_REQUIRE_LOADERS = Object.create(null);
33602const DYNAMIC_REQUIRE_CACHE = Object.create(null);
33603const DEFAULT_PARENT_MODULE = {
33604 id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []
33605};
33606const CHECKED_EXTENSIONS = ['', '.js', '.json'];
33607
33608function normalize (path) {
33609 path = path.replace(/\\\\/g, '/');
33610 const parts = path.split('/');
33611 const slashed = parts[0] === '';
33612 for (let i = 1; i < parts.length; i++) {
33613 if (parts[i] === '.' || parts[i] === '') {
33614 parts.splice(i--, 1);
33615 }
33616 }
33617 for (let i = 1; i < parts.length; i++) {
33618 if (parts[i] !== '..') continue;
33619 if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {
33620 parts.splice(--i, 2);
33621 i--;
33622 }
33623 }
33624 path = parts.join('/');
33625 if (slashed && path[0] !== '/')
33626 path = '/' + path;
33627 else if (path.length === 0)
33628 path = '.';
33629 return path;
33630}
33631
33632function join () {
33633 if (arguments.length === 0)
33634 return '.';
33635 let joined;
33636 for (let i = 0; i < arguments.length; ++i) {
33637 let arg = arguments[i];
33638 if (arg.length > 0) {
33639 if (joined === undefined)
33640 joined = arg;
33641 else
33642 joined += '/' + arg;
33643 }
33644 }
33645 if (joined === undefined)
33646 return '.';
33647
33648 return joined;
33649}
33650
33651function isPossibleNodeModulesPath (modulePath) {
33652 let c0 = modulePath[0];
33653 if (c0 === '/' || c0 === '\\\\') return false;
33654 let c1 = modulePath[1], c2 = modulePath[2];
33655 if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||
33656 (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;
33657 if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))
33658 return false;
33659 return true;
33660}
33661
33662function dirname (path) {
33663 if (path.length === 0)
33664 return '.';
33665
33666 let i = path.length - 1;
33667 while (i > 0) {
33668 const c = path.charCodeAt(i);
33669 if ((c === 47 || c === 92) && i !== path.length - 1)
33670 break;
33671 i--;
33672 }
33673
33674 if (i > 0)
33675 return path.substr(0, i);
33676
33677 if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)
33678 return path.charAt(0);
33679
33680 return '.';
33681}
33682
33683export function commonjsResolveImpl (path, originalModuleDir, testCache) {
33684 const shouldTryNodeModules = isPossibleNodeModulesPath(path);
33685 path = normalize(path);
33686 let relPath;
33687 if (path[0] === '/') {
33688 originalModuleDir = '/';
33689 }
33690 while (true) {
33691 if (!shouldTryNodeModules) {
33692 relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;
33693 } else if (originalModuleDir) {
33694 relPath = normalize(originalModuleDir + '/node_modules/' + path);
33695 } else {
33696 relPath = normalize(join('node_modules', path));
33697 }
33698
33699 if (relPath.endsWith('/..')) {
33700 break; // Travelled too far up, avoid infinite loop
33701 }
33702
33703 for (let extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {
33704 const resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];
33705 if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {
33706 return resolvedPath;
33707 };
33708 if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {
33709 return resolvedPath;
33710 };
33711 }
33712 if (!shouldTryNodeModules) break;
33713 const nextDir = normalize(originalModuleDir + '/..');
33714 if (nextDir === originalModuleDir) break;
33715 originalModuleDir = nextDir;
33716 }
33717 return null;
33718}
33719
33720export function commonjsResolve (path, originalModuleDir) {
33721 const resolvedPath = commonjsResolveImpl(path, originalModuleDir);
33722 if (resolvedPath !== null) {
33723 return resolvedPath;
33724 }
33725 return require.resolve(path);
33726}
33727
33728export function commonjsRequire (path, originalModuleDir) {
33729 const resolvedPath = commonjsResolveImpl(path, originalModuleDir, true);
33730 if (resolvedPath !== null) {
33731 let cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];
33732 if (cachedModule) return cachedModule.exports;
33733 const loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];
33734 if (loader) {
33735 DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {
33736 id: resolvedPath,
33737 filename: resolvedPath,
33738 path: dirname(resolvedPath),
33739 exports: {},
33740 parent: DEFAULT_PARENT_MODULE,
33741 loaded: false,
33742 children: [],
33743 paths: [],
33744 require: function (path, base) {
33745 return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);
33746 }
33747 };
33748 try {
33749 loader.call(commonjsGlobal, cachedModule, cachedModule.exports);
33750 } catch (error) {
33751 delete DYNAMIC_REQUIRE_CACHE[resolvedPath];
33752 throw error;
33753 }
33754 cachedModule.loaded = true;
33755 return cachedModule.exports;
33756 };
33757 }
33758 ${ignoreDynamicRequires ? 'return require(path);' : FAILED_REQUIRE_ERROR}
33759}
33760
33761commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;
33762commonjsRequire.resolve = commonjsResolve;
33763`;
33764
33765function getHelpersModule(isDynamicRequireModulesEnabled, ignoreDynamicRequires) {
33766 return `${HELPERS}${
33767 isDynamicRequireModulesEnabled ? getDynamicHelpers(ignoreDynamicRequires) : HELPER_NON_DYNAMIC
33768 }`;
33769}
33770
33771/* eslint-disable import/prefer-default-export */
33772
33773function deconflict(scopes, globals, identifier) {
33774 let i = 1;
33775 let deconflicted = makeLegalIdentifier(identifier);
33776 const hasConflicts = () =>
33777 scopes.some((scope) => scope.contains(deconflicted)) || globals.has(deconflicted);
33778
33779 while (hasConflicts()) {
33780 deconflicted = makeLegalIdentifier(`${identifier}_${i}`);
33781 i += 1;
33782 }
33783
33784 for (const scope of scopes) {
33785 scope.declarations[deconflicted] = true;
33786 }
33787
33788 return deconflicted;
33789}
33790
33791function getName(id) {
33792 const name = makeLegalIdentifier(path$A.basename(id, path$A.extname(id)));
33793 if (name !== 'index') {
33794 return name;
33795 }
33796 const segments = path$A.dirname(id).split(path$A.sep);
33797 return makeLegalIdentifier(segments[segments.length - 1]);
33798}
33799
33800function normalizePathSlashes(path) {
33801 return path.replace(/\\/g, '/');
33802}
33803
33804const VIRTUAL_PATH_BASE = '/$$rollup_base$$';
33805const getVirtualPathForDynamicRequirePath = (path, commonDir) => {
33806 const normalizedPath = normalizePathSlashes(path);
33807 return normalizedPath.startsWith(commonDir)
33808 ? VIRTUAL_PATH_BASE + normalizedPath.slice(commonDir.length)
33809 : normalizedPath;
33810};
33811
33812function getPackageEntryPoint(dirPath) {
33813 let entryPoint = 'index.js';
33814
33815 try {
33816 if (fs$w.existsSync(path$A.join(dirPath, 'package.json'))) {
33817 entryPoint =
33818 JSON.parse(fs$w.readFileSync(path$A.join(dirPath, 'package.json'), { encoding: 'utf8' })).main ||
33819 entryPoint;
33820 }
33821 } catch (ignored) {
33822 // ignored
33823 }
33824
33825 return entryPoint;
33826}
33827
33828function getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir) {
33829 let code = `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');`;
33830 for (const dir of dynamicRequireModuleDirPaths) {
33831 const entryPoint = getPackageEntryPoint(dir);
33832
33833 code += `\ncommonjsRegister(${JSON.stringify(
33834 getVirtualPathForDynamicRequirePath(dir, commonDir)
33835 )}, function (module, exports) {
33836 module.exports = require(${JSON.stringify(normalizePathSlashes(path$A.join(dir, entryPoint)))});
33837});`;
33838 }
33839 return code;
33840}
33841
33842function getDynamicPackagesEntryIntro(
33843 dynamicRequireModuleDirPaths,
33844 dynamicRequireModuleSet
33845) {
33846 let dynamicImports = Array.from(
33847 dynamicRequireModuleSet,
33848 (dynamicId) => `require(${JSON.stringify(wrapId(dynamicId, DYNAMIC_REGISTER_SUFFIX))});`
33849 ).join('\n');
33850
33851 if (dynamicRequireModuleDirPaths.length) {
33852 dynamicImports += `require(${JSON.stringify(
33853 wrapId(DYNAMIC_PACKAGES_ID, DYNAMIC_REGISTER_SUFFIX)
33854 )});`;
33855 }
33856
33857 return dynamicImports;
33858}
33859
33860function isDynamicModuleImport(id, dynamicRequireModuleSet) {
33861 const normalizedPath = normalizePathSlashes(id);
33862 return dynamicRequireModuleSet.has(normalizedPath) && !normalizedPath.endsWith('.json');
33863}
33864
33865function isDirectory(path) {
33866 try {
33867 if (fs$w.statSync(path).isDirectory()) return true;
33868 } catch (ignored) {
33869 // Nothing to do here
33870 }
33871 return false;
33872}
33873
33874function getDynamicRequirePaths(patterns) {
33875 const dynamicRequireModuleSet = new Set();
33876 for (const pattern of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) {
33877 const isNegated = pattern.startsWith('!');
33878 const modifySet = Set.prototype[isNegated ? 'delete' : 'add'].bind(dynamicRequireModuleSet);
33879 for (const path of glob_1.sync(isNegated ? pattern.substr(1) : pattern)) {
33880 modifySet(normalizePathSlashes(path$A.resolve(path)));
33881 if (isDirectory(path)) {
33882 modifySet(normalizePathSlashes(path$A.resolve(path$A.join(path, getPackageEntryPoint(path)))));
33883 }
33884 }
33885 }
33886 const dynamicRequireModuleDirPaths = Array.from(dynamicRequireModuleSet.values()).filter((path) =>
33887 isDirectory(path)
33888 );
33889 return { dynamicRequireModuleSet, dynamicRequireModuleDirPaths };
33890}
33891
33892function getCommonJSMetaPromise(commonJSMetaPromises, id) {
33893 let commonJSMetaPromise = commonJSMetaPromises.get(id);
33894 if (commonJSMetaPromise) return commonJSMetaPromise.promise;
33895
33896 const promise = new Promise((resolve) => {
33897 commonJSMetaPromise = {
33898 resolve,
33899 promise: null
33900 };
33901 commonJSMetaPromises.set(id, commonJSMetaPromise);
33902 });
33903 commonJSMetaPromise.promise = promise;
33904
33905 return promise;
33906}
33907
33908function setCommonJSMetaPromise(commonJSMetaPromises, id, commonjsMeta) {
33909 const commonJSMetaPromise = commonJSMetaPromises.get(id);
33910 if (commonJSMetaPromise) {
33911 if (commonJSMetaPromise.resolve) {
33912 commonJSMetaPromise.resolve(commonjsMeta);
33913 commonJSMetaPromise.resolve = null;
33914 }
33915 } else {
33916 commonJSMetaPromises.set(id, { promise: Promise.resolve(commonjsMeta), resolve: null });
33917 }
33918}
33919
33920// e.g. id === "commonjsHelpers?commonjsRegister"
33921function getSpecificHelperProxy(id) {
33922 return `export {${id.split('?')[1]} as default} from "${HELPERS_ID}";`;
33923}
33924
33925function getUnknownRequireProxy(id, requireReturnsDefault) {
33926 if (requireReturnsDefault === true || id.endsWith('.json')) {
33927 return `export {default} from ${JSON.stringify(id)};`;
33928 }
33929 const name = getName(id);
33930 const exported =
33931 requireReturnsDefault === 'auto'
33932 ? `import {getDefaultExportFromNamespaceIfNotNamed} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name});`
33933 : requireReturnsDefault === 'preferred'
33934 ? `import {getDefaultExportFromNamespaceIfPresent} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name});`
33935 : !requireReturnsDefault
33936 ? `import {getAugmentedNamespace} from "${HELPERS_ID}"; export default /*@__PURE__*/getAugmentedNamespace(${name});`
33937 : `export default ${name};`;
33938 return `import * as ${name} from ${JSON.stringify(id)}; ${exported}`;
33939}
33940
33941function getDynamicJsonProxy(id, commonDir) {
33942 const normalizedPath = normalizePathSlashes(id.slice(DYNAMIC_JSON_PREFIX.length));
33943 return `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');\ncommonjsRegister(${JSON.stringify(
33944 getVirtualPathForDynamicRequirePath(normalizedPath, commonDir)
33945 )}, function (module, exports) {
33946 module.exports = require(${JSON.stringify(normalizedPath)});
33947});`;
33948}
33949
33950function getDynamicRequireProxy(normalizedPath, commonDir) {
33951 return `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');\ncommonjsRegister(${JSON.stringify(
33952 getVirtualPathForDynamicRequirePath(normalizedPath, commonDir)
33953 )}, function (module, exports) {
33954 ${fs$w.readFileSync(normalizedPath, { encoding: 'utf8' })}
33955});`;
33956}
33957
33958async function getStaticRequireProxy(
33959 id,
33960 requireReturnsDefault,
33961 esModulesWithDefaultExport,
33962 esModulesWithNamedExports,
33963 commonJsMetaPromises
33964) {
33965 const name = getName(id);
33966 const commonjsMeta = await getCommonJSMetaPromise(commonJsMetaPromises, id);
33967 if (commonjsMeta && commonjsMeta.isCommonJS) {
33968 return `export { __moduleExports as default } from ${JSON.stringify(id)};`;
33969 } else if (commonjsMeta === null) {
33970 return getUnknownRequireProxy(id, requireReturnsDefault);
33971 } else if (!requireReturnsDefault) {
33972 return `import { getAugmentedNamespace } from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify(
33973 id
33974 )}; export default /*@__PURE__*/getAugmentedNamespace(${name});`;
33975 } else if (
33976 requireReturnsDefault !== true &&
33977 (requireReturnsDefault === 'namespace' ||
33978 !esModulesWithDefaultExport.has(id) ||
33979 (requireReturnsDefault === 'auto' && esModulesWithNamedExports.has(id)))
33980 ) {
33981 return `import * as ${name} from ${JSON.stringify(id)}; export default ${name};`;
33982 }
33983 return `export { default } from ${JSON.stringify(id)};`;
33984}
33985
33986/* eslint-disable no-param-reassign, no-undefined */
33987
33988function getCandidatesForExtension(resolved, extension) {
33989 return [resolved + extension, `${resolved}${path$A.sep}index${extension}`];
33990}
33991
33992function getCandidates(resolved, extensions) {
33993 return extensions.reduce(
33994 (paths, extension) => paths.concat(getCandidatesForExtension(resolved, extension)),
33995 [resolved]
33996 );
33997}
33998
33999function getResolveId(extensions) {
34000 function resolveExtensions(importee, importer) {
34001 // not our problem
34002 if (importee[0] !== '.' || !importer) return undefined;
34003
34004 const resolved = path$A.resolve(path$A.dirname(importer), importee);
34005 const candidates = getCandidates(resolved, extensions);
34006
34007 for (let i = 0; i < candidates.length; i += 1) {
34008 try {
34009 const stats = fs$w.statSync(candidates[i]);
34010 if (stats.isFile()) return { id: candidates[i] };
34011 } catch (err) {
34012 /* noop */
34013 }
34014 }
34015
34016 return undefined;
34017 }
34018
34019 return function resolveId(importee, rawImporter) {
34020 if (isWrappedId(importee, MODULE_SUFFIX) || isWrappedId(importee, EXPORTS_SUFFIX)) {
34021 return importee;
34022 }
34023
34024 const importer =
34025 rawImporter && isWrappedId(rawImporter, DYNAMIC_REGISTER_SUFFIX)
34026 ? unwrapId(rawImporter, DYNAMIC_REGISTER_SUFFIX)
34027 : rawImporter;
34028
34029 // Except for exports, proxies are only importing resolved ids,
34030 // no need to resolve again
34031 if (importer && isWrappedId(importer, PROXY_SUFFIX)) {
34032 return importee;
34033 }
34034
34035 const isProxyModule = isWrappedId(importee, PROXY_SUFFIX);
34036 const isRequiredModule = isWrappedId(importee, REQUIRE_SUFFIX);
34037 let isModuleRegistration = false;
34038
34039 if (isProxyModule) {
34040 importee = unwrapId(importee, PROXY_SUFFIX);
34041 } else if (isRequiredModule) {
34042 importee = unwrapId(importee, REQUIRE_SUFFIX);
34043
34044 isModuleRegistration = isWrappedId(importee, DYNAMIC_REGISTER_SUFFIX);
34045 if (isModuleRegistration) {
34046 importee = unwrapId(importee, DYNAMIC_REGISTER_SUFFIX);
34047 }
34048 }
34049
34050 if (
34051 importee.startsWith(HELPERS_ID) ||
34052 importee === DYNAMIC_PACKAGES_ID ||
34053 importee.startsWith(DYNAMIC_JSON_PREFIX)
34054 ) {
34055 return importee;
34056 }
34057
34058 if (importee.startsWith('\0')) {
34059 return null;
34060 }
34061
34062 return this.resolve(importee, importer, {
34063 skipSelf: true,
34064 custom: { 'node-resolve': { isRequire: isProxyModule || isRequiredModule } }
34065 }).then((resolved) => {
34066 if (!resolved) {
34067 resolved = resolveExtensions(importee, importer);
34068 }
34069 if (resolved && isProxyModule) {
34070 resolved.id = wrapId(resolved.id, resolved.external ? EXTERNAL_SUFFIX : PROXY_SUFFIX);
34071 resolved.external = false;
34072 } else if (resolved && isModuleRegistration) {
34073 resolved.id = wrapId(resolved.id, DYNAMIC_REGISTER_SUFFIX);
34074 } else if (!resolved && (isProxyModule || isRequiredModule)) {
34075 return { id: wrapId(importee, EXTERNAL_SUFFIX), external: false };
34076 }
34077 return resolved;
34078 });
34079 };
34080}
34081
34082function validateRollupVersion(rollupVersion, peerDependencyVersion) {
34083 const [major, minor] = rollupVersion.split('.').map(Number);
34084 const versionRegexp = /\^(\d+\.\d+)\.\d+/g;
34085 let minMajor = Infinity;
34086 let minMinor = Infinity;
34087 let foundVersion;
34088 // eslint-disable-next-line no-cond-assign
34089 while ((foundVersion = versionRegexp.exec(peerDependencyVersion))) {
34090 const [foundMajor, foundMinor] = foundVersion[1].split('.').map(Number);
34091 if (foundMajor < minMajor) {
34092 minMajor = foundMajor;
34093 minMinor = foundMinor;
34094 }
34095 }
34096 if (major < minMajor || (major === minMajor && minor < minMinor)) {
34097 throw new Error(
34098 `Insufficient Rollup version: "@rollup/plugin-commonjs" requires at least rollup@${minMajor}.${minMinor} but found rollup@${rollupVersion}.`
34099 );
34100 }
34101}
34102
34103const operators = {
34104 '==': (x) => equals(x.left, x.right, false),
34105
34106 '!=': (x) => not(operators['=='](x)),
34107
34108 '===': (x) => equals(x.left, x.right, true),
34109
34110 '!==': (x) => not(operators['==='](x)),
34111
34112 '!': (x) => isFalsy(x.argument),
34113
34114 '&&': (x) => isTruthy(x.left) && isTruthy(x.right),
34115
34116 '||': (x) => isTruthy(x.left) || isTruthy(x.right)
34117};
34118
34119function not(value) {
34120 return value === null ? value : !value;
34121}
34122
34123function equals(a, b, strict) {
34124 if (a.type !== b.type) return null;
34125 // eslint-disable-next-line eqeqeq
34126 if (a.type === 'Literal') return strict ? a.value === b.value : a.value == b.value;
34127 return null;
34128}
34129
34130function isTruthy(node) {
34131 if (!node) return false;
34132 if (node.type === 'Literal') return !!node.value;
34133 if (node.type === 'ParenthesizedExpression') return isTruthy(node.expression);
34134 if (node.operator in operators) return operators[node.operator](node);
34135 return null;
34136}
34137
34138function isFalsy(node) {
34139 return not(isTruthy(node));
34140}
34141
34142function getKeypath(node) {
34143 const parts = [];
34144
34145 while (node.type === 'MemberExpression') {
34146 if (node.computed) return null;
34147
34148 parts.unshift(node.property.name);
34149 // eslint-disable-next-line no-param-reassign
34150 node = node.object;
34151 }
34152
34153 if (node.type !== 'Identifier') return null;
34154
34155 const { name } = node;
34156 parts.unshift(name);
34157
34158 return { name, keypath: parts.join('.') };
34159}
34160
34161const KEY_COMPILED_ESM = '__esModule';
34162
34163function isDefineCompiledEsm(node) {
34164 const definedProperty =
34165 getDefinePropertyCallName(node, 'exports') || getDefinePropertyCallName(node, 'module.exports');
34166 if (definedProperty && definedProperty.key === KEY_COMPILED_ESM) {
34167 return isTruthy(definedProperty.value);
34168 }
34169 return false;
34170}
34171
34172function getDefinePropertyCallName(node, targetName) {
34173 const {
34174 callee: { object, property }
34175 } = node;
34176 if (!object || object.type !== 'Identifier' || object.name !== 'Object') return;
34177 if (!property || property.type !== 'Identifier' || property.name !== 'defineProperty') return;
34178 if (node.arguments.length !== 3) return;
34179
34180 const targetNames = targetName.split('.');
34181 const [target, key, value] = node.arguments;
34182 if (targetNames.length === 1) {
34183 if (target.type !== 'Identifier' || target.name !== targetNames[0]) {
34184 return;
34185 }
34186 }
34187
34188 if (targetNames.length === 2) {
34189 if (
34190 target.type !== 'MemberExpression' ||
34191 target.object.name !== targetNames[0] ||
34192 target.property.name !== targetNames[1]
34193 ) {
34194 return;
34195 }
34196 }
34197
34198 if (value.type !== 'ObjectExpression' || !value.properties) return;
34199
34200 const valueProperty = value.properties.find((p) => p.key && p.key.name === 'value');
34201 if (!valueProperty || !valueProperty.value) return;
34202
34203 // eslint-disable-next-line consistent-return
34204 return { key: key.value, value: valueProperty.value };
34205}
34206
34207function isShorthandProperty(parent) {
34208 return parent && parent.type === 'Property' && parent.shorthand;
34209}
34210
34211function wrapCode(magicString, uses, moduleName, exportsName) {
34212 const args = [];
34213 const passedArgs = [];
34214 if (uses.module) {
34215 args.push('module');
34216 passedArgs.push(moduleName);
34217 }
34218 if (uses.exports) {
34219 args.push('exports');
34220 passedArgs.push(exportsName);
34221 }
34222 magicString
34223 .trim()
34224 .prepend(`(function (${args.join(', ')}) {\n`)
34225 .append(`\n}(${passedArgs.join(', ')}));`);
34226}
34227
34228function rewriteExportsAndGetExportsBlock(
34229 magicString,
34230 moduleName,
34231 exportsName,
34232 wrapped,
34233 moduleExportsAssignments,
34234 firstTopLevelModuleExportsAssignment,
34235 exportsAssignmentsByName,
34236 topLevelAssignments,
34237 defineCompiledEsmExpressions,
34238 deconflictedExportNames,
34239 code,
34240 HELPERS_NAME,
34241 exportMode,
34242 detectWrappedDefault,
34243 defaultIsModuleExports
34244) {
34245 const exports = [];
34246 const exportDeclarations = [];
34247
34248 if (exportMode === 'replace') {
34249 getExportsForReplacedModuleExports(
34250 magicString,
34251 exports,
34252 exportDeclarations,
34253 moduleExportsAssignments,
34254 firstTopLevelModuleExportsAssignment,
34255 exportsName
34256 );
34257 } else {
34258 exports.push(`${exportsName} as __moduleExports`);
34259 if (wrapped) {
34260 getExportsWhenWrapping(
34261 exportDeclarations,
34262 exportsName,
34263 detectWrappedDefault,
34264 HELPERS_NAME,
34265 defaultIsModuleExports
34266 );
34267 } else {
34268 getExports(
34269 magicString,
34270 exports,
34271 exportDeclarations,
34272 moduleExportsAssignments,
34273 exportsAssignmentsByName,
34274 deconflictedExportNames,
34275 topLevelAssignments,
34276 moduleName,
34277 exportsName,
34278 defineCompiledEsmExpressions,
34279 HELPERS_NAME,
34280 defaultIsModuleExports
34281 );
34282 }
34283 }
34284 if (exports.length) {
34285 exportDeclarations.push(`export { ${exports.join(', ')} };`);
34286 }
34287
34288 return `\n\n${exportDeclarations.join('\n')}`;
34289}
34290
34291function getExportsForReplacedModuleExports(
34292 magicString,
34293 exports,
34294 exportDeclarations,
34295 moduleExportsAssignments,
34296 firstTopLevelModuleExportsAssignment,
34297 exportsName
34298) {
34299 for (const { left } of moduleExportsAssignments) {
34300 magicString.overwrite(left.start, left.end, exportsName);
34301 }
34302 magicString.prependRight(firstTopLevelModuleExportsAssignment.left.start, 'var ');
34303 exports.push(`${exportsName} as __moduleExports`);
34304 exportDeclarations.push(`export default ${exportsName};`);
34305}
34306
34307function getExportsWhenWrapping(
34308 exportDeclarations,
34309 exportsName,
34310 detectWrappedDefault,
34311 HELPERS_NAME,
34312 defaultIsModuleExports
34313) {
34314 exportDeclarations.push(
34315 `export default ${
34316 detectWrappedDefault && defaultIsModuleExports === 'auto'
34317 ? `/*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportsName})`
34318 : defaultIsModuleExports === false
34319 ? `${exportsName}.default`
34320 : exportsName
34321 };`
34322 );
34323}
34324
34325function getExports(
34326 magicString,
34327 exports,
34328 exportDeclarations,
34329 moduleExportsAssignments,
34330 exportsAssignmentsByName,
34331 deconflictedExportNames,
34332 topLevelAssignments,
34333 moduleName,
34334 exportsName,
34335 defineCompiledEsmExpressions,
34336 HELPERS_NAME,
34337 defaultIsModuleExports
34338) {
34339 let deconflictedDefaultExportName;
34340 // Collect and rewrite module.exports assignments
34341 for (const { left } of moduleExportsAssignments) {
34342 magicString.overwrite(left.start, left.end, `${moduleName}.exports`);
34343 }
34344
34345 // Collect and rewrite named exports
34346 for (const [exportName, { nodes }] of exportsAssignmentsByName) {
34347 const deconflicted = deconflictedExportNames[exportName];
34348 let needsDeclaration = true;
34349 for (const node of nodes) {
34350 let replacement = `${deconflicted} = ${exportsName}.${exportName}`;
34351 if (needsDeclaration && topLevelAssignments.has(node)) {
34352 replacement = `var ${replacement}`;
34353 needsDeclaration = false;
34354 }
34355 magicString.overwrite(node.start, node.left.end, replacement);
34356 }
34357 if (needsDeclaration) {
34358 magicString.prepend(`var ${deconflicted};\n`);
34359 }
34360
34361 if (exportName === 'default') {
34362 deconflictedDefaultExportName = deconflicted;
34363 } else {
34364 exports.push(exportName === deconflicted ? exportName : `${deconflicted} as ${exportName}`);
34365 }
34366 }
34367
34368 // Collect and rewrite exports.__esModule assignments
34369 let isRestorableCompiledEsm = false;
34370 for (const expression of defineCompiledEsmExpressions) {
34371 isRestorableCompiledEsm = true;
34372 const moduleExportsExpression =
34373 expression.type === 'CallExpression' ? expression.arguments[0] : expression.left.object;
34374 magicString.overwrite(moduleExportsExpression.start, moduleExportsExpression.end, exportsName);
34375 }
34376
34377 if (!isRestorableCompiledEsm || defaultIsModuleExports === true) {
34378 exportDeclarations.push(`export default ${exportsName};`);
34379 } else if (moduleExportsAssignments.length === 0 || defaultIsModuleExports === false) {
34380 exports.push(`${deconflictedDefaultExportName || exportsName} as default`);
34381 } else {
34382 exportDeclarations.push(
34383 `export default /*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportsName});`
34384 );
34385 }
34386}
34387
34388function isRequireStatement(node, scope) {
34389 if (!node) return false;
34390 if (node.type !== 'CallExpression') return false;
34391
34392 // Weird case of `require()` or `module.require()` without arguments
34393 if (node.arguments.length === 0) return false;
34394
34395 return isRequire(node.callee, scope);
34396}
34397
34398function isRequire(node, scope) {
34399 return (
34400 (node.type === 'Identifier' && node.name === 'require' && !scope.contains('require')) ||
34401 (node.type === 'MemberExpression' && isModuleRequire(node, scope))
34402 );
34403}
34404
34405function isModuleRequire({ object, property }, scope) {
34406 return (
34407 object.type === 'Identifier' &&
34408 object.name === 'module' &&
34409 property.type === 'Identifier' &&
34410 property.name === 'require' &&
34411 !scope.contains('module')
34412 );
34413}
34414
34415function isStaticRequireStatement(node, scope) {
34416 if (!isRequireStatement(node, scope)) return false;
34417 return !hasDynamicArguments(node);
34418}
34419
34420function hasDynamicArguments(node) {
34421 return (
34422 node.arguments.length > 1 ||
34423 (node.arguments[0].type !== 'Literal' &&
34424 (node.arguments[0].type !== 'TemplateLiteral' || node.arguments[0].expressions.length > 0))
34425 );
34426}
34427
34428const reservedMethod = { resolve: true, cache: true, main: true };
34429
34430function isNodeRequirePropertyAccess(parent) {
34431 return parent && parent.property && reservedMethod[parent.property.name];
34432}
34433
34434function isIgnoredRequireStatement(requiredNode, ignoreRequire) {
34435 return ignoreRequire(requiredNode.arguments[0].value);
34436}
34437
34438function getRequireStringArg(node) {
34439 return node.arguments[0].type === 'Literal'
34440 ? node.arguments[0].value
34441 : node.arguments[0].quasis[0].value.cooked;
34442}
34443
34444function hasDynamicModuleForPath(source, id, dynamicRequireModuleSet) {
34445 if (!/^(?:\.{0,2}[/\\]|[A-Za-z]:[/\\])/.test(source)) {
34446 try {
34447 const resolvedPath = normalizePathSlashes(resolve$4.sync(source, { basedir: path$A.dirname(id) }));
34448 if (dynamicRequireModuleSet.has(resolvedPath)) {
34449 return true;
34450 }
34451 } catch (ex) {
34452 // Probably a node.js internal module
34453 return false;
34454 }
34455
34456 return false;
34457 }
34458
34459 for (const attemptExt of ['', '.js', '.json']) {
34460 const resolvedPath = normalizePathSlashes(path$A.resolve(path$A.dirname(id), source + attemptExt));
34461 if (dynamicRequireModuleSet.has(resolvedPath)) {
34462 return true;
34463 }
34464 }
34465
34466 return false;
34467}
34468
34469function getRequireHandlers() {
34470 const requiredSources = [];
34471 const requiredBySource = Object.create(null);
34472 const requiredByNode = new Map();
34473 const requireExpressionsWithUsedReturnValue = [];
34474
34475 function addRequireStatement(sourceId, node, scope, usesReturnValue) {
34476 const required = getRequired(sourceId);
34477 requiredByNode.set(node, { scope, required });
34478 if (usesReturnValue) {
34479 required.nodesUsingRequired.push(node);
34480 requireExpressionsWithUsedReturnValue.push(node);
34481 }
34482 }
34483
34484 function getRequired(sourceId) {
34485 if (!requiredBySource[sourceId]) {
34486 requiredSources.push(sourceId);
34487
34488 requiredBySource[sourceId] = {
34489 source: sourceId,
34490 name: null,
34491 nodesUsingRequired: []
34492 };
34493 }
34494
34495 return requiredBySource[sourceId];
34496 }
34497
34498 function rewriteRequireExpressionsAndGetImportBlock(
34499 magicString,
34500 topLevelDeclarations,
34501 topLevelRequireDeclarators,
34502 reassignedNames,
34503 helpersName,
34504 dynamicRegisterSources,
34505 moduleName,
34506 exportsName,
34507 id,
34508 exportMode
34509 ) {
34510 setRemainingImportNamesAndRewriteRequires(
34511 requireExpressionsWithUsedReturnValue,
34512 requiredByNode,
34513 magicString
34514 );
34515 const imports = [];
34516 imports.push(`import * as ${helpersName} from "${HELPERS_ID}";`);
34517 if (exportMode === 'module') {
34518 imports.push(
34519 `import { __module as ${moduleName}, exports as ${exportsName} } from ${JSON.stringify(
34520 wrapId(id, MODULE_SUFFIX)
34521 )}`
34522 );
34523 } else if (exportMode === 'exports') {
34524 imports.push(
34525 `import { __exports as ${exportsName} } from ${JSON.stringify(wrapId(id, EXPORTS_SUFFIX))}`
34526 );
34527 }
34528 for (const source of dynamicRegisterSources) {
34529 imports.push(`import ${JSON.stringify(wrapId(source, REQUIRE_SUFFIX))};`);
34530 }
34531 for (const source of requiredSources) {
34532 if (!source.startsWith('\0')) {
34533 imports.push(`import ${JSON.stringify(wrapId(source, REQUIRE_SUFFIX))};`);
34534 }
34535 const { name, nodesUsingRequired } = requiredBySource[source];
34536 imports.push(
34537 `import ${nodesUsingRequired.length ? `${name} from ` : ''}${JSON.stringify(
34538 source.startsWith('\0') ? source : wrapId(source, PROXY_SUFFIX)
34539 )};`
34540 );
34541 }
34542 return imports.length ? `${imports.join('\n')}\n\n` : '';
34543 }
34544
34545 return {
34546 addRequireStatement,
34547 requiredSources,
34548 rewriteRequireExpressionsAndGetImportBlock
34549 };
34550}
34551
34552function setRemainingImportNamesAndRewriteRequires(
34553 requireExpressionsWithUsedReturnValue,
34554 requiredByNode,
34555 magicString
34556) {
34557 let uid = 0;
34558 for (const requireExpression of requireExpressionsWithUsedReturnValue) {
34559 const { required } = requiredByNode.get(requireExpression);
34560 if (!required.name) {
34561 let potentialName;
34562 const isUsedName = (node) => requiredByNode.get(node).scope.contains(potentialName);
34563 do {
34564 potentialName = `require$$${uid}`;
34565 uid += 1;
34566 } while (required.nodesUsingRequired.some(isUsedName));
34567 required.name = potentialName;
34568 }
34569 magicString.overwrite(requireExpression.start, requireExpression.end, required.name);
34570 }
34571}
34572
34573/* eslint-disable no-param-reassign, no-shadow, no-underscore-dangle, no-continue */
34574
34575const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/;
34576
34577const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/;
34578
34579function transformCommonjs(
34580 parse,
34581 code,
34582 id,
34583 isEsModule,
34584 ignoreGlobal,
34585 ignoreRequire,
34586 ignoreDynamicRequires,
34587 getIgnoreTryCatchRequireStatementMode,
34588 sourceMap,
34589 isDynamicRequireModulesEnabled,
34590 dynamicRequireModuleSet,
34591 disableWrap,
34592 commonDir,
34593 astCache,
34594 defaultIsModuleExports
34595) {
34596 const ast = astCache || tryParse(parse, code, id);
34597 const magicString = new MagicString(code);
34598 const uses = {
34599 module: false,
34600 exports: false,
34601 global: false,
34602 require: false
34603 };
34604 let usesDynamicRequire = false;
34605 const virtualDynamicRequirePath =
34606 isDynamicRequireModulesEnabled && getVirtualPathForDynamicRequirePath(path$A.dirname(id), commonDir);
34607 let scope = attachScopes(ast, 'scope');
34608 let lexicalDepth = 0;
34609 let programDepth = 0;
34610 let currentTryBlockEnd = null;
34611 let shouldWrap = false;
34612
34613 const globals = new Set();
34614
34615 // TODO technically wrong since globals isn't populated yet, but ¯\_(ツ)_/¯
34616 const HELPERS_NAME = deconflict([scope], globals, 'commonjsHelpers');
34617 const dynamicRegisterSources = new Set();
34618 let hasRemovedRequire = false;
34619
34620 const {
34621 addRequireStatement,
34622 requiredSources,
34623 rewriteRequireExpressionsAndGetImportBlock
34624 } = getRequireHandlers();
34625
34626 // See which names are assigned to. This is necessary to prevent
34627 // illegally replacing `var foo = require('foo')` with `import foo from 'foo'`,
34628 // where `foo` is later reassigned. (This happens in the wild. CommonJS, sigh)
34629 const reassignedNames = new Set();
34630 const topLevelDeclarations = [];
34631 const topLevelRequireDeclarators = new Set();
34632 const skippedNodes = new Set();
34633 const moduleAccessScopes = new Set([scope]);
34634 const exportsAccessScopes = new Set([scope]);
34635 const moduleExportsAssignments = [];
34636 let firstTopLevelModuleExportsAssignment = null;
34637 const exportsAssignmentsByName = new Map();
34638 const topLevelAssignments = new Set();
34639 const topLevelDefineCompiledEsmExpressions = [];
34640
34641 walk$1(ast, {
34642 enter(node, parent) {
34643 if (skippedNodes.has(node)) {
34644 this.skip();
34645 return;
34646 }
34647
34648 if (currentTryBlockEnd !== null && node.start > currentTryBlockEnd) {
34649 currentTryBlockEnd = null;
34650 }
34651
34652 programDepth += 1;
34653 if (node.scope) ({ scope } = node);
34654 if (functionType.test(node.type)) lexicalDepth += 1;
34655 if (sourceMap) {
34656 magicString.addSourcemapLocation(node.start);
34657 magicString.addSourcemapLocation(node.end);
34658 }
34659
34660 // eslint-disable-next-line default-case
34661 switch (node.type) {
34662 case 'TryStatement':
34663 if (currentTryBlockEnd === null) {
34664 currentTryBlockEnd = node.block.end;
34665 }
34666 return;
34667 case 'AssignmentExpression':
34668 if (node.left.type === 'MemberExpression') {
34669 const flattened = getKeypath(node.left);
34670 if (!flattened || scope.contains(flattened.name)) return;
34671
34672 const exportsPatternMatch = exportsPattern.exec(flattened.keypath);
34673 if (!exportsPatternMatch || flattened.keypath === 'exports') return;
34674
34675 const [, exportName] = exportsPatternMatch;
34676 uses[flattened.name] = true;
34677
34678 // we're dealing with `module.exports = ...` or `[module.]exports.foo = ...` –
34679 if (flattened.keypath === 'module.exports') {
34680 moduleExportsAssignments.push(node);
34681 if (programDepth > 3) {
34682 moduleAccessScopes.add(scope);
34683 } else if (!firstTopLevelModuleExportsAssignment) {
34684 firstTopLevelModuleExportsAssignment = node;
34685 }
34686 } else if (exportName === KEY_COMPILED_ESM) {
34687 if (programDepth > 3) {
34688 shouldWrap = true;
34689 } else {
34690 topLevelDefineCompiledEsmExpressions.push(node);
34691 }
34692 } else {
34693 const exportsAssignments = exportsAssignmentsByName.get(exportName) || {
34694 nodes: [],
34695 scopes: new Set()
34696 };
34697 exportsAssignments.nodes.push(node);
34698 exportsAssignments.scopes.add(scope);
34699 exportsAccessScopes.add(scope);
34700 exportsAssignmentsByName.set(exportName, exportsAssignments);
34701 if (programDepth <= 3) {
34702 topLevelAssignments.add(node);
34703 }
34704 }
34705
34706 skippedNodes.add(node.left);
34707 } else {
34708 for (const name of extractAssignedNames(node.left)) {
34709 reassignedNames.add(name);
34710 }
34711 }
34712 return;
34713 case 'CallExpression': {
34714 if (isDefineCompiledEsm(node)) {
34715 if (programDepth === 3 && parent.type === 'ExpressionStatement') {
34716 // skip special handling for [module.]exports until we know we render this
34717 skippedNodes.add(node.arguments[0]);
34718 topLevelDefineCompiledEsmExpressions.push(node);
34719 } else {
34720 shouldWrap = true;
34721 }
34722 return;
34723 }
34724
34725 if (
34726 node.callee.object &&
34727 node.callee.object.name === 'require' &&
34728 node.callee.property.name === 'resolve' &&
34729 hasDynamicModuleForPath(id, '/', dynamicRequireModuleSet)
34730 ) {
34731 const requireNode = node.callee.object;
34732 magicString.appendLeft(
34733 node.end - 1,
34734 `,${JSON.stringify(
34735 path$A.dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
34736 )}`
34737 );
34738 magicString.overwrite(
34739 requireNode.start,
34740 requireNode.end,
34741 `${HELPERS_NAME}.commonjsRequire`,
34742 {
34743 storeName: true
34744 }
34745 );
34746 return;
34747 }
34748
34749 if (!isStaticRequireStatement(node, scope)) return;
34750 if (!isDynamicRequireModulesEnabled) {
34751 skippedNodes.add(node.callee);
34752 }
34753 if (!isIgnoredRequireStatement(node, ignoreRequire)) {
34754 skippedNodes.add(node.callee);
34755 const usesReturnValue = parent.type !== 'ExpressionStatement';
34756
34757 let canConvertRequire = true;
34758 let shouldRemoveRequireStatement = false;
34759
34760 if (currentTryBlockEnd !== null) {
34761 ({
34762 canConvertRequire,
34763 shouldRemoveRequireStatement
34764 } = getIgnoreTryCatchRequireStatementMode(node.arguments[0].value));
34765
34766 if (shouldRemoveRequireStatement) {
34767 hasRemovedRequire = true;
34768 }
34769 }
34770
34771 let sourceId = getRequireStringArg(node);
34772 const isDynamicRegister = isWrappedId(sourceId, DYNAMIC_REGISTER_SUFFIX);
34773 if (isDynamicRegister) {
34774 sourceId = unwrapId(sourceId, DYNAMIC_REGISTER_SUFFIX);
34775 if (sourceId.endsWith('.json')) {
34776 sourceId = DYNAMIC_JSON_PREFIX + sourceId;
34777 }
34778 dynamicRegisterSources.add(wrapId(sourceId, DYNAMIC_REGISTER_SUFFIX));
34779 } else {
34780 if (
34781 !sourceId.endsWith('.json') &&
34782 hasDynamicModuleForPath(sourceId, id, dynamicRequireModuleSet)
34783 ) {
34784 if (shouldRemoveRequireStatement) {
34785 magicString.overwrite(node.start, node.end, `undefined`);
34786 } else if (canConvertRequire) {
34787 magicString.overwrite(
34788 node.start,
34789 node.end,
34790 `${HELPERS_NAME}.commonjsRequire(${JSON.stringify(
34791 getVirtualPathForDynamicRequirePath(sourceId, commonDir)
34792 )}, ${JSON.stringify(
34793 path$A.dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
34794 )})`
34795 );
34796 usesDynamicRequire = true;
34797 }
34798 return;
34799 }
34800
34801 if (canConvertRequire) {
34802 addRequireStatement(sourceId, node, scope, usesReturnValue);
34803 }
34804 }
34805
34806 if (usesReturnValue) {
34807 if (shouldRemoveRequireStatement) {
34808 magicString.overwrite(node.start, node.end, `undefined`);
34809 return;
34810 }
34811
34812 if (
34813 parent.type === 'VariableDeclarator' &&
34814 !scope.parent &&
34815 parent.id.type === 'Identifier'
34816 ) {
34817 // This will allow us to reuse this variable name as the imported variable if it is not reassigned
34818 // and does not conflict with variables in other places where this is imported
34819 topLevelRequireDeclarators.add(parent);
34820 }
34821 } else {
34822 // This is a bare import, e.g. `require('foo');`
34823
34824 if (!canConvertRequire && !shouldRemoveRequireStatement) {
34825 return;
34826 }
34827
34828 magicString.remove(parent.start, parent.end);
34829 }
34830 }
34831 return;
34832 }
34833 case 'ConditionalExpression':
34834 case 'IfStatement':
34835 // skip dead branches
34836 if (isFalsy(node.test)) {
34837 skippedNodes.add(node.consequent);
34838 } else if (node.alternate && isTruthy(node.test)) {
34839 skippedNodes.add(node.alternate);
34840 }
34841 return;
34842 case 'Identifier': {
34843 const { name } = node;
34844 if (!(isReference(node, parent) && !scope.contains(name))) return;
34845 switch (name) {
34846 case 'require':
34847 if (isNodeRequirePropertyAccess(parent)) {
34848 if (hasDynamicModuleForPath(id, '/', dynamicRequireModuleSet)) {
34849 if (parent.property.name === 'cache') {
34850 magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
34851 storeName: true
34852 });
34853 }
34854 }
34855
34856 return;
34857 }
34858
34859 if (isDynamicRequireModulesEnabled && isRequireStatement(parent, scope)) {
34860 magicString.appendLeft(
34861 parent.end - 1,
34862 `,${JSON.stringify(
34863 path$A.dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
34864 )}`
34865 );
34866 }
34867 if (!ignoreDynamicRequires) {
34868 if (isShorthandProperty(parent)) {
34869 magicString.appendRight(node.end, `: ${HELPERS_NAME}.commonjsRequire`);
34870 } else {
34871 magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
34872 storeName: true
34873 });
34874 }
34875 }
34876 usesDynamicRequire = true;
34877 return;
34878 case 'module':
34879 case 'exports':
34880 shouldWrap = true;
34881 uses[name] = true;
34882 return;
34883 case 'global':
34884 uses.global = true;
34885 if (!ignoreGlobal) {
34886 magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
34887 storeName: true
34888 });
34889 }
34890 return;
34891 case 'define':
34892 magicString.overwrite(node.start, node.end, 'undefined', {
34893 storeName: true
34894 });
34895 return;
34896 default:
34897 globals.add(name);
34898 return;
34899 }
34900 }
34901 case 'MemberExpression':
34902 if (!isDynamicRequireModulesEnabled && isModuleRequire(node, scope)) {
34903 magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
34904 storeName: true
34905 });
34906 skippedNodes.add(node.object);
34907 skippedNodes.add(node.property);
34908 }
34909 return;
34910 case 'ReturnStatement':
34911 // if top-level return, we need to wrap it
34912 if (lexicalDepth === 0) {
34913 shouldWrap = true;
34914 }
34915 return;
34916 case 'ThisExpression':
34917 // rewrite top-level `this` as `commonjsHelpers.commonjsGlobal`
34918 if (lexicalDepth === 0) {
34919 uses.global = true;
34920 if (!ignoreGlobal) {
34921 magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
34922 storeName: true
34923 });
34924 }
34925 }
34926 return;
34927 case 'UnaryExpression':
34928 // rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151)
34929 if (node.operator === 'typeof') {
34930 const flattened = getKeypath(node.argument);
34931 if (!flattened) return;
34932
34933 if (scope.contains(flattened.name)) return;
34934
34935 if (
34936 flattened.keypath === 'module.exports' ||
34937 flattened.keypath === 'module' ||
34938 flattened.keypath === 'exports'
34939 ) {
34940 magicString.overwrite(node.start, node.end, `'object'`, {
34941 storeName: false
34942 });
34943 }
34944 }
34945 return;
34946 case 'VariableDeclaration':
34947 if (!scope.parent) {
34948 topLevelDeclarations.push(node);
34949 }
34950 }
34951 },
34952
34953 leave(node) {
34954 programDepth -= 1;
34955 if (node.scope) scope = scope.parent;
34956 if (functionType.test(node.type)) lexicalDepth -= 1;
34957 }
34958 });
34959
34960 const nameBase = getName(id);
34961 const exportsName = deconflict([...exportsAccessScopes], globals, nameBase);
34962 const moduleName = deconflict([...moduleAccessScopes], globals, `${nameBase}Module`);
34963 const deconflictedExportNames = Object.create(null);
34964 for (const [exportName, { scopes }] of exportsAssignmentsByName) {
34965 deconflictedExportNames[exportName] = deconflict([...scopes], globals, exportName);
34966 }
34967
34968 // We cannot wrap ES/mixed modules
34969 shouldWrap =
34970 !isEsModule &&
34971 !disableWrap &&
34972 (shouldWrap || (uses.exports && moduleExportsAssignments.length > 0));
34973 const detectWrappedDefault =
34974 shouldWrap &&
34975 (topLevelDefineCompiledEsmExpressions.length > 0 || code.indexOf('__esModule') >= 0);
34976
34977 if (
34978 !(
34979 requiredSources.length ||
34980 dynamicRegisterSources.size ||
34981 uses.module ||
34982 uses.exports ||
34983 uses.require ||
34984 usesDynamicRequire ||
34985 hasRemovedRequire ||
34986 topLevelDefineCompiledEsmExpressions.length > 0
34987 ) &&
34988 (ignoreGlobal || !uses.global)
34989 ) {
34990 return { meta: { commonjs: { isCommonJS: false } } };
34991 }
34992
34993 let leadingComment = '';
34994 if (code.startsWith('/*')) {
34995 const commentEnd = code.indexOf('*/', 2) + 2;
34996 leadingComment = `${code.slice(0, commentEnd)}\n`;
34997 magicString.remove(0, commentEnd).trim();
34998 }
34999
35000 const exportMode = shouldWrap
35001 ? uses.module
35002 ? 'module'
35003 : 'exports'
35004 : firstTopLevelModuleExportsAssignment
35005 ? exportsAssignmentsByName.size === 0 && topLevelDefineCompiledEsmExpressions.length === 0
35006 ? 'replace'
35007 : 'module'
35008 : moduleExportsAssignments.length === 0
35009 ? 'exports'
35010 : 'module';
35011
35012 const importBlock = rewriteRequireExpressionsAndGetImportBlock(
35013 magicString,
35014 topLevelDeclarations,
35015 topLevelRequireDeclarators,
35016 reassignedNames,
35017 HELPERS_NAME,
35018 dynamicRegisterSources,
35019 moduleName,
35020 exportsName,
35021 id,
35022 exportMode
35023 );
35024
35025 const exportBlock = isEsModule
35026 ? ''
35027 : rewriteExportsAndGetExportsBlock(
35028 magicString,
35029 moduleName,
35030 exportsName,
35031 shouldWrap,
35032 moduleExportsAssignments,
35033 firstTopLevelModuleExportsAssignment,
35034 exportsAssignmentsByName,
35035 topLevelAssignments,
35036 topLevelDefineCompiledEsmExpressions,
35037 deconflictedExportNames,
35038 code,
35039 HELPERS_NAME,
35040 exportMode,
35041 detectWrappedDefault,
35042 defaultIsModuleExports
35043 );
35044
35045 if (shouldWrap) {
35046 wrapCode(magicString, uses, moduleName, exportsName);
35047 }
35048
35049 magicString
35050 .trim()
35051 .prepend(leadingComment + importBlock)
35052 .append(exportBlock);
35053
35054 return {
35055 code: magicString.toString(),
35056 map: sourceMap ? magicString.generateMap() : null,
35057 syntheticNamedExports: isEsModule ? false : '__moduleExports',
35058 meta: { commonjs: { isCommonJS: !isEsModule } }
35059 };
35060}
35061
35062function commonjs(options = {}) {
35063 const extensions = options.extensions || ['.js'];
35064 const filter = createFilter(options.include, options.exclude);
35065 const {
35066 ignoreGlobal,
35067 ignoreDynamicRequires,
35068 requireReturnsDefault: requireReturnsDefaultOption,
35069 esmExternals
35070 } = options;
35071 const getRequireReturnsDefault =
35072 typeof requireReturnsDefaultOption === 'function'
35073 ? requireReturnsDefaultOption
35074 : () => requireReturnsDefaultOption;
35075 let esmExternalIds;
35076 const isEsmExternal =
35077 typeof esmExternals === 'function'
35078 ? esmExternals
35079 : Array.isArray(esmExternals)
35080 ? ((esmExternalIds = new Set(esmExternals)), (id) => esmExternalIds.has(id))
35081 : () => esmExternals;
35082 const defaultIsModuleExports =
35083 typeof options.defaultIsModuleExports === 'boolean' ? options.defaultIsModuleExports : 'auto';
35084
35085 const { dynamicRequireModuleSet, dynamicRequireModuleDirPaths } = getDynamicRequirePaths(
35086 options.dynamicRequireTargets
35087 );
35088 const isDynamicRequireModulesEnabled = dynamicRequireModuleSet.size > 0;
35089 const commonDir = isDynamicRequireModulesEnabled
35090 ? commondir(null, Array.from(dynamicRequireModuleSet).concat(process.cwd()))
35091 : null;
35092
35093 const esModulesWithDefaultExport = new Set();
35094 const esModulesWithNamedExports = new Set();
35095 const commonJsMetaPromises = new Map();
35096
35097 const ignoreRequire =
35098 typeof options.ignore === 'function'
35099 ? options.ignore
35100 : Array.isArray(options.ignore)
35101 ? (id) => options.ignore.includes(id)
35102 : () => false;
35103
35104 const getIgnoreTryCatchRequireStatementMode = (id) => {
35105 const mode =
35106 typeof options.ignoreTryCatch === 'function'
35107 ? options.ignoreTryCatch(id)
35108 : Array.isArray(options.ignoreTryCatch)
35109 ? options.ignoreTryCatch.includes(id)
35110 : options.ignoreTryCatch || false;
35111
35112 return {
35113 canConvertRequire: mode !== 'remove' && mode !== true,
35114 shouldRemoveRequireStatement: mode === 'remove'
35115 };
35116 };
35117
35118 const resolveId = getResolveId(extensions);
35119
35120 const sourceMap = options.sourceMap !== false;
35121
35122 function transformAndCheckExports(code, id) {
35123 if (isDynamicRequireModulesEnabled && this.getModuleInfo(id).isEntry) {
35124 // eslint-disable-next-line no-param-reassign
35125 code =
35126 getDynamicPackagesEntryIntro(dynamicRequireModuleDirPaths, dynamicRequireModuleSet) + code;
35127 }
35128
35129 const { isEsModule, hasDefaultExport, hasNamedExports, ast } = analyzeTopLevelStatements(
35130 this.parse,
35131 code,
35132 id
35133 );
35134 if (hasDefaultExport) {
35135 esModulesWithDefaultExport.add(id);
35136 }
35137 if (hasNamedExports) {
35138 esModulesWithNamedExports.add(id);
35139 }
35140
35141 if (
35142 !dynamicRequireModuleSet.has(normalizePathSlashes(id)) &&
35143 (!hasCjsKeywords(code, ignoreGlobal) || (isEsModule && !options.transformMixedEsModules))
35144 ) {
35145 return { meta: { commonjs: { isCommonJS: false } } };
35146 }
35147
35148 // avoid wrapping as this is a commonjsRegister call
35149 const disableWrap = isWrappedId(id, DYNAMIC_REGISTER_SUFFIX);
35150 if (disableWrap) {
35151 // eslint-disable-next-line no-param-reassign
35152 id = unwrapId(id, DYNAMIC_REGISTER_SUFFIX);
35153 }
35154
35155 return transformCommonjs(
35156 this.parse,
35157 code,
35158 id,
35159 isEsModule,
35160 ignoreGlobal || isEsModule,
35161 ignoreRequire,
35162 ignoreDynamicRequires && !isDynamicRequireModulesEnabled,
35163 getIgnoreTryCatchRequireStatementMode,
35164 sourceMap,
35165 isDynamicRequireModulesEnabled,
35166 dynamicRequireModuleSet,
35167 disableWrap,
35168 commonDir,
35169 ast,
35170 defaultIsModuleExports
35171 );
35172 }
35173
35174 return {
35175 name: 'commonjs',
35176
35177 buildStart() {
35178 validateRollupVersion(this.meta.rollupVersion, peerDependencies.rollup);
35179 if (options.namedExports != null) {
35180 this.warn(
35181 'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.'
35182 );
35183 }
35184 },
35185
35186 resolveId,
35187
35188 load(id) {
35189 if (id === HELPERS_ID) {
35190 return getHelpersModule(isDynamicRequireModulesEnabled, ignoreDynamicRequires);
35191 }
35192
35193 if (id.startsWith(HELPERS_ID)) {
35194 return getSpecificHelperProxy(id);
35195 }
35196
35197 if (isWrappedId(id, MODULE_SUFFIX)) {
35198 const actualId = unwrapId(id, MODULE_SUFFIX);
35199 let name = getName(actualId);
35200 let code;
35201 if (isDynamicRequireModulesEnabled) {
35202 if (['modulePath', 'commonjsRequire', 'createModule'].includes(name)) {
35203 name = `${name}_`;
35204 }
35205 code =
35206 `import {commonjsRequire, createModule} from "${HELPERS_ID}";\n` +
35207 `var ${name} = createModule(${JSON.stringify(
35208 getVirtualPathForDynamicRequirePath(path$A.dirname(actualId), commonDir)
35209 )});\n` +
35210 `export {${name} as __module}`;
35211 } else {
35212 code = `var ${name} = {exports: {}}; export {${name} as __module}`;
35213 }
35214 return {
35215 code,
35216 syntheticNamedExports: '__module',
35217 meta: { commonjs: { isCommonJS: false } }
35218 };
35219 }
35220
35221 if (isWrappedId(id, EXPORTS_SUFFIX)) {
35222 const actualId = unwrapId(id, EXPORTS_SUFFIX);
35223 const name = getName(actualId);
35224 return {
35225 code: `var ${name} = {}; export {${name} as __exports}`,
35226 meta: { commonjs: { isCommonJS: false } }
35227 };
35228 }
35229
35230 if (isWrappedId(id, EXTERNAL_SUFFIX)) {
35231 const actualId = unwrapId(id, EXTERNAL_SUFFIX);
35232 return getUnknownRequireProxy(
35233 actualId,
35234 isEsmExternal(actualId) ? getRequireReturnsDefault(actualId) : true
35235 );
35236 }
35237
35238 if (id === DYNAMIC_PACKAGES_ID) {
35239 return getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir);
35240 }
35241
35242 if (id.startsWith(DYNAMIC_JSON_PREFIX)) {
35243 return getDynamicJsonProxy(id, commonDir);
35244 }
35245
35246 if (isDynamicModuleImport(id, dynamicRequireModuleSet)) {
35247 return `export default require(${JSON.stringify(normalizePathSlashes(id))});`;
35248 }
35249
35250 if (isWrappedId(id, DYNAMIC_REGISTER_SUFFIX)) {
35251 return getDynamicRequireProxy(
35252 normalizePathSlashes(unwrapId(id, DYNAMIC_REGISTER_SUFFIX)),
35253 commonDir
35254 );
35255 }
35256
35257 if (isWrappedId(id, PROXY_SUFFIX)) {
35258 const actualId = unwrapId(id, PROXY_SUFFIX);
35259 return getStaticRequireProxy(
35260 actualId,
35261 getRequireReturnsDefault(actualId),
35262 esModulesWithDefaultExport,
35263 esModulesWithNamedExports,
35264 commonJsMetaPromises
35265 );
35266 }
35267
35268 return null;
35269 },
35270
35271 transform(code, rawId) {
35272 let id = rawId;
35273
35274 if (isWrappedId(id, DYNAMIC_REGISTER_SUFFIX)) {
35275 id = unwrapId(id, DYNAMIC_REGISTER_SUFFIX);
35276 }
35277
35278 const extName = path$A.extname(id);
35279 if (
35280 extName !== '.cjs' &&
35281 id !== DYNAMIC_PACKAGES_ID &&
35282 !id.startsWith(DYNAMIC_JSON_PREFIX) &&
35283 (!filter(id) || !extensions.includes(extName))
35284 ) {
35285 return null;
35286 }
35287
35288 try {
35289 return transformAndCheckExports.call(this, code, rawId);
35290 } catch (err) {
35291 return this.error(err, err.loc);
35292 }
35293 },
35294
35295 moduleParsed({ id, meta: { commonjs: commonjsMeta } }) {
35296 if (commonjsMeta && commonjsMeta.isCommonJS != null) {
35297 setCommonJSMetaPromise(commonJsMetaPromises, id, commonjsMeta);
35298 return;
35299 }
35300 setCommonJSMetaPromise(commonJsMetaPromises, id, null);
35301 }
35302 };
35303}
35304
35305var globby$1 = {exports: {}};
35306
35307var arrayUnion$1 = (...arguments_) => {
35308 return [...new Set([].concat(...arguments_))];
35309};
35310
35311var tasks = {};
35312
35313var utils$8 = {};
35314
35315var array$1 = {};
35316
35317Object.defineProperty(array$1, "__esModule", { value: true });
35318array$1.splitWhen = array$1.flatten = void 0;
35319function flatten$1(items) {
35320 return items.reduce((collection, item) => [].concat(collection, item), []);
35321}
35322array$1.flatten = flatten$1;
35323function splitWhen(items, predicate) {
35324 const result = [[]];
35325 let groupIndex = 0;
35326 for (const item of items) {
35327 if (predicate(item)) {
35328 groupIndex++;
35329 result[groupIndex] = [];
35330 }
35331 else {
35332 result[groupIndex].push(item);
35333 }
35334 }
35335 return result;
35336}
35337array$1.splitWhen = splitWhen;
35338
35339var errno$1 = {};
35340
35341Object.defineProperty(errno$1, "__esModule", { value: true });
35342errno$1.isEnoentCodeError = void 0;
35343function isEnoentCodeError(error) {
35344 return error.code === 'ENOENT';
35345}
35346errno$1.isEnoentCodeError = isEnoentCodeError;
35347
35348var fs$g = {};
35349
35350Object.defineProperty(fs$g, "__esModule", { value: true });
35351fs$g.createDirentFromStats = void 0;
35352class DirentFromStats {
35353 constructor(name, stats) {
35354 this.name = name;
35355 this.isBlockDevice = stats.isBlockDevice.bind(stats);
35356 this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
35357 this.isDirectory = stats.isDirectory.bind(stats);
35358 this.isFIFO = stats.isFIFO.bind(stats);
35359 this.isFile = stats.isFile.bind(stats);
35360 this.isSocket = stats.isSocket.bind(stats);
35361 this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
35362 }
35363}
35364function createDirentFromStats(name, stats) {
35365 return new DirentFromStats(name, stats);
35366}
35367fs$g.createDirentFromStats = createDirentFromStats;
35368
35369var path$i = {};
35370
35371Object.defineProperty(path$i, "__esModule", { value: true });
35372path$i.removeLeadingDotSegment = path$i.escape = path$i.makeAbsolute = path$i.unixify = void 0;
35373const path$h = path__default;
35374const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\
35375const UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\())/g;
35376/**
35377 * Designed to work only with simple paths: `dir\\file`.
35378 */
35379function unixify(filepath) {
35380 return filepath.replace(/\\/g, '/');
35381}
35382path$i.unixify = unixify;
35383function makeAbsolute(cwd, filepath) {
35384 return path$h.resolve(cwd, filepath);
35385}
35386path$i.makeAbsolute = makeAbsolute;
35387function escape$1(pattern) {
35388 return pattern.replace(UNESCAPED_GLOB_SYMBOLS_RE, '\\$2');
35389}
35390path$i.escape = escape$1;
35391function removeLeadingDotSegment(entry) {
35392 // We do not use `startsWith` because this is 10x slower than current implementation for some cases.
35393 // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with
35394 if (entry.charAt(0) === '.') {
35395 const secondCharactery = entry.charAt(1);
35396 if (secondCharactery === '/' || secondCharactery === '\\') {
35397 return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT);
35398 }
35399 }
35400 return entry;
35401}
35402path$i.removeLeadingDotSegment = removeLeadingDotSegment;
35403
35404var pattern$1 = {};
35405
35406Object.defineProperty(pattern$1, "__esModule", { value: true });
35407pattern$1.matchAny = pattern$1.convertPatternsToRe = pattern$1.makeRe = pattern$1.getPatternParts = pattern$1.expandBraceExpansion = pattern$1.expandPatternsWithBraceExpansion = pattern$1.isAffectDepthOfReadingPattern = pattern$1.endsWithSlashGlobStar = pattern$1.hasGlobStar = pattern$1.getBaseDirectory = pattern$1.getPositivePatterns = pattern$1.getNegativePatterns = pattern$1.isPositivePattern = pattern$1.isNegativePattern = pattern$1.convertToNegativePattern = pattern$1.convertToPositivePattern = pattern$1.isDynamicPattern = pattern$1.isStaticPattern = void 0;
35408const path$g = path__default;
35409const globParent$1 = globParent$3;
35410const micromatch = micromatch_1;
35411const picomatch$2 = picomatch$4;
35412const GLOBSTAR$1 = '**';
35413const ESCAPE_SYMBOL = '\\';
35414const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/;
35415const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[.*]/;
35416const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\(.*\|.*\)/;
35417const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\(.*\)/;
35418const BRACE_EXPANSIONS_SYMBOLS_RE = /{.*(?:,|\.\.).*}/;
35419function isStaticPattern(pattern, options = {}) {
35420 return !isDynamicPattern(pattern, options);
35421}
35422pattern$1.isStaticPattern = isStaticPattern;
35423function isDynamicPattern(pattern, options = {}) {
35424 /**
35425 * A special case with an empty string is necessary for matching patterns that start with a forward slash.
35426 * An empty string cannot be a dynamic pattern.
35427 * For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'.
35428 */
35429 if (pattern === '') {
35430 return false;
35431 }
35432 /**
35433 * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check
35434 * filepath directly (without read directory).
35435 */
35436 if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) {
35437 return true;
35438 }
35439 if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) {
35440 return true;
35441 }
35442 if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) {
35443 return true;
35444 }
35445 if (options.braceExpansion !== false && BRACE_EXPANSIONS_SYMBOLS_RE.test(pattern)) {
35446 return true;
35447 }
35448 return false;
35449}
35450pattern$1.isDynamicPattern = isDynamicPattern;
35451function convertToPositivePattern(pattern) {
35452 return isNegativePattern(pattern) ? pattern.slice(1) : pattern;
35453}
35454pattern$1.convertToPositivePattern = convertToPositivePattern;
35455function convertToNegativePattern(pattern) {
35456 return '!' + pattern;
35457}
35458pattern$1.convertToNegativePattern = convertToNegativePattern;
35459function isNegativePattern(pattern) {
35460 return pattern.startsWith('!') && pattern[1] !== '(';
35461}
35462pattern$1.isNegativePattern = isNegativePattern;
35463function isPositivePattern(pattern) {
35464 return !isNegativePattern(pattern);
35465}
35466pattern$1.isPositivePattern = isPositivePattern;
35467function getNegativePatterns(patterns) {
35468 return patterns.filter(isNegativePattern);
35469}
35470pattern$1.getNegativePatterns = getNegativePatterns;
35471function getPositivePatterns$1(patterns) {
35472 return patterns.filter(isPositivePattern);
35473}
35474pattern$1.getPositivePatterns = getPositivePatterns$1;
35475function getBaseDirectory(pattern) {
35476 return globParent$1(pattern, { flipBackslashes: false });
35477}
35478pattern$1.getBaseDirectory = getBaseDirectory;
35479function hasGlobStar(pattern) {
35480 return pattern.includes(GLOBSTAR$1);
35481}
35482pattern$1.hasGlobStar = hasGlobStar;
35483function endsWithSlashGlobStar(pattern) {
35484 return pattern.endsWith('/' + GLOBSTAR$1);
35485}
35486pattern$1.endsWithSlashGlobStar = endsWithSlashGlobStar;
35487function isAffectDepthOfReadingPattern(pattern) {
35488 const basename = path$g.basename(pattern);
35489 return endsWithSlashGlobStar(pattern) || isStaticPattern(basename);
35490}
35491pattern$1.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern;
35492function expandPatternsWithBraceExpansion(patterns) {
35493 return patterns.reduce((collection, pattern) => {
35494 return collection.concat(expandBraceExpansion(pattern));
35495 }, []);
35496}
35497pattern$1.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion;
35498function expandBraceExpansion(pattern) {
35499 return micromatch.braces(pattern, {
35500 expand: true,
35501 nodupes: true
35502 });
35503}
35504pattern$1.expandBraceExpansion = expandBraceExpansion;
35505function getPatternParts(pattern, options) {
35506 let { parts } = picomatch$2.scan(pattern, Object.assign(Object.assign({}, options), { parts: true }));
35507 /**
35508 * The scan method returns an empty array in some cases.
35509 * See micromatch/picomatch#58 for more details.
35510 */
35511 if (parts.length === 0) {
35512 parts = [pattern];
35513 }
35514 /**
35515 * The scan method does not return an empty part for the pattern with a forward slash.
35516 * This is another part of micromatch/picomatch#58.
35517 */
35518 if (parts[0].startsWith('/')) {
35519 parts[0] = parts[0].slice(1);
35520 parts.unshift('');
35521 }
35522 return parts;
35523}
35524pattern$1.getPatternParts = getPatternParts;
35525function makeRe(pattern, options) {
35526 return micromatch.makeRe(pattern, options);
35527}
35528pattern$1.makeRe = makeRe;
35529function convertPatternsToRe(patterns, options) {
35530 return patterns.map((pattern) => makeRe(pattern, options));
35531}
35532pattern$1.convertPatternsToRe = convertPatternsToRe;
35533function matchAny(entry, patternsRe) {
35534 return patternsRe.some((patternRe) => patternRe.test(entry));
35535}
35536pattern$1.matchAny = matchAny;
35537
35538var stream$6 = {};
35539
35540Object.defineProperty(stream$6, "__esModule", { value: true });
35541stream$6.merge = void 0;
35542const merge2$1 = merge2_1;
35543function merge$1(streams) {
35544 const mergedStream = merge2$1(streams);
35545 streams.forEach((stream) => {
35546 stream.once('error', (error) => mergedStream.emit('error', error));
35547 });
35548 mergedStream.once('close', () => propagateCloseEventToSources(streams));
35549 mergedStream.once('end', () => propagateCloseEventToSources(streams));
35550 return mergedStream;
35551}
35552stream$6.merge = merge$1;
35553function propagateCloseEventToSources(streams) {
35554 streams.forEach((stream) => stream.emit('close'));
35555}
35556
35557var string$1 = {};
35558
35559Object.defineProperty(string$1, "__esModule", { value: true });
35560string$1.isEmpty = string$1.isString = void 0;
35561function isString$1(input) {
35562 return typeof input === 'string';
35563}
35564string$1.isString = isString$1;
35565function isEmpty(input) {
35566 return input === '';
35567}
35568string$1.isEmpty = isEmpty;
35569
35570Object.defineProperty(utils$8, "__esModule", { value: true });
35571utils$8.string = utils$8.stream = utils$8.pattern = utils$8.path = utils$8.fs = utils$8.errno = utils$8.array = void 0;
35572const array = array$1;
35573utils$8.array = array;
35574const errno = errno$1;
35575utils$8.errno = errno;
35576const fs$f = fs$g;
35577utils$8.fs = fs$f;
35578const path$f = path$i;
35579utils$8.path = path$f;
35580const pattern = pattern$1;
35581utils$8.pattern = pattern;
35582const stream$5 = stream$6;
35583utils$8.stream = stream$5;
35584const string = string$1;
35585utils$8.string = string;
35586
35587Object.defineProperty(tasks, "__esModule", { value: true });
35588tasks.convertPatternGroupToTask = tasks.convertPatternGroupsToTasks = tasks.groupPatternsByBaseDirectory = tasks.getNegativePatternsAsPositive = tasks.getPositivePatterns = tasks.convertPatternsToTasks = tasks.generate = void 0;
35589const utils$7 = utils$8;
35590function generate(patterns, settings) {
35591 const positivePatterns = getPositivePatterns(patterns);
35592 const negativePatterns = getNegativePatternsAsPositive(patterns, settings.ignore);
35593 const staticPatterns = positivePatterns.filter((pattern) => utils$7.pattern.isStaticPattern(pattern, settings));
35594 const dynamicPatterns = positivePatterns.filter((pattern) => utils$7.pattern.isDynamicPattern(pattern, settings));
35595 const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, /* dynamic */ false);
35596 const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns, /* dynamic */ true);
35597 return staticTasks.concat(dynamicTasks);
35598}
35599tasks.generate = generate;
35600function convertPatternsToTasks(positive, negative, dynamic) {
35601 const positivePatternsGroup = groupPatternsByBaseDirectory(positive);
35602 // When we have a global group – there is no reason to divide the patterns into independent tasks.
35603 // In this case, the global task covers the rest.
35604 if ('.' in positivePatternsGroup) {
35605 const task = convertPatternGroupToTask('.', positive, negative, dynamic);
35606 return [task];
35607 }
35608 return convertPatternGroupsToTasks(positivePatternsGroup, negative, dynamic);
35609}
35610tasks.convertPatternsToTasks = convertPatternsToTasks;
35611function getPositivePatterns(patterns) {
35612 return utils$7.pattern.getPositivePatterns(patterns);
35613}
35614tasks.getPositivePatterns = getPositivePatterns;
35615function getNegativePatternsAsPositive(patterns, ignore) {
35616 const negative = utils$7.pattern.getNegativePatterns(patterns).concat(ignore);
35617 const positive = negative.map(utils$7.pattern.convertToPositivePattern);
35618 return positive;
35619}
35620tasks.getNegativePatternsAsPositive = getNegativePatternsAsPositive;
35621function groupPatternsByBaseDirectory(patterns) {
35622 const group = {};
35623 return patterns.reduce((collection, pattern) => {
35624 const base = utils$7.pattern.getBaseDirectory(pattern);
35625 if (base in collection) {
35626 collection[base].push(pattern);
35627 }
35628 else {
35629 collection[base] = [pattern];
35630 }
35631 return collection;
35632 }, group);
35633}
35634tasks.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory;
35635function convertPatternGroupsToTasks(positive, negative, dynamic) {
35636 return Object.keys(positive).map((base) => {
35637 return convertPatternGroupToTask(base, positive[base], negative, dynamic);
35638 });
35639}
35640tasks.convertPatternGroupsToTasks = convertPatternGroupsToTasks;
35641function convertPatternGroupToTask(base, positive, negative, dynamic) {
35642 return {
35643 dynamic,
35644 positive,
35645 negative,
35646 base,
35647 patterns: [].concat(positive, negative.map(utils$7.pattern.convertToNegativePattern))
35648 };
35649}
35650tasks.convertPatternGroupToTask = convertPatternGroupToTask;
35651
35652var async = {};
35653
35654var stream$4 = {};
35655
35656var reader = {};
35657
35658Object.defineProperty(reader, "__esModule", { value: true });
35659const path$e = path__default;
35660const fsStat$2 = out$4;
35661const utils$6 = utils$8;
35662class Reader {
35663 constructor(_settings) {
35664 this._settings = _settings;
35665 this._fsStatSettings = new fsStat$2.Settings({
35666 followSymbolicLink: this._settings.followSymbolicLinks,
35667 fs: this._settings.fs,
35668 throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks
35669 });
35670 }
35671 _getFullEntryPath(filepath) {
35672 return path$e.resolve(this._settings.cwd, filepath);
35673 }
35674 _makeEntry(stats, pattern) {
35675 const entry = {
35676 name: pattern,
35677 path: pattern,
35678 dirent: utils$6.fs.createDirentFromStats(pattern, stats)
35679 };
35680 if (this._settings.stats) {
35681 entry.stats = stats;
35682 }
35683 return entry;
35684 }
35685 _isFatalError(error) {
35686 return !utils$6.errno.isEnoentCodeError(error) && !this._settings.suppressErrors;
35687 }
35688}
35689reader.default = Reader;
35690
35691Object.defineProperty(stream$4, "__esModule", { value: true });
35692const stream_1$3 = require$$0__default$2;
35693const fsStat$1 = out$4;
35694const fsWalk$1 = out$3;
35695const reader_1$1 = reader;
35696class ReaderStream extends reader_1$1.default {
35697 constructor() {
35698 super(...arguments);
35699 this._walkStream = fsWalk$1.walkStream;
35700 this._stat = fsStat$1.stat;
35701 }
35702 dynamic(root, options) {
35703 return this._walkStream(root, options);
35704 }
35705 static(patterns, options) {
35706 const filepaths = patterns.map(this._getFullEntryPath, this);
35707 const stream = new stream_1$3.PassThrough({ objectMode: true });
35708 stream._write = (index, _enc, done) => {
35709 return this._getEntry(filepaths[index], patterns[index], options)
35710 .then((entry) => {
35711 if (entry !== null && options.entryFilter(entry)) {
35712 stream.push(entry);
35713 }
35714 if (index === filepaths.length - 1) {
35715 stream.end();
35716 }
35717 done();
35718 })
35719 .catch(done);
35720 };
35721 for (let i = 0; i < filepaths.length; i++) {
35722 stream.write(i);
35723 }
35724 return stream;
35725 }
35726 _getEntry(filepath, pattern, options) {
35727 return this._getStat(filepath)
35728 .then((stats) => this._makeEntry(stats, pattern))
35729 .catch((error) => {
35730 if (options.errorFilter(error)) {
35731 return null;
35732 }
35733 throw error;
35734 });
35735 }
35736 _getStat(filepath) {
35737 return new Promise((resolve, reject) => {
35738 this._stat(filepath, this._fsStatSettings, (error, stats) => {
35739 return error === null ? resolve(stats) : reject(error);
35740 });
35741 });
35742 }
35743}
35744stream$4.default = ReaderStream;
35745
35746var provider = {};
35747
35748var deep = {};
35749
35750var partial = {};
35751
35752var matcher = {};
35753
35754Object.defineProperty(matcher, "__esModule", { value: true });
35755const utils$5 = utils$8;
35756class Matcher {
35757 constructor(_patterns, _settings, _micromatchOptions) {
35758 this._patterns = _patterns;
35759 this._settings = _settings;
35760 this._micromatchOptions = _micromatchOptions;
35761 this._storage = [];
35762 this._fillStorage();
35763 }
35764 _fillStorage() {
35765 /**
35766 * The original pattern may include `{,*,**,a/*}`, which will lead to problems with matching (unresolved level).
35767 * So, before expand patterns with brace expansion into separated patterns.
35768 */
35769 const patterns = utils$5.pattern.expandPatternsWithBraceExpansion(this._patterns);
35770 for (const pattern of patterns) {
35771 const segments = this._getPatternSegments(pattern);
35772 const sections = this._splitSegmentsIntoSections(segments);
35773 this._storage.push({
35774 complete: sections.length <= 1,
35775 pattern,
35776 segments,
35777 sections
35778 });
35779 }
35780 }
35781 _getPatternSegments(pattern) {
35782 const parts = utils$5.pattern.getPatternParts(pattern, this._micromatchOptions);
35783 return parts.map((part) => {
35784 const dynamic = utils$5.pattern.isDynamicPattern(part, this._settings);
35785 if (!dynamic) {
35786 return {
35787 dynamic: false,
35788 pattern: part
35789 };
35790 }
35791 return {
35792 dynamic: true,
35793 pattern: part,
35794 patternRe: utils$5.pattern.makeRe(part, this._micromatchOptions)
35795 };
35796 });
35797 }
35798 _splitSegmentsIntoSections(segments) {
35799 return utils$5.array.splitWhen(segments, (segment) => segment.dynamic && utils$5.pattern.hasGlobStar(segment.pattern));
35800 }
35801}
35802matcher.default = Matcher;
35803
35804Object.defineProperty(partial, "__esModule", { value: true });
35805const matcher_1 = matcher;
35806class PartialMatcher extends matcher_1.default {
35807 match(filepath) {
35808 const parts = filepath.split('/');
35809 const levels = parts.length;
35810 const patterns = this._storage.filter((info) => !info.complete || info.segments.length > levels);
35811 for (const pattern of patterns) {
35812 const section = pattern.sections[0];
35813 /**
35814 * In this case, the pattern has a globstar and we must read all directories unconditionally,
35815 * but only if the level has reached the end of the first group.
35816 *
35817 * fixtures/{a,b}/**
35818 * ^ true/false ^ always true
35819 */
35820 if (!pattern.complete && levels > section.length) {
35821 return true;
35822 }
35823 const match = parts.every((part, index) => {
35824 const segment = pattern.segments[index];
35825 if (segment.dynamic && segment.patternRe.test(part)) {
35826 return true;
35827 }
35828 if (!segment.dynamic && segment.pattern === part) {
35829 return true;
35830 }
35831 return false;
35832 });
35833 if (match) {
35834 return true;
35835 }
35836 }
35837 return false;
35838 }
35839}
35840partial.default = PartialMatcher;
35841
35842Object.defineProperty(deep, "__esModule", { value: true });
35843const utils$4 = utils$8;
35844const partial_1 = partial;
35845class DeepFilter {
35846 constructor(_settings, _micromatchOptions) {
35847 this._settings = _settings;
35848 this._micromatchOptions = _micromatchOptions;
35849 }
35850 getFilter(basePath, positive, negative) {
35851 const matcher = this._getMatcher(positive);
35852 const negativeRe = this._getNegativePatternsRe(negative);
35853 return (entry) => this._filter(basePath, entry, matcher, negativeRe);
35854 }
35855 _getMatcher(patterns) {
35856 return new partial_1.default(patterns, this._settings, this._micromatchOptions);
35857 }
35858 _getNegativePatternsRe(patterns) {
35859 const affectDepthOfReadingPatterns = patterns.filter(utils$4.pattern.isAffectDepthOfReadingPattern);
35860 return utils$4.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions);
35861 }
35862 _filter(basePath, entry, matcher, negativeRe) {
35863 if (this._isSkippedByDeep(basePath, entry.path)) {
35864 return false;
35865 }
35866 if (this._isSkippedSymbolicLink(entry)) {
35867 return false;
35868 }
35869 const filepath = utils$4.path.removeLeadingDotSegment(entry.path);
35870 if (this._isSkippedByPositivePatterns(filepath, matcher)) {
35871 return false;
35872 }
35873 return this._isSkippedByNegativePatterns(filepath, negativeRe);
35874 }
35875 _isSkippedByDeep(basePath, entryPath) {
35876 /**
35877 * Avoid unnecessary depth calculations when it doesn't matter.
35878 */
35879 if (this._settings.deep === Infinity) {
35880 return false;
35881 }
35882 return this._getEntryLevel(basePath, entryPath) >= this._settings.deep;
35883 }
35884 _getEntryLevel(basePath, entryPath) {
35885 const entryPathDepth = entryPath.split('/').length;
35886 if (basePath === '') {
35887 return entryPathDepth;
35888 }
35889 const basePathDepth = basePath.split('/').length;
35890 return entryPathDepth - basePathDepth;
35891 }
35892 _isSkippedSymbolicLink(entry) {
35893 return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink();
35894 }
35895 _isSkippedByPositivePatterns(entryPath, matcher) {
35896 return !this._settings.baseNameMatch && !matcher.match(entryPath);
35897 }
35898 _isSkippedByNegativePatterns(entryPath, patternsRe) {
35899 return !utils$4.pattern.matchAny(entryPath, patternsRe);
35900 }
35901}
35902deep.default = DeepFilter;
35903
35904var entry$1 = {};
35905
35906Object.defineProperty(entry$1, "__esModule", { value: true });
35907const utils$3 = utils$8;
35908class EntryFilter {
35909 constructor(_settings, _micromatchOptions) {
35910 this._settings = _settings;
35911 this._micromatchOptions = _micromatchOptions;
35912 this.index = new Map();
35913 }
35914 getFilter(positive, negative) {
35915 const positiveRe = utils$3.pattern.convertPatternsToRe(positive, this._micromatchOptions);
35916 const negativeRe = utils$3.pattern.convertPatternsToRe(negative, this._micromatchOptions);
35917 return (entry) => this._filter(entry, positiveRe, negativeRe);
35918 }
35919 _filter(entry, positiveRe, negativeRe) {
35920 if (this._settings.unique && this._isDuplicateEntry(entry)) {
35921 return false;
35922 }
35923 if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) {
35924 return false;
35925 }
35926 if (this._isSkippedByAbsoluteNegativePatterns(entry.path, negativeRe)) {
35927 return false;
35928 }
35929 const filepath = this._settings.baseNameMatch ? entry.name : entry.path;
35930 const isMatched = this._isMatchToPatterns(filepath, positiveRe) && !this._isMatchToPatterns(entry.path, negativeRe);
35931 if (this._settings.unique && isMatched) {
35932 this._createIndexRecord(entry);
35933 }
35934 return isMatched;
35935 }
35936 _isDuplicateEntry(entry) {
35937 return this.index.has(entry.path);
35938 }
35939 _createIndexRecord(entry) {
35940 this.index.set(entry.path, undefined);
35941 }
35942 _onlyFileFilter(entry) {
35943 return this._settings.onlyFiles && !entry.dirent.isFile();
35944 }
35945 _onlyDirectoryFilter(entry) {
35946 return this._settings.onlyDirectories && !entry.dirent.isDirectory();
35947 }
35948 _isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) {
35949 if (!this._settings.absolute) {
35950 return false;
35951 }
35952 const fullpath = utils$3.path.makeAbsolute(this._settings.cwd, entryPath);
35953 return utils$3.pattern.matchAny(fullpath, patternsRe);
35954 }
35955 _isMatchToPatterns(entryPath, patternsRe) {
35956 const filepath = utils$3.path.removeLeadingDotSegment(entryPath);
35957 return utils$3.pattern.matchAny(filepath, patternsRe);
35958 }
35959}
35960entry$1.default = EntryFilter;
35961
35962var error$3 = {};
35963
35964Object.defineProperty(error$3, "__esModule", { value: true });
35965const utils$2 = utils$8;
35966class ErrorFilter {
35967 constructor(_settings) {
35968 this._settings = _settings;
35969 }
35970 getFilter() {
35971 return (error) => this._isNonFatalError(error);
35972 }
35973 _isNonFatalError(error) {
35974 return utils$2.errno.isEnoentCodeError(error) || this._settings.suppressErrors;
35975 }
35976}
35977error$3.default = ErrorFilter;
35978
35979var entry = {};
35980
35981Object.defineProperty(entry, "__esModule", { value: true });
35982const utils$1 = utils$8;
35983class EntryTransformer {
35984 constructor(_settings) {
35985 this._settings = _settings;
35986 }
35987 getTransformer() {
35988 return (entry) => this._transform(entry);
35989 }
35990 _transform(entry) {
35991 let filepath = entry.path;
35992 if (this._settings.absolute) {
35993 filepath = utils$1.path.makeAbsolute(this._settings.cwd, filepath);
35994 filepath = utils$1.path.unixify(filepath);
35995 }
35996 if (this._settings.markDirectories && entry.dirent.isDirectory()) {
35997 filepath += '/';
35998 }
35999 if (!this._settings.objectMode) {
36000 return filepath;
36001 }
36002 return Object.assign(Object.assign({}, entry), { path: filepath });
36003 }
36004}
36005entry.default = EntryTransformer;
36006
36007Object.defineProperty(provider, "__esModule", { value: true });
36008const path$d = path__default;
36009const deep_1 = deep;
36010const entry_1 = entry$1;
36011const error_1 = error$3;
36012const entry_2 = entry;
36013class Provider {
36014 constructor(_settings) {
36015 this._settings = _settings;
36016 this.errorFilter = new error_1.default(this._settings);
36017 this.entryFilter = new entry_1.default(this._settings, this._getMicromatchOptions());
36018 this.deepFilter = new deep_1.default(this._settings, this._getMicromatchOptions());
36019 this.entryTransformer = new entry_2.default(this._settings);
36020 }
36021 _getRootDirectory(task) {
36022 return path$d.resolve(this._settings.cwd, task.base);
36023 }
36024 _getReaderOptions(task) {
36025 const basePath = task.base === '.' ? '' : task.base;
36026 return {
36027 basePath,
36028 pathSegmentSeparator: '/',
36029 concurrency: this._settings.concurrency,
36030 deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative),
36031 entryFilter: this.entryFilter.getFilter(task.positive, task.negative),
36032 errorFilter: this.errorFilter.getFilter(),
36033 followSymbolicLinks: this._settings.followSymbolicLinks,
36034 fs: this._settings.fs,
36035 stats: this._settings.stats,
36036 throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink,
36037 transform: this.entryTransformer.getTransformer()
36038 };
36039 }
36040 _getMicromatchOptions() {
36041 return {
36042 dot: this._settings.dot,
36043 matchBase: this._settings.baseNameMatch,
36044 nobrace: !this._settings.braceExpansion,
36045 nocase: !this._settings.caseSensitiveMatch,
36046 noext: !this._settings.extglob,
36047 noglobstar: !this._settings.globstar,
36048 posix: true,
36049 strictSlashes: false
36050 };
36051 }
36052}
36053provider.default = Provider;
36054
36055Object.defineProperty(async, "__esModule", { value: true });
36056const stream_1$2 = stream$4;
36057const provider_1$2 = provider;
36058class ProviderAsync extends provider_1$2.default {
36059 constructor() {
36060 super(...arguments);
36061 this._reader = new stream_1$2.default(this._settings);
36062 }
36063 read(task) {
36064 const root = this._getRootDirectory(task);
36065 const options = this._getReaderOptions(task);
36066 const entries = [];
36067 return new Promise((resolve, reject) => {
36068 const stream = this.api(root, task, options);
36069 stream.once('error', reject);
36070 stream.on('data', (entry) => entries.push(options.transform(entry)));
36071 stream.once('end', () => resolve(entries));
36072 });
36073 }
36074 api(root, task, options) {
36075 if (task.dynamic) {
36076 return this._reader.dynamic(root, options);
36077 }
36078 return this._reader.static(task.patterns, options);
36079 }
36080}
36081async.default = ProviderAsync;
36082
36083var stream$3 = {};
36084
36085Object.defineProperty(stream$3, "__esModule", { value: true });
36086const stream_1$1 = require$$0__default$2;
36087const stream_2 = stream$4;
36088const provider_1$1 = provider;
36089class ProviderStream extends provider_1$1.default {
36090 constructor() {
36091 super(...arguments);
36092 this._reader = new stream_2.default(this._settings);
36093 }
36094 read(task) {
36095 const root = this._getRootDirectory(task);
36096 const options = this._getReaderOptions(task);
36097 const source = this.api(root, task, options);
36098 const destination = new stream_1$1.Readable({ objectMode: true, read: () => { } });
36099 source
36100 .once('error', (error) => destination.emit('error', error))
36101 .on('data', (entry) => destination.emit('data', options.transform(entry)))
36102 .once('end', () => destination.emit('end'));
36103 destination
36104 .once('close', () => source.destroy());
36105 return destination;
36106 }
36107 api(root, task, options) {
36108 if (task.dynamic) {
36109 return this._reader.dynamic(root, options);
36110 }
36111 return this._reader.static(task.patterns, options);
36112 }
36113}
36114stream$3.default = ProviderStream;
36115
36116var sync$4 = {};
36117
36118var sync$3 = {};
36119
36120Object.defineProperty(sync$3, "__esModule", { value: true });
36121const fsStat = out$4;
36122const fsWalk = out$3;
36123const reader_1 = reader;
36124class ReaderSync extends reader_1.default {
36125 constructor() {
36126 super(...arguments);
36127 this._walkSync = fsWalk.walkSync;
36128 this._statSync = fsStat.statSync;
36129 }
36130 dynamic(root, options) {
36131 return this._walkSync(root, options);
36132 }
36133 static(patterns, options) {
36134 const entries = [];
36135 for (const pattern of patterns) {
36136 const filepath = this._getFullEntryPath(pattern);
36137 const entry = this._getEntry(filepath, pattern, options);
36138 if (entry === null || !options.entryFilter(entry)) {
36139 continue;
36140 }
36141 entries.push(entry);
36142 }
36143 return entries;
36144 }
36145 _getEntry(filepath, pattern, options) {
36146 try {
36147 const stats = this._getStat(filepath);
36148 return this._makeEntry(stats, pattern);
36149 }
36150 catch (error) {
36151 if (options.errorFilter(error)) {
36152 return null;
36153 }
36154 throw error;
36155 }
36156 }
36157 _getStat(filepath) {
36158 return this._statSync(filepath, this._fsStatSettings);
36159 }
36160}
36161sync$3.default = ReaderSync;
36162
36163Object.defineProperty(sync$4, "__esModule", { value: true });
36164const sync_1$1 = sync$3;
36165const provider_1 = provider;
36166class ProviderSync extends provider_1.default {
36167 constructor() {
36168 super(...arguments);
36169 this._reader = new sync_1$1.default(this._settings);
36170 }
36171 read(task) {
36172 const root = this._getRootDirectory(task);
36173 const options = this._getReaderOptions(task);
36174 const entries = this.api(root, task, options);
36175 return entries.map(options.transform);
36176 }
36177 api(root, task, options) {
36178 if (task.dynamic) {
36179 return this._reader.dynamic(root, options);
36180 }
36181 return this._reader.static(task.patterns, options);
36182 }
36183}
36184sync$4.default = ProviderSync;
36185
36186var settings = {};
36187
36188(function (exports) {
36189Object.defineProperty(exports, "__esModule", { value: true });
36190exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0;
36191const fs = fs__default;
36192const os = require$$0__default$1;
36193/**
36194 * The `os.cpus` method can return zero. We expect the number of cores to be greater than zero.
36195 * https://github.com/nodejs/node/blob/7faeddf23a98c53896f8b574a6e66589e8fb1eb8/lib/os.js#L106-L107
36196 */
36197const CPU_COUNT = Math.max(os.cpus().length, 1);
36198exports.DEFAULT_FILE_SYSTEM_ADAPTER = {
36199 lstat: fs.lstat,
36200 lstatSync: fs.lstatSync,
36201 stat: fs.stat,
36202 statSync: fs.statSync,
36203 readdir: fs.readdir,
36204 readdirSync: fs.readdirSync
36205};
36206class Settings {
36207 constructor(_options = {}) {
36208 this._options = _options;
36209 this.absolute = this._getValue(this._options.absolute, false);
36210 this.baseNameMatch = this._getValue(this._options.baseNameMatch, false);
36211 this.braceExpansion = this._getValue(this._options.braceExpansion, true);
36212 this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true);
36213 this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT);
36214 this.cwd = this._getValue(this._options.cwd, process.cwd());
36215 this.deep = this._getValue(this._options.deep, Infinity);
36216 this.dot = this._getValue(this._options.dot, false);
36217 this.extglob = this._getValue(this._options.extglob, true);
36218 this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true);
36219 this.fs = this._getFileSystemMethods(this._options.fs);
36220 this.globstar = this._getValue(this._options.globstar, true);
36221 this.ignore = this._getValue(this._options.ignore, []);
36222 this.markDirectories = this._getValue(this._options.markDirectories, false);
36223 this.objectMode = this._getValue(this._options.objectMode, false);
36224 this.onlyDirectories = this._getValue(this._options.onlyDirectories, false);
36225 this.onlyFiles = this._getValue(this._options.onlyFiles, true);
36226 this.stats = this._getValue(this._options.stats, false);
36227 this.suppressErrors = this._getValue(this._options.suppressErrors, false);
36228 this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false);
36229 this.unique = this._getValue(this._options.unique, true);
36230 if (this.onlyDirectories) {
36231 this.onlyFiles = false;
36232 }
36233 if (this.stats) {
36234 this.objectMode = true;
36235 }
36236 }
36237 _getValue(option, value) {
36238 return option === undefined ? value : option;
36239 }
36240 _getFileSystemMethods(methods = {}) {
36241 return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods);
36242 }
36243}
36244exports.default = Settings;
36245}(settings));
36246
36247const taskManager = tasks;
36248const async_1 = async;
36249const stream_1 = stream$3;
36250const sync_1 = sync$4;
36251const settings_1 = settings;
36252const utils = utils$8;
36253async function FastGlob(source, options) {
36254 assertPatternsInput$1(source);
36255 const works = getWorks(source, async_1.default, options);
36256 const result = await Promise.all(works);
36257 return utils.array.flatten(result);
36258}
36259// https://github.com/typescript-eslint/typescript-eslint/issues/60
36260// eslint-disable-next-line no-redeclare
36261(function (FastGlob) {
36262 function sync(source, options) {
36263 assertPatternsInput$1(source);
36264 const works = getWorks(source, sync_1.default, options);
36265 return utils.array.flatten(works);
36266 }
36267 FastGlob.sync = sync;
36268 function stream(source, options) {
36269 assertPatternsInput$1(source);
36270 const works = getWorks(source, stream_1.default, options);
36271 /**
36272 * The stream returned by the provider cannot work with an asynchronous iterator.
36273 * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams.
36274 * This affects performance (+25%). I don't see best solution right now.
36275 */
36276 return utils.stream.merge(works);
36277 }
36278 FastGlob.stream = stream;
36279 function generateTasks(source, options) {
36280 assertPatternsInput$1(source);
36281 const patterns = [].concat(source);
36282 const settings = new settings_1.default(options);
36283 return taskManager.generate(patterns, settings);
36284 }
36285 FastGlob.generateTasks = generateTasks;
36286 function isDynamicPattern(source, options) {
36287 assertPatternsInput$1(source);
36288 const settings = new settings_1.default(options);
36289 return utils.pattern.isDynamicPattern(source, settings);
36290 }
36291 FastGlob.isDynamicPattern = isDynamicPattern;
36292 function escapePath(source) {
36293 assertPatternsInput$1(source);
36294 return utils.path.escape(source);
36295 }
36296 FastGlob.escapePath = escapePath;
36297})(FastGlob || (FastGlob = {}));
36298function getWorks(source, _Provider, options) {
36299 const patterns = [].concat(source);
36300 const settings = new settings_1.default(options);
36301 const tasks = taskManager.generate(patterns, settings);
36302 const provider = new _Provider(settings);
36303 return tasks.map(provider.read, provider);
36304}
36305function assertPatternsInput$1(input) {
36306 const source = [].concat(input);
36307 const isValidSource = source.every((item) => utils.string.isString(item) && !utils.string.isEmpty(item));
36308 if (!isValidSource) {
36309 throw new TypeError('Patterns must be a string (non empty) or an array of strings');
36310 }
36311}
36312var out = FastGlob;
36313
36314var dirGlob$1 = {exports: {}};
36315
36316var pathType$1 = {};
36317
36318const {promisify: promisify$6} = require$$0__default$3;
36319const fs$e = fs__default;
36320
36321async function isType(fsStatType, statsMethodName, filePath) {
36322 if (typeof filePath !== 'string') {
36323 throw new TypeError(`Expected a string, got ${typeof filePath}`);
36324 }
36325
36326 try {
36327 const stats = await promisify$6(fs$e[fsStatType])(filePath);
36328 return stats[statsMethodName]();
36329 } catch (error) {
36330 if (error.code === 'ENOENT') {
36331 return false;
36332 }
36333
36334 throw error;
36335 }
36336}
36337
36338function isTypeSync(fsStatType, statsMethodName, filePath) {
36339 if (typeof filePath !== 'string') {
36340 throw new TypeError(`Expected a string, got ${typeof filePath}`);
36341 }
36342
36343 try {
36344 return fs$e[fsStatType](filePath)[statsMethodName]();
36345 } catch (error) {
36346 if (error.code === 'ENOENT') {
36347 return false;
36348 }
36349
36350 throw error;
36351 }
36352}
36353
36354pathType$1.isFile = isType.bind(null, 'stat', 'isFile');
36355pathType$1.isDirectory = isType.bind(null, 'stat', 'isDirectory');
36356pathType$1.isSymlink = isType.bind(null, 'lstat', 'isSymbolicLink');
36357pathType$1.isFileSync = isTypeSync.bind(null, 'statSync', 'isFile');
36358pathType$1.isDirectorySync = isTypeSync.bind(null, 'statSync', 'isDirectory');
36359pathType$1.isSymlinkSync = isTypeSync.bind(null, 'lstatSync', 'isSymbolicLink');
36360
36361const path$c = path__default;
36362const pathType = pathType$1;
36363
36364const getExtensions = extensions => extensions.length > 1 ? `{${extensions.join(',')}}` : extensions[0];
36365
36366const getPath = (filepath, cwd) => {
36367 const pth = filepath[0] === '!' ? filepath.slice(1) : filepath;
36368 return path$c.isAbsolute(pth) ? pth : path$c.join(cwd, pth);
36369};
36370
36371const addExtensions = (file, extensions) => {
36372 if (path$c.extname(file)) {
36373 return `**/${file}`;
36374 }
36375
36376 return `**/${file}.${getExtensions(extensions)}`;
36377};
36378
36379const getGlob = (directory, options) => {
36380 if (options.files && !Array.isArray(options.files)) {
36381 throw new TypeError(`Expected \`files\` to be of type \`Array\` but received type \`${typeof options.files}\``);
36382 }
36383
36384 if (options.extensions && !Array.isArray(options.extensions)) {
36385 throw new TypeError(`Expected \`extensions\` to be of type \`Array\` but received type \`${typeof options.extensions}\``);
36386 }
36387
36388 if (options.files && options.extensions) {
36389 return options.files.map(x => path$c.posix.join(directory, addExtensions(x, options.extensions)));
36390 }
36391
36392 if (options.files) {
36393 return options.files.map(x => path$c.posix.join(directory, `**/${x}`));
36394 }
36395
36396 if (options.extensions) {
36397 return [path$c.posix.join(directory, `**/*.${getExtensions(options.extensions)}`)];
36398 }
36399
36400 return [path$c.posix.join(directory, '**')];
36401};
36402
36403dirGlob$1.exports = async (input, options) => {
36404 options = {
36405 cwd: process.cwd(),
36406 ...options
36407 };
36408
36409 if (typeof options.cwd !== 'string') {
36410 throw new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof options.cwd}\``);
36411 }
36412
36413 const globs = await Promise.all([].concat(input).map(async x => {
36414 const isDirectory = await pathType.isDirectory(getPath(x, options.cwd));
36415 return isDirectory ? getGlob(x, options) : x;
36416 }));
36417
36418 return [].concat.apply([], globs); // eslint-disable-line prefer-spread
36419};
36420
36421dirGlob$1.exports.sync = (input, options) => {
36422 options = {
36423 cwd: process.cwd(),
36424 ...options
36425 };
36426
36427 if (typeof options.cwd !== 'string') {
36428 throw new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof options.cwd}\``);
36429 }
36430
36431 const globs = [].concat(input).map(x => pathType.isDirectorySync(getPath(x, options.cwd)) ? getGlob(x, options) : x);
36432
36433 return [].concat.apply([], globs); // eslint-disable-line prefer-spread
36434};
36435
36436var gitignore$1 = {exports: {}};
36437
36438// A simple implementation of make-array
36439function makeArray (subject) {
36440 return Array.isArray(subject)
36441 ? subject
36442 : [subject]
36443}
36444
36445const EMPTY = '';
36446const SPACE = ' ';
36447const ESCAPE = '\\';
36448const REGEX_TEST_BLANK_LINE = /^\s+$/;
36449const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
36450const REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/;
36451const REGEX_SPLITALL_CRLF = /\r?\n/g;
36452// /foo,
36453// ./foo,
36454// ../foo,
36455// .
36456// ..
36457const REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/;
36458
36459const SLASH$1 = '/';
36460const KEY_IGNORE = typeof Symbol !== 'undefined'
36461 ? Symbol.for('node-ignore')
36462 /* istanbul ignore next */
36463 : 'node-ignore';
36464
36465const define = (object, key, value) =>
36466 Object.defineProperty(object, key, {value});
36467
36468const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g;
36469
36470// Sanitize the range of a regular expression
36471// The cases are complicated, see test cases for details
36472const sanitizeRange = range => range.replace(
36473 REGEX_REGEXP_RANGE,
36474 (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0)
36475 ? match
36476 // Invalid range (out of order) which is ok for gitignore rules but
36477 // fatal for JavaScript regular expression, so eliminate it.
36478 : EMPTY
36479);
36480
36481// See fixtures #59
36482const cleanRangeBackSlash = slashes => {
36483 const {length} = slashes;
36484 return slashes.slice(0, length - length % 2)
36485};
36486
36487// > If the pattern ends with a slash,
36488// > it is removed for the purpose of the following description,
36489// > but it would only find a match with a directory.
36490// > In other words, foo/ will match a directory foo and paths underneath it,
36491// > but will not match a regular file or a symbolic link foo
36492// > (this is consistent with the way how pathspec works in general in Git).
36493// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'
36494// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call
36495// you could use option `mark: true` with `glob`
36496
36497// '`foo/`' should not continue with the '`..`'
36498const REPLACERS = [
36499
36500 // > Trailing spaces are ignored unless they are quoted with backslash ("\")
36501 [
36502 // (a\ ) -> (a )
36503 // (a ) -> (a)
36504 // (a \ ) -> (a )
36505 /\\?\s+$/,
36506 match => match.indexOf('\\') === 0
36507 ? SPACE
36508 : EMPTY
36509 ],
36510
36511 // replace (\ ) with ' '
36512 [
36513 /\\\s/g,
36514 () => SPACE
36515 ],
36516
36517 // Escape metacharacters
36518 // which is written down by users but means special for regular expressions.
36519
36520 // > There are 12 characters with special meanings:
36521 // > - the backslash \,
36522 // > - the caret ^,
36523 // > - the dollar sign $,
36524 // > - the period or dot .,
36525 // > - the vertical bar or pipe symbol |,
36526 // > - the question mark ?,
36527 // > - the asterisk or star *,
36528 // > - the plus sign +,
36529 // > - the opening parenthesis (,
36530 // > - the closing parenthesis ),
36531 // > - and the opening square bracket [,
36532 // > - the opening curly brace {,
36533 // > These special characters are often called "metacharacters".
36534 [
36535 /[\\$.|*+(){^]/g,
36536 match => `\\${match}`
36537 ],
36538
36539 [
36540 // > a question mark (?) matches a single character
36541 /(?!\\)\?/g,
36542 () => '[^/]'
36543 ],
36544
36545 // leading slash
36546 [
36547
36548 // > A leading slash matches the beginning of the pathname.
36549 // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
36550 // A leading slash matches the beginning of the pathname
36551 /^\//,
36552 () => '^'
36553 ],
36554
36555 // replace special metacharacter slash after the leading slash
36556 [
36557 /\//g,
36558 () => '\\/'
36559 ],
36560
36561 [
36562 // > A leading "**" followed by a slash means match in all directories.
36563 // > For example, "**/foo" matches file or directory "foo" anywhere,
36564 // > the same as pattern "foo".
36565 // > "**/foo/bar" matches file or directory "bar" anywhere that is directly
36566 // > under directory "foo".
36567 // Notice that the '*'s have been replaced as '\\*'
36568 /^\^*\\\*\\\*\\\//,
36569
36570 // '**/foo' <-> 'foo'
36571 () => '^(?:.*\\/)?'
36572 ],
36573
36574 // starting
36575 [
36576 // there will be no leading '/'
36577 // (which has been replaced by section "leading slash")
36578 // If starts with '**', adding a '^' to the regular expression also works
36579 /^(?=[^^])/,
36580 function startingReplacer () {
36581 // If has a slash `/` at the beginning or middle
36582 return !/\/(?!$)/.test(this)
36583 // > Prior to 2.22.1
36584 // > If the pattern does not contain a slash /,
36585 // > Git treats it as a shell glob pattern
36586 // Actually, if there is only a trailing slash,
36587 // git also treats it as a shell glob pattern
36588
36589 // After 2.22.1 (compatible but clearer)
36590 // > If there is a separator at the beginning or middle (or both)
36591 // > of the pattern, then the pattern is relative to the directory
36592 // > level of the particular .gitignore file itself.
36593 // > Otherwise the pattern may also match at any level below
36594 // > the .gitignore level.
36595 ? '(?:^|\\/)'
36596
36597 // > Otherwise, Git treats the pattern as a shell glob suitable for
36598 // > consumption by fnmatch(3)
36599 : '^'
36600 }
36601 ],
36602
36603 // two globstars
36604 [
36605 // Use lookahead assertions so that we could match more than one `'/**'`
36606 /\\\/\\\*\\\*(?=\\\/|$)/g,
36607
36608 // Zero, one or several directories
36609 // should not use '*', or it will be replaced by the next replacer
36610
36611 // Check if it is not the last `'/**'`
36612 (_, index, str) => index + 6 < str.length
36613
36614 // case: /**/
36615 // > A slash followed by two consecutive asterisks then a slash matches
36616 // > zero or more directories.
36617 // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on.
36618 // '/**/'
36619 ? '(?:\\/[^\\/]+)*'
36620
36621 // case: /**
36622 // > A trailing `"/**"` matches everything inside.
36623
36624 // #21: everything inside but it should not include the current folder
36625 : '\\/.+'
36626 ],
36627
36628 // intermediate wildcards
36629 [
36630 // Never replace escaped '*'
36631 // ignore rule '\*' will match the path '*'
36632
36633 // 'abc.*/' -> go
36634 // 'abc.*' -> skip this rule
36635 /(^|[^\\]+)\\\*(?=.+)/g,
36636
36637 // '*.js' matches '.js'
36638 // '*.js' doesn't match 'abc'
36639 (_, p1) => `${p1}[^\\/]*`
36640 ],
36641
36642 [
36643 // unescape, revert step 3 except for back slash
36644 // For example, if a user escape a '\\*',
36645 // after step 3, the result will be '\\\\\\*'
36646 /\\\\\\(?=[$.|*+(){^])/g,
36647 () => ESCAPE
36648 ],
36649
36650 [
36651 // '\\\\' -> '\\'
36652 /\\\\/g,
36653 () => ESCAPE
36654 ],
36655
36656 [
36657 // > The range notation, e.g. [a-zA-Z],
36658 // > can be used to match one of the characters in a range.
36659
36660 // `\` is escaped by step 3
36661 /(\\)?\[([^\]/]*?)(\\*)($|\])/g,
36662 (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE
36663 // '\\[bar]' -> '\\\\[bar\\]'
36664 ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}`
36665 : close === ']'
36666 ? endEscape.length % 2 === 0
36667 // A normal case, and it is a range notation
36668 // '[bar]'
36669 // '[bar\\\\]'
36670 ? `[${sanitizeRange(range)}${endEscape}]`
36671 // Invalid range notaton
36672 // '[bar\\]' -> '[bar\\\\]'
36673 : '[]'
36674 : '[]'
36675 ],
36676
36677 // ending
36678 [
36679 // 'js' will not match 'js.'
36680 // 'ab' will not match 'abc'
36681 /(?:[^*])$/,
36682
36683 // WTF!
36684 // https://git-scm.com/docs/gitignore
36685 // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)
36686 // which re-fixes #24, #38
36687
36688 // > If there is a separator at the end of the pattern then the pattern
36689 // > will only match directories, otherwise the pattern can match both
36690 // > files and directories.
36691
36692 // 'js*' will not match 'a.js'
36693 // 'js/' will not match 'a.js'
36694 // 'js' will match 'a.js' and 'a.js/'
36695 match => /\/$/.test(match)
36696 // foo/ will not match 'foo'
36697 ? `${match}$`
36698 // foo matches 'foo' and 'foo/'
36699 : `${match}(?=$|\\/$)`
36700 ],
36701
36702 // trailing wildcard
36703 [
36704 /(\^|\\\/)?\\\*$/,
36705 (_, p1) => {
36706 const prefix = p1
36707 // '\^':
36708 // '/*' does not match EMPTY
36709 // '/*' does not match everything
36710
36711 // '\\\/':
36712 // 'abc/*' does not match 'abc/'
36713 ? `${p1}[^/]+`
36714
36715 // 'a*' matches 'a'
36716 // 'a*' matches 'aa'
36717 : '[^/]*';
36718
36719 return `${prefix}(?=$|\\/$)`
36720 }
36721 ],
36722];
36723
36724// A simple cache, because an ignore rule only has only one certain meaning
36725const regexCache = Object.create(null);
36726
36727// @param {pattern}
36728const makeRegex = (pattern, negative, ignorecase) => {
36729 const r = regexCache[pattern];
36730 if (r) {
36731 return r
36732 }
36733
36734 // const replacers = negative
36735 // ? NEGATIVE_REPLACERS
36736 // : POSITIVE_REPLACERS
36737
36738 const source = REPLACERS.reduce(
36739 (prev, current) => prev.replace(current[0], current[1].bind(pattern)),
36740 pattern
36741 );
36742
36743 return regexCache[pattern] = ignorecase
36744 ? new RegExp(source, 'i')
36745 : new RegExp(source)
36746};
36747
36748const isString = subject => typeof subject === 'string';
36749
36750// > A blank line matches no files, so it can serve as a separator for readability.
36751const checkPattern = pattern => pattern
36752 && isString(pattern)
36753 && !REGEX_TEST_BLANK_LINE.test(pattern)
36754
36755 // > A line starting with # serves as a comment.
36756 && pattern.indexOf('#') !== 0;
36757
36758const splitPattern = pattern => pattern.split(REGEX_SPLITALL_CRLF);
36759
36760class IgnoreRule {
36761 constructor (
36762 origin,
36763 pattern,
36764 negative,
36765 regex
36766 ) {
36767 this.origin = origin;
36768 this.pattern = pattern;
36769 this.negative = negative;
36770 this.regex = regex;
36771 }
36772}
36773
36774const createRule = (pattern, ignorecase) => {
36775 const origin = pattern;
36776 let negative = false;
36777
36778 // > An optional prefix "!" which negates the pattern;
36779 if (pattern.indexOf('!') === 0) {
36780 negative = true;
36781 pattern = pattern.substr(1);
36782 }
36783
36784 pattern = pattern
36785 // > Put a backslash ("\") in front of the first "!" for patterns that
36786 // > begin with a literal "!", for example, `"\!important!.txt"`.
36787 .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!')
36788 // > Put a backslash ("\") in front of the first hash for patterns that
36789 // > begin with a hash.
36790 .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#');
36791
36792 const regex = makeRegex(pattern, negative, ignorecase);
36793
36794 return new IgnoreRule(
36795 origin,
36796 pattern,
36797 negative,
36798 regex
36799 )
36800};
36801
36802const throwError = (message, Ctor) => {
36803 throw new Ctor(message)
36804};
36805
36806const checkPath = (path, originalPath, doThrow) => {
36807 if (!isString(path)) {
36808 return doThrow(
36809 `path must be a string, but got \`${originalPath}\``,
36810 TypeError
36811 )
36812 }
36813
36814 // We don't know if we should ignore EMPTY, so throw
36815 if (!path) {
36816 return doThrow(`path must not be empty`, TypeError)
36817 }
36818
36819 // Check if it is a relative path
36820 if (checkPath.isNotRelative(path)) {
36821 const r = '`path.relative()`d';
36822 return doThrow(
36823 `path should be a ${r} string, but got "${originalPath}"`,
36824 RangeError
36825 )
36826 }
36827
36828 return true
36829};
36830
36831const isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path);
36832
36833checkPath.isNotRelative = isNotRelative;
36834checkPath.convert = p => p;
36835
36836class Ignore {
36837 constructor ({
36838 ignorecase = true
36839 } = {}) {
36840 this._rules = [];
36841 this._ignorecase = ignorecase;
36842 define(this, KEY_IGNORE, true);
36843 this._initCache();
36844 }
36845
36846 _initCache () {
36847 this._ignoreCache = Object.create(null);
36848 this._testCache = Object.create(null);
36849 }
36850
36851 _addPattern (pattern) {
36852 // #32
36853 if (pattern && pattern[KEY_IGNORE]) {
36854 this._rules = this._rules.concat(pattern._rules);
36855 this._added = true;
36856 return
36857 }
36858
36859 if (checkPattern(pattern)) {
36860 const rule = createRule(pattern, this._ignorecase);
36861 this._added = true;
36862 this._rules.push(rule);
36863 }
36864 }
36865
36866 // @param {Array<string> | string | Ignore} pattern
36867 add (pattern) {
36868 this._added = false;
36869
36870 makeArray(
36871 isString(pattern)
36872 ? splitPattern(pattern)
36873 : pattern
36874 ).forEach(this._addPattern, this);
36875
36876 // Some rules have just added to the ignore,
36877 // making the behavior changed.
36878 if (this._added) {
36879 this._initCache();
36880 }
36881
36882 return this
36883 }
36884
36885 // legacy
36886 addPattern (pattern) {
36887 return this.add(pattern)
36888 }
36889
36890 // | ignored : unignored
36891 // negative | 0:0 | 0:1 | 1:0 | 1:1
36892 // -------- | ------- | ------- | ------- | --------
36893 // 0 | TEST | TEST | SKIP | X
36894 // 1 | TESTIF | SKIP | TEST | X
36895
36896 // - SKIP: always skip
36897 // - TEST: always test
36898 // - TESTIF: only test if checkUnignored
36899 // - X: that never happen
36900
36901 // @param {boolean} whether should check if the path is unignored,
36902 // setting `checkUnignored` to `false` could reduce additional
36903 // path matching.
36904
36905 // @returns {TestResult} true if a file is ignored
36906 _testOne (path, checkUnignored) {
36907 let ignored = false;
36908 let unignored = false;
36909
36910 this._rules.forEach(rule => {
36911 const {negative} = rule;
36912 if (
36913 unignored === negative && ignored !== unignored
36914 || negative && !ignored && !unignored && !checkUnignored
36915 ) {
36916 return
36917 }
36918
36919 const matched = rule.regex.test(path);
36920
36921 if (matched) {
36922 ignored = !negative;
36923 unignored = negative;
36924 }
36925 });
36926
36927 return {
36928 ignored,
36929 unignored
36930 }
36931 }
36932
36933 // @returns {TestResult}
36934 _test (originalPath, cache, checkUnignored, slices) {
36935 const path = originalPath
36936 // Supports nullable path
36937 && checkPath.convert(originalPath);
36938
36939 checkPath(path, originalPath, throwError);
36940
36941 return this._t(path, cache, checkUnignored, slices)
36942 }
36943
36944 _t (path, cache, checkUnignored, slices) {
36945 if (path in cache) {
36946 return cache[path]
36947 }
36948
36949 if (!slices) {
36950 // path/to/a.js
36951 // ['path', 'to', 'a.js']
36952 slices = path.split(SLASH$1);
36953 }
36954
36955 slices.pop();
36956
36957 // If the path has no parent directory, just test it
36958 if (!slices.length) {
36959 return cache[path] = this._testOne(path, checkUnignored)
36960 }
36961
36962 const parent = this._t(
36963 slices.join(SLASH$1) + SLASH$1,
36964 cache,
36965 checkUnignored,
36966 slices
36967 );
36968
36969 // If the path contains a parent directory, check the parent first
36970 return cache[path] = parent.ignored
36971 // > It is not possible to re-include a file if a parent directory of
36972 // > that file is excluded.
36973 ? parent
36974 : this._testOne(path, checkUnignored)
36975 }
36976
36977 ignores (path) {
36978 return this._test(path, this._ignoreCache, false).ignored
36979 }
36980
36981 createFilter () {
36982 return path => !this.ignores(path)
36983 }
36984
36985 filter (paths) {
36986 return makeArray(paths).filter(this.createFilter())
36987 }
36988
36989 // @returns {TestResult}
36990 test (path) {
36991 return this._test(path, this._testCache, true)
36992 }
36993}
36994
36995const factory = options => new Ignore(options);
36996
36997const returnFalse = () => false;
36998
36999const isPathValid = path =>
37000 checkPath(path && checkPath.convert(path), path, returnFalse);
37001
37002factory.isPathValid = isPathValid;
37003
37004// Fixes typescript
37005factory.default = factory;
37006
37007var ignore = factory;
37008
37009// Windows
37010// --------------------------------------------------------------
37011/* istanbul ignore if */
37012if (
37013 // Detect `process` so that it can run in browsers.
37014 typeof process !== 'undefined'
37015 && (
37016 process.env && process.env.IGNORE_TEST_WIN32
37017 || process.platform === 'win32'
37018 )
37019) {
37020 /* eslint no-control-regex: "off" */
37021 const makePosix = str => /^\\\\\?\\/.test(str)
37022 || /["<>|\u0000-\u001F]+/u.test(str)
37023 ? str
37024 : str.replace(/\\/g, '/');
37025
37026 checkPath.convert = makePosix;
37027
37028 // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/'
37029 // 'd:\\foo'
37030 const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
37031 checkPath.isNotRelative = path =>
37032 REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path)
37033 || isNotRelative(path);
37034}
37035
37036var slash$1 = path => {
37037 const isExtendedLengthPath = /^\\\\\?\\/.test(path);
37038 const hasNonAscii = /[^\u0000-\u0080]+/.test(path); // eslint-disable-line no-control-regex
37039
37040 if (isExtendedLengthPath || hasNonAscii) {
37041 return path;
37042 }
37043
37044 return path.replace(/\\/g, '/');
37045};
37046
37047const {promisify: promisify$5} = require$$0__default$3;
37048const fs$d = fs__default;
37049const path$b = path__default;
37050const fastGlob$1 = out;
37051const gitIgnore = ignore;
37052const slash = slash$1;
37053
37054const DEFAULT_IGNORE = [
37055 '**/node_modules/**',
37056 '**/flow-typed/**',
37057 '**/coverage/**',
37058 '**/.git'
37059];
37060
37061const readFileP = promisify$5(fs$d.readFile);
37062
37063const mapGitIgnorePatternTo = base => ignore => {
37064 if (ignore.startsWith('!')) {
37065 return '!' + path$b.posix.join(base, ignore.slice(1));
37066 }
37067
37068 return path$b.posix.join(base, ignore);
37069};
37070
37071const parseGitIgnore = (content, options) => {
37072 const base = slash(path$b.relative(options.cwd, path$b.dirname(options.fileName)));
37073
37074 return content
37075 .split(/\r?\n/)
37076 .filter(Boolean)
37077 .filter(line => !line.startsWith('#'))
37078 .map(mapGitIgnorePatternTo(base));
37079};
37080
37081const reduceIgnore = files => {
37082 const ignores = gitIgnore();
37083 for (const file of files) {
37084 ignores.add(parseGitIgnore(file.content, {
37085 cwd: file.cwd,
37086 fileName: file.filePath
37087 }));
37088 }
37089
37090 return ignores;
37091};
37092
37093const ensureAbsolutePathForCwd = (cwd, p) => {
37094 cwd = slash(cwd);
37095 if (path$b.isAbsolute(p)) {
37096 if (slash(p).startsWith(cwd)) {
37097 return p;
37098 }
37099
37100 throw new Error(`Path ${p} is not in cwd ${cwd}`);
37101 }
37102
37103 return path$b.join(cwd, p);
37104};
37105
37106const getIsIgnoredPredecate = (ignores, cwd) => {
37107 return p => ignores.ignores(slash(path$b.relative(cwd, ensureAbsolutePathForCwd(cwd, p.path || p))));
37108};
37109
37110const getFile = async (file, cwd) => {
37111 const filePath = path$b.join(cwd, file);
37112 const content = await readFileP(filePath, 'utf8');
37113
37114 return {
37115 cwd,
37116 filePath,
37117 content
37118 };
37119};
37120
37121const getFileSync = (file, cwd) => {
37122 const filePath = path$b.join(cwd, file);
37123 const content = fs$d.readFileSync(filePath, 'utf8');
37124
37125 return {
37126 cwd,
37127 filePath,
37128 content
37129 };
37130};
37131
37132const normalizeOptions = ({
37133 ignore = [],
37134 cwd = slash(process.cwd())
37135} = {}) => {
37136 return {ignore, cwd};
37137};
37138
37139gitignore$1.exports = async options => {
37140 options = normalizeOptions(options);
37141
37142 const paths = await fastGlob$1('**/.gitignore', {
37143 ignore: DEFAULT_IGNORE.concat(options.ignore),
37144 cwd: options.cwd
37145 });
37146
37147 const files = await Promise.all(paths.map(file => getFile(file, options.cwd)));
37148 const ignores = reduceIgnore(files);
37149
37150 return getIsIgnoredPredecate(ignores, options.cwd);
37151};
37152
37153gitignore$1.exports.sync = options => {
37154 options = normalizeOptions(options);
37155
37156 const paths = fastGlob$1.sync('**/.gitignore', {
37157 ignore: DEFAULT_IGNORE.concat(options.ignore),
37158 cwd: options.cwd
37159 });
37160
37161 const files = paths.map(file => getFileSync(file, options.cwd));
37162 const ignores = reduceIgnore(files);
37163
37164 return getIsIgnoredPredecate(ignores, options.cwd);
37165};
37166
37167const {Transform} = require$$0__default$2;
37168
37169class ObjectTransform extends Transform {
37170 constructor() {
37171 super({
37172 objectMode: true
37173 });
37174 }
37175}
37176
37177class FilterStream$1 extends ObjectTransform {
37178 constructor(filter) {
37179 super();
37180 this._filter = filter;
37181 }
37182
37183 _transform(data, encoding, callback) {
37184 if (this._filter(data)) {
37185 this.push(data);
37186 }
37187
37188 callback();
37189 }
37190}
37191
37192class UniqueStream$1 extends ObjectTransform {
37193 constructor() {
37194 super();
37195 this._pushed = new Set();
37196 }
37197
37198 _transform(data, encoding, callback) {
37199 if (!this._pushed.has(data)) {
37200 this.push(data);
37201 this._pushed.add(data);
37202 }
37203
37204 callback();
37205 }
37206}
37207
37208var streamUtils = {
37209 FilterStream: FilterStream$1,
37210 UniqueStream: UniqueStream$1
37211};
37212
37213const fs$c = fs__default;
37214const arrayUnion = arrayUnion$1;
37215const merge2 = merge2_1;
37216const fastGlob = out;
37217const dirGlob = dirGlob$1.exports;
37218const gitignore = gitignore$1.exports;
37219const {FilterStream, UniqueStream} = streamUtils;
37220
37221const DEFAULT_FILTER = () => false;
37222
37223const isNegative = pattern => pattern[0] === '!';
37224
37225const assertPatternsInput = patterns => {
37226 if (!patterns.every(pattern => typeof pattern === 'string')) {
37227 throw new TypeError('Patterns must be a string or an array of strings');
37228 }
37229};
37230
37231const checkCwdOption = (options = {}) => {
37232 if (!options.cwd) {
37233 return;
37234 }
37235
37236 let stat;
37237 try {
37238 stat = fs$c.statSync(options.cwd);
37239 } catch {
37240 return;
37241 }
37242
37243 if (!stat.isDirectory()) {
37244 throw new Error('The `cwd` option must be a path to a directory');
37245 }
37246};
37247
37248const getPathString = p => p.stats instanceof fs$c.Stats ? p.path : p;
37249
37250const generateGlobTasks = (patterns, taskOptions) => {
37251 patterns = arrayUnion([].concat(patterns));
37252 assertPatternsInput(patterns);
37253 checkCwdOption(taskOptions);
37254
37255 const globTasks = [];
37256
37257 taskOptions = {
37258 ignore: [],
37259 expandDirectories: true,
37260 ...taskOptions
37261 };
37262
37263 for (const [index, pattern] of patterns.entries()) {
37264 if (isNegative(pattern)) {
37265 continue;
37266 }
37267
37268 const ignore = patterns
37269 .slice(index)
37270 .filter(pattern => isNegative(pattern))
37271 .map(pattern => pattern.slice(1));
37272
37273 const options = {
37274 ...taskOptions,
37275 ignore: taskOptions.ignore.concat(ignore)
37276 };
37277
37278 globTasks.push({pattern, options});
37279 }
37280
37281 return globTasks;
37282};
37283
37284const globDirs = (task, fn) => {
37285 let options = {};
37286 if (task.options.cwd) {
37287 options.cwd = task.options.cwd;
37288 }
37289
37290 if (Array.isArray(task.options.expandDirectories)) {
37291 options = {
37292 ...options,
37293 files: task.options.expandDirectories
37294 };
37295 } else if (typeof task.options.expandDirectories === 'object') {
37296 options = {
37297 ...options,
37298 ...task.options.expandDirectories
37299 };
37300 }
37301
37302 return fn(task.pattern, options);
37303};
37304
37305const getPattern = (task, fn) => task.options.expandDirectories ? globDirs(task, fn) : [task.pattern];
37306
37307const getFilterSync = options => {
37308 return options && options.gitignore ?
37309 gitignore.sync({cwd: options.cwd, ignore: options.ignore}) :
37310 DEFAULT_FILTER;
37311};
37312
37313const globToTask = task => glob => {
37314 const {options} = task;
37315 if (options.ignore && Array.isArray(options.ignore) && options.expandDirectories) {
37316 options.ignore = dirGlob.sync(options.ignore);
37317 }
37318
37319 return {
37320 pattern: glob,
37321 options
37322 };
37323};
37324
37325globby$1.exports = async (patterns, options) => {
37326 const globTasks = generateGlobTasks(patterns, options);
37327
37328 const getFilter = async () => {
37329 return options && options.gitignore ?
37330 gitignore({cwd: options.cwd, ignore: options.ignore}) :
37331 DEFAULT_FILTER;
37332 };
37333
37334 const getTasks = async () => {
37335 const tasks = await Promise.all(globTasks.map(async task => {
37336 const globs = await getPattern(task, dirGlob);
37337 return Promise.all(globs.map(globToTask(task)));
37338 }));
37339
37340 return arrayUnion(...tasks);
37341 };
37342
37343 const [filter, tasks] = await Promise.all([getFilter(), getTasks()]);
37344 const paths = await Promise.all(tasks.map(task => fastGlob(task.pattern, task.options)));
37345
37346 return arrayUnion(...paths).filter(path_ => !filter(getPathString(path_)));
37347};
37348
37349globby$1.exports.sync = (patterns, options) => {
37350 const globTasks = generateGlobTasks(patterns, options);
37351
37352 const tasks = [];
37353 for (const task of globTasks) {
37354 const newTask = getPattern(task, dirGlob.sync).map(globToTask(task));
37355 tasks.push(...newTask);
37356 }
37357
37358 const filter = getFilterSync(options);
37359
37360 let matches = [];
37361 for (const task of tasks) {
37362 matches = arrayUnion(matches, fastGlob.sync(task.pattern, task.options));
37363 }
37364
37365 return matches.filter(path_ => !filter(path_));
37366};
37367
37368globby$1.exports.stream = (patterns, options) => {
37369 const globTasks = generateGlobTasks(patterns, options);
37370
37371 const tasks = [];
37372 for (const task of globTasks) {
37373 const newTask = getPattern(task, dirGlob.sync).map(globToTask(task));
37374 tasks.push(...newTask);
37375 }
37376
37377 const filter = getFilterSync(options);
37378 const filterStream = new FilterStream(p => !filter(p));
37379 const uniqueStream = new UniqueStream();
37380
37381 return merge2(tasks.map(task => fastGlob.stream(task.pattern, task.options)))
37382 .pipe(filterStream)
37383 .pipe(uniqueStream);
37384};
37385
37386globby$1.exports.generateGlobTasks = generateGlobTasks;
37387
37388globby$1.exports.hasMagic = (patterns, options) => []
37389 .concat(patterns)
37390 .some(pattern => fastGlob.isDynamicPattern(pattern, options));
37391
37392globby$1.exports.gitignore = gitignore;
37393
37394var globby = globby$1.exports;
37395
37396class VariableDynamicImportError extends Error {}
37397
37398/* eslint-disable-next-line no-template-curly-in-string */
37399const example = 'For example: import(`./foo/${bar}.js`).';
37400
37401function sanitizeString(str) {
37402 if (str.includes('*')) {
37403 throw new VariableDynamicImportError('A dynamic import cannot contain * characters.');
37404 }
37405 return str;
37406}
37407
37408function templateLiteralToGlob(node) {
37409 let glob = '';
37410
37411 for (let i = 0; i < node.quasis.length; i += 1) {
37412 glob += sanitizeString(node.quasis[i].value.raw);
37413 if (node.expressions[i]) {
37414 glob += expressionToGlob(node.expressions[i]);
37415 }
37416 }
37417
37418 return glob;
37419}
37420
37421function callExpressionToGlob(node) {
37422 const { callee } = node;
37423 if (
37424 callee.type === 'MemberExpression' &&
37425 callee.property.type === 'Identifier' &&
37426 callee.property.name === 'concat'
37427 ) {
37428 return `${expressionToGlob(callee.object)}${node.arguments.map(expressionToGlob).join('')}`;
37429 }
37430 return '*';
37431}
37432
37433function binaryExpressionToGlob(node) {
37434 if (node.operator !== '+') {
37435 throw new VariableDynamicImportError(`${node.operator} operator is not supported.`);
37436 }
37437
37438 return `${expressionToGlob(node.left)}${expressionToGlob(node.right)}`;
37439}
37440
37441function expressionToGlob(node) {
37442 switch (node.type) {
37443 case 'TemplateLiteral':
37444 return templateLiteralToGlob(node);
37445 case 'CallExpression':
37446 return callExpressionToGlob(node);
37447 case 'BinaryExpression':
37448 return binaryExpressionToGlob(node);
37449 case 'Literal': {
37450 return sanitizeString(node.value);
37451 }
37452 default:
37453 return '*';
37454 }
37455}
37456
37457function dynamicImportToGlob(node, sourceString) {
37458 let glob = expressionToGlob(node);
37459 if (!glob.includes('*')) {
37460 return null;
37461 }
37462 glob = glob.replace(/\*\*/g, '*');
37463
37464 if (glob.startsWith('*')) {
37465 throw new VariableDynamicImportError(
37466 `invalid import "${sourceString}". It cannot be statically analyzed. Variable dynamic imports must start with ./ and be limited to a specific directory. ${example}`
37467 );
37468 }
37469
37470 if (glob.startsWith('/')) {
37471 throw new VariableDynamicImportError(
37472 `invalid import "${sourceString}". Variable absolute imports are not supported, imports must start with ./ in the static part of the import. ${example}`
37473 );
37474 }
37475
37476 if (!glob.startsWith('./') && !glob.startsWith('../')) {
37477 throw new VariableDynamicImportError(
37478 `invalid import "${sourceString}". Variable bare imports are not supported, imports must start with ./ in the static part of the import. ${example}`
37479 );
37480 }
37481
37482 if (glob.startsWith('./*.')) {
37483 throw new VariableDynamicImportError(
37484 `${`invalid import "${sourceString}". Variable imports cannot import their own directory, ` +
37485 'place imports in a separate directory or make the import filename more specific. '}${example}`
37486 );
37487 }
37488
37489 if (path__default.extname(glob) === '') {
37490 throw new VariableDynamicImportError(
37491 `invalid import "${sourceString}". A file extension must be included in the static part of the import. ${example}`
37492 );
37493 }
37494
37495 return glob;
37496}
37497
37498function dynamicImportVariables({ include, exclude, warnOnError } = {}) {
37499 const filter = createFilter(include, exclude);
37500
37501 return {
37502 name: 'rollup-plugin-dynamic-import-variables',
37503
37504 transform(code, id) {
37505 if (!filter(id)) {
37506 return null;
37507 }
37508
37509 const parsed = this.parse(code);
37510
37511 let dynamicImportIndex = -1;
37512 let ms;
37513
37514 walk$1(parsed, {
37515 enter: (node) => {
37516 if (node.type !== 'ImportExpression') {
37517 return;
37518 }
37519 dynamicImportIndex += 1;
37520
37521 try {
37522 // see if this is a variable dynamic import, and generate a glob expression
37523 const glob = dynamicImportToGlob(node.source, code.substring(node.start, node.end));
37524
37525 if (!glob) {
37526 // this was not a variable dynamic import
37527 return;
37528 }
37529
37530 // execute the glob
37531 const result = globby.sync(glob, { cwd: path__default.dirname(id) });
37532 const paths = result.map((r) =>
37533 r.startsWith('./') || r.startsWith('../') ? r : `./${r}`
37534 );
37535
37536 // create magic string if it wasn't created already
37537 ms = ms || new MagicString(code);
37538 // unpack variable dynamic import into a function with import statements per file, rollup
37539 // will turn these into chunks automatically
37540 ms.prepend(
37541 `function __variableDynamicImportRuntime${dynamicImportIndex}__(path) {
37542 switch (path) {
37543 ${paths.map((p) => ` case '${p}': return import('${p}');`).join('\n ')}
37544 default: return Promise.reject(new Error("Unknown variable dynamic import: " + path));
37545 }
37546 }\n\n`
37547 );
37548 // call the runtime function instead of doing a dynamic import, the import specifier will
37549 // be evaluated at runtime and the correct import will be returned by the injected function
37550 ms.overwrite(
37551 node.start,
37552 node.start + 6,
37553 `__variableDynamicImportRuntime${dynamicImportIndex}__`
37554 );
37555 } catch (error) {
37556 if (error instanceof VariableDynamicImportError) {
37557 // TODO: line number
37558 if (warnOnError) {
37559 this.warn(error);
37560 } else {
37561 this.error(error);
37562 }
37563 } else {
37564 this.error(error);
37565 }
37566 }
37567 }
37568 });
37569
37570 if (ms && dynamicImportIndex !== -1) {
37571 return {
37572 code: ms.toString(),
37573 map: ms.generateMap({
37574 file: id,
37575 includeContent: true,
37576 hires: true
37577 })
37578 };
37579 }
37580 return null;
37581 }
37582 };
37583}
37584
37585const dataUriRE = /^([^/]+\/[^;,]+)(;base64)?,([\s\S]*)$/;
37586const dataUriPrefix = `/@data-uri/`;
37587/**
37588 * Build only, since importing from a data URI works natively.
37589 */
37590function dataURIPlugin() {
37591 let resolved;
37592 return {
37593 name: 'vite:data-uri',
37594 buildStart() {
37595 resolved = {};
37596 },
37597 resolveId(id) {
37598 if (!dataUriRE.test(id)) {
37599 return null;
37600 }
37601 const uri = new require$$0$b.URL(id);
37602 if (uri.protocol !== 'data:') {
37603 return null;
37604 }
37605 const match = uri.pathname.match(dataUriRE);
37606 if (!match) {
37607 return null;
37608 }
37609 const [, mime, format, data] = match;
37610 if (mime !== 'text/javascript') {
37611 throw new Error(`data URI with non-JavaScript mime type is not supported.`);
37612 }
37613 // decode data
37614 const base64 = format && /base64/i.test(format.substring(1));
37615 const content = base64
37616 ? Buffer.from(data, 'base64').toString('utf-8')
37617 : data;
37618 resolved[id] = content;
37619 return dataUriPrefix + id;
37620 },
37621 load(id) {
37622 if (id.startsWith(dataUriPrefix)) {
37623 id = id.slice(dataUriPrefix.length);
37624 return resolved[id] || null;
37625 }
37626 }
37627 };
37628}
37629
37630/**
37631 * @param {object} exports
37632 * @param {Set<string>} keys
37633 */
37634function loop(exports, keys) {
37635 if (typeof exports === 'string') {
37636 return exports;
37637 }
37638
37639 if (exports) {
37640 let idx, tmp;
37641 if (Array.isArray(exports)) {
37642 for (idx=0; idx < exports.length; idx++) {
37643 if (tmp = loop(exports[idx], keys)) return tmp;
37644 }
37645 } else {
37646 for (idx in exports) {
37647 if (keys.has(idx)) {
37648 return loop(exports[idx], keys);
37649 }
37650 }
37651 }
37652 }
37653}
37654
37655/**
37656 * @param {string} name The package name
37657 * @param {string} entry The target entry, eg "."
37658 * @param {number} [condition] Unmatched condition?
37659 */
37660function bail(name, entry, condition) {
37661 throw new Error(
37662 condition
37663 ? `No known conditions for "${entry}" entry in "${name}" package`
37664 : `Missing "${entry}" export in "${name}" package`
37665 );
37666}
37667
37668/**
37669 * @param {string} name the package name
37670 * @param {string} entry the target path/import
37671 */
37672function toName(name, entry) {
37673 return entry === name ? '.'
37674 : entry[0] === '.' ? entry
37675 : entry.replace(new RegExp('^' + name + '\/'), './');
37676}
37677
37678/**
37679 * @param {object} pkg package.json contents
37680 * @param {string} [entry] entry name or import path
37681 * @param {object} [options]
37682 * @param {boolean} [options.browser]
37683 * @param {boolean} [options.require]
37684 * @param {string[]} [options.conditions]
37685 */
37686function resolve$1(pkg, entry='.', options={}) {
37687 let { name, exports } = pkg;
37688
37689 if (exports) {
37690 let { browser, require, conditions=[] } = options;
37691
37692 let target = toName(name, entry);
37693 if (target[0] !== '.') target = './' + target;
37694
37695 if (typeof exports === 'string') {
37696 return target === '.' ? exports : bail(name, target);
37697 }
37698
37699 let allows = new Set(['default', ...conditions]);
37700 allows.add(require ? 'require' : 'import');
37701 allows.add(browser ? 'browser' : 'node');
37702
37703 let key, tmp, isSingle=false;
37704
37705 for (key in exports) {
37706 isSingle = key[0] !== '.';
37707 break;
37708 }
37709
37710 if (isSingle) {
37711 return target === '.'
37712 ? loop(exports, allows) || bail(name, target, 1)
37713 : bail(name, target);
37714 }
37715
37716 if (tmp = exports[target]) {
37717 return loop(tmp, allows) || bail(name, target, 1);
37718 }
37719
37720 for (key in exports) {
37721 tmp = key[key.length - 1];
37722 if (tmp === '/' && target.startsWith(key)) {
37723 return (tmp = loop(exports[key], allows))
37724 ? (tmp + target.substring(key.length))
37725 : bail(name, target, 1);
37726 }
37727 if (tmp === '*' && target.startsWith(key.slice(0, -1))) {
37728 // do not trigger if no *content* to inject
37729 if (target.substring(key.length - 1).length > 0) {
37730 return (tmp = loop(exports[key], allows))
37731 ? tmp.replace('*', target.substring(key.length - 1))
37732 : bail(name, target, 1);
37733 }
37734 }
37735 }
37736
37737 return bail(name, target);
37738 }
37739}
37740
37741// special id for paths marked with browser: false
37742// https://github.com/defunctzombie/package-browser-field-spec#ignore-a-module
37743const browserExternalId = '__vite-browser-external';
37744const isDebug$4 = process.env.DEBUG;
37745const debug$a = createDebugger('vite:resolve-details', {
37746 onlyWhenFocused: true
37747});
37748function resolvePlugin(baseOptions) {
37749 const { root, isProduction, asSrc, ssrTarget, preferRelative = false } = baseOptions;
37750 const requireOptions = {
37751 ...baseOptions,
37752 isRequire: true
37753 };
37754 let server;
37755 return {
37756 name: 'vite:resolve',
37757 configureServer(_server) {
37758 server = _server;
37759 },
37760 resolveId(id, importer, resolveOpts, ssr) {
37761 if (id.startsWith(browserExternalId)) {
37762 return id;
37763 }
37764 // fast path for commonjs proxy modules
37765 if (/\?commonjs/.test(id) || id === 'commonjsHelpers.js') {
37766 return;
37767 }
37768 const targetWeb = !ssr || ssrTarget === 'webworker';
37769 // this is passed by @rollup/plugin-commonjs
37770 const isRequire = resolveOpts &&
37771 resolveOpts.custom &&
37772 resolveOpts.custom['node-resolve'] &&
37773 resolveOpts.custom['node-resolve'].isRequire;
37774 const options = isRequire ? requireOptions : baseOptions;
37775 let res;
37776 // explicit fs paths that starts with /@fs/*
37777 if (asSrc && id.startsWith(FS_PREFIX)) {
37778 const fsPath = fsPathFromId(id);
37779 res = tryFsResolve(fsPath, options);
37780 isDebug$4 && debug$a(`[@fs] ${source.cyan(id)} -> ${source.dim(res)}`);
37781 // always return here even if res doesn't exist since /@fs/ is explicit
37782 // if the file doesn't exist it should be a 404
37783 return res || fsPath;
37784 }
37785 // URL
37786 // /foo -> /fs-root/foo
37787 if (asSrc && id.startsWith('/')) {
37788 const fsPath = path__default.resolve(root, id.slice(1));
37789 if ((res = tryFsResolve(fsPath, options))) {
37790 isDebug$4 && debug$a(`[url] ${source.cyan(id)} -> ${source.dim(res)}`);
37791 return res;
37792 }
37793 }
37794 // relative
37795 if (id.startsWith('.') || (preferRelative && /^\w/.test(id))) {
37796 const basedir = importer ? path__default.dirname(importer) : process.cwd();
37797 const fsPath = path__default.resolve(basedir, id);
37798 // handle browser field mapping for relative imports
37799 const normalizedFsPath = normalizePath$4(fsPath);
37800 const pathFromBasedir = normalizedFsPath.slice(basedir.length);
37801 if (pathFromBasedir.startsWith('/node_modules/')) {
37802 // normalize direct imports from node_modules to bare imports, so the
37803 // hashing logic is shared and we avoid duplicated modules #2503
37804 const bareImport = pathFromBasedir.slice('/node_modules/'.length);
37805 if ((res = tryNodeResolve(bareImport, importer, options, targetWeb, server, ssr)) &&
37806 res.id.startsWith(normalizedFsPath)) {
37807 return res;
37808 }
37809 }
37810 if (targetWeb &&
37811 (res = tryResolveBrowserMapping(fsPath, importer, options, true))) {
37812 return res;
37813 }
37814 if ((res = tryFsResolve(fsPath, options))) {
37815 isDebug$4 && debug$a(`[relative] ${source.cyan(id)} -> ${source.dim(res)}`);
37816 const pkg = importer != null && idToPkgMap.get(importer);
37817 if (pkg) {
37818 idToPkgMap.set(res, pkg);
37819 return {
37820 id: res,
37821 moduleSideEffects: pkg.hasSideEffects(res)
37822 };
37823 }
37824 return res;
37825 }
37826 }
37827 // absolute fs paths
37828 if (path__default.isAbsolute(id) && (res = tryFsResolve(id, options))) {
37829 isDebug$4 && debug$a(`[fs] ${source.cyan(id)} -> ${source.dim(res)}`);
37830 return res;
37831 }
37832 // external
37833 if (isExternalUrl(id)) {
37834 return {
37835 id,
37836 external: true
37837 };
37838 }
37839 // data uri: pass through (this only happens during build and will be
37840 // handled by dedicated plugin)
37841 if (isDataUrl(id)) {
37842 return null;
37843 }
37844 // bare package imports, perform node resolve
37845 if (bareImportRE.test(id)) {
37846 if (asSrc &&
37847 server &&
37848 !ssr &&
37849 (res = tryOptimizedResolve(id, server))) {
37850 return res;
37851 }
37852 if (targetWeb &&
37853 (res = tryResolveBrowserMapping(id, importer, options, false))) {
37854 return res;
37855 }
37856 if ((res = tryNodeResolve(id, importer, options, targetWeb, server, ssr))) {
37857 return res;
37858 }
37859 // node built-ins.
37860 // externalize if building for SSR, otherwise redirect to empty module
37861 if (isBuiltin(id)) {
37862 if (ssr) {
37863 return {
37864 id,
37865 external: true
37866 };
37867 }
37868 else {
37869 if (!asSrc) {
37870 debug$a(`externalized node built-in "${id}" to empty module. ` +
37871 `(imported by: ${source.white.dim(importer)})`);
37872 }
37873 return isProduction
37874 ? browserExternalId
37875 : `${browserExternalId}:${id}`;
37876 }
37877 }
37878 }
37879 isDebug$4 && debug$a(`[fallthrough] ${source.dim(id)}`);
37880 },
37881 load(id) {
37882 if (id.startsWith(browserExternalId)) {
37883 return isProduction
37884 ? `export default {}`
37885 : `export default new Proxy({}, {
37886 get() {
37887 throw new Error('Module "${id.slice(browserExternalId.length + 1)}" has been externalized for browser compatibility and cannot be accessed in client code.')
37888 }
37889})`;
37890 }
37891 }
37892 };
37893}
37894function tryFsResolve(fsPath, options, tryIndex = true, targetWeb = true) {
37895 let file = fsPath;
37896 let postfix = '';
37897 let postfixIndex = fsPath.indexOf('?');
37898 if (postfixIndex < 0) {
37899 postfixIndex = fsPath.indexOf('#');
37900 }
37901 if (postfixIndex > 0) {
37902 file = fsPath.slice(0, postfixIndex);
37903 postfix = fsPath.slice(postfixIndex);
37904 }
37905 let res;
37906 if ((res = tryResolveFile(file, postfix, options, false, targetWeb, options.tryPrefix))) {
37907 return res;
37908 }
37909 for (const ext of options.extensions || DEFAULT_EXTENSIONS) {
37910 if ((res = tryResolveFile(file + ext, postfix, options, false, targetWeb, options.tryPrefix))) {
37911 return res;
37912 }
37913 }
37914 if ((res = tryResolveFile(file, postfix, options, tryIndex, targetWeb, options.tryPrefix))) {
37915 return res;
37916 }
37917}
37918function tryResolveFile(file, postfix, options, tryIndex, targetWeb, tryPrefix) {
37919 let isReadable = false;
37920 try {
37921 // #2051 if we don't have read permission on a directory, existsSync() still
37922 // works and will result in massively slow subsequent checks (which are
37923 // unnecessary in the first place)
37924 fs__default.accessSync(file, fs__default.constants.R_OK);
37925 isReadable = true;
37926 }
37927 catch (e) { }
37928 if (isReadable) {
37929 if (!fs__default.statSync(file).isDirectory()) {
37930 return normalizePath$4(ensureVolumeInPath(file)) + postfix;
37931 }
37932 else if (tryIndex) {
37933 const pkgPath = file + '/package.json';
37934 if (fs__default.existsSync(pkgPath)) {
37935 // path points to a node package
37936 const pkg = loadPackageData(pkgPath);
37937 return resolvePackageEntry(file, pkg, options, targetWeb);
37938 }
37939 const index = tryFsResolve(file + '/index', options);
37940 if (index)
37941 return index + postfix;
37942 }
37943 }
37944 if (tryPrefix) {
37945 const prefixed = `${path__default.dirname(file)}/${tryPrefix}${path__default.basename(file)}`;
37946 return tryResolveFile(prefixed, postfix, options, tryIndex, targetWeb);
37947 }
37948}
37949const idToPkgMap = new Map();
37950function tryNodeResolve(id, importer, options, targetWeb, server, ssr) {
37951 var _a, _b, _c;
37952 const { root, dedupe, isBuild } = options;
37953 const deepMatch = id.match(deepImportRE);
37954 const pkgId = deepMatch ? deepMatch[1] || deepMatch[2] : id;
37955 let basedir;
37956 if (dedupe && dedupe.includes(pkgId)) {
37957 basedir = root;
37958 }
37959 else if (importer &&
37960 path__default.isAbsolute(importer) &&
37961 fs__default.existsSync(cleanUrl(importer))) {
37962 basedir = path__default.dirname(importer);
37963 }
37964 else {
37965 basedir = root;
37966 }
37967 const pkg = resolvePackageData(pkgId, basedir);
37968 if (!pkg) {
37969 return;
37970 }
37971 let resolved = deepMatch
37972 ? resolveDeepImport(id, pkg, options, targetWeb)
37973 : resolvePackageEntry(id, pkg, options, targetWeb);
37974 if (!resolved) {
37975 return;
37976 }
37977 // link id to pkg for browser field mapping check
37978 idToPkgMap.set(resolved, pkg);
37979 if (isBuild) {
37980 // Resolve package side effects for build so that rollup can better
37981 // perform tree-shaking
37982 return {
37983 id: resolved,
37984 moduleSideEffects: pkg.hasSideEffects(resolved)
37985 };
37986 }
37987 else {
37988 if (!resolved.includes('node_modules') || // linked
37989 !server || // build
37990 server._isRunningOptimizer || // optimizing
37991 !server._optimizeDepsMetadata) {
37992 return { id: resolved };
37993 }
37994 // if we reach here, it's a valid dep import that hasn't been optimized.
37995 const isJsType = OPTIMIZABLE_ENTRY_RE.test(resolved);
37996 const exclude = (_a = server.config.optimizeDeps) === null || _a === void 0 ? void 0 : _a.exclude;
37997 if (!isJsType ||
37998 (importer === null || importer === void 0 ? void 0 : importer.includes('node_modules')) ||
37999 (exclude === null || exclude === void 0 ? void 0 : exclude.includes(pkgId)) ||
38000 (exclude === null || exclude === void 0 ? void 0 : exclude.includes(id)) ||
38001 SPECIAL_QUERY_RE.test(resolved)) {
38002 // excluded from optimization
38003 // Inject a version query to npm deps so that the browser
38004 // can cache it without re-validation, but only do so for known js types.
38005 // otherwise we may introduce duplicated modules for externalized files
38006 // from pre-bundled deps.
38007 const versionHash = (_b = server._optimizeDepsMetadata) === null || _b === void 0 ? void 0 : _b.browserHash;
38008 if (versionHash && isJsType) {
38009 resolved = injectQuery(resolved, `v=${versionHash}`);
38010 }
38011 }
38012 else {
38013 // this is a missing import.
38014 // queue optimize-deps re-run.
38015 (_c = server._registerMissingImport) === null || _c === void 0 ? void 0 : _c.call(server, id, resolved, ssr);
38016 }
38017 return { id: resolved };
38018 }
38019}
38020function tryOptimizedResolve(id, server) {
38021 const cacheDir = server.config.cacheDir;
38022 const depData = server._optimizeDepsMetadata;
38023 if (cacheDir && depData) {
38024 const isOptimized = depData.optimized[id];
38025 if (isOptimized) {
38026 return (isOptimized.file +
38027 `?v=${depData.browserHash}${isOptimized.needsInterop ? `&es-interop` : ``}`);
38028 }
38029 }
38030}
38031const packageCache = new Map();
38032function resolvePackageData(id, basedir) {
38033 const cacheKey = id + basedir;
38034 if (packageCache.has(cacheKey)) {
38035 return packageCache.get(cacheKey);
38036 }
38037 try {
38038 const pkgPath = resolveFrom$3(`${id}/package.json`, basedir);
38039 return loadPackageData(pkgPath, cacheKey);
38040 }
38041 catch (e) {
38042 isDebug$4 && debug$a(`${source.red(`[failed loading package.json]`)} ${id}`);
38043 }
38044}
38045function loadPackageData(pkgPath, cacheKey = pkgPath) {
38046 const data = JSON.parse(fs__default.readFileSync(pkgPath, 'utf-8'));
38047 const pkgDir = path__default.dirname(pkgPath);
38048 const { sideEffects } = data;
38049 let hasSideEffects;
38050 if (typeof sideEffects === 'boolean') {
38051 hasSideEffects = () => sideEffects;
38052 }
38053 else if (Array.isArray(sideEffects)) {
38054 hasSideEffects = createFilter$1(sideEffects, null, { resolve: pkgDir });
38055 }
38056 else {
38057 hasSideEffects = () => true;
38058 }
38059 const pkg = {
38060 dir: pkgDir,
38061 data,
38062 hasSideEffects,
38063 webResolvedImports: {},
38064 nodeResolvedImports: {},
38065 setResolvedCache(key, entry, targetWeb) {
38066 if (targetWeb) {
38067 pkg.webResolvedImports[key] = entry;
38068 }
38069 else {
38070 pkg.nodeResolvedImports[key] = entry;
38071 }
38072 },
38073 getResolvedCache(key, targetWeb) {
38074 if (targetWeb) {
38075 return pkg.webResolvedImports[key];
38076 }
38077 else {
38078 return pkg.nodeResolvedImports[key];
38079 }
38080 }
38081 };
38082 packageCache.set(cacheKey, pkg);
38083 return pkg;
38084}
38085function resolvePackageEntry(id, { dir, data, setResolvedCache, getResolvedCache }, options, targetWeb) {
38086 const cached = getResolvedCache('.', targetWeb);
38087 if (cached) {
38088 return cached;
38089 }
38090 let entryPoint;
38091 // resolve exports field with highest priority
38092 // using https://github.com/lukeed/resolve.exports
38093 if (data.exports) {
38094 entryPoint = resolveExports(data, '.', options, targetWeb);
38095 }
38096 // if exports resolved to .mjs, still resolve other fields.
38097 // This is because .mjs files can technically import .cjs files which would
38098 // make them invalid for pure ESM environments - so if other module/browser
38099 // fields are present, prioritize those instead.
38100 if (targetWeb && (!entryPoint || entryPoint.endsWith('.mjs'))) {
38101 // check browser field
38102 // https://github.com/defunctzombie/package-browser-field-spec
38103 const browserEntry = typeof data.browser === 'string'
38104 ? data.browser
38105 : isObject$3(data.browser) && data.browser['.'];
38106 if (browserEntry) {
38107 // check if the package also has a "module" field.
38108 if (typeof data.module === 'string' && data.module !== browserEntry) {
38109 // if both are present, we may have a problem: some package points both
38110 // to ESM, with "module" targeting Node.js, while some packages points
38111 // "module" to browser ESM and "browser" to UMD.
38112 // the heuristics here is to actually read the browser entry when
38113 // possible and check for hints of UMD. If it is UMD, prefer "module"
38114 // instead; Otherwise, assume it's ESM and use it.
38115 const resolvedBrowserEntry = tryFsResolve(path__default.join(dir, browserEntry), options);
38116 if (resolvedBrowserEntry) {
38117 const content = fs__default.readFileSync(resolvedBrowserEntry, 'utf-8');
38118 if ((/typeof exports\s*==/.test(content) &&
38119 /typeof module\s*==/.test(content)) ||
38120 /module\.exports\s*=/.test(content)) {
38121 // likely UMD or CJS(!!! e.g. firebase 7.x), prefer module
38122 entryPoint = data.module;
38123 }
38124 }
38125 }
38126 else {
38127 entryPoint = browserEntry;
38128 }
38129 }
38130 }
38131 if (!entryPoint || entryPoint.endsWith('.mjs')) {
38132 for (const field of options.mainFields || DEFAULT_MAIN_FIELDS) {
38133 if (typeof data[field] === 'string') {
38134 entryPoint = data[field];
38135 break;
38136 }
38137 }
38138 }
38139 entryPoint = entryPoint || data.main || 'index.js';
38140 // resolve object browser field in package.json
38141 const { browser: browserField } = data;
38142 if (targetWeb && isObject$3(browserField)) {
38143 entryPoint = mapWithBrowserField(entryPoint, browserField) || entryPoint;
38144 }
38145 entryPoint = path__default.join(dir, entryPoint);
38146 const resolvedEntryPoint = tryFsResolve(entryPoint, options);
38147 if (resolvedEntryPoint) {
38148 isDebug$4 &&
38149 debug$a(`[package entry] ${source.cyan(id)} -> ${source.dim(resolvedEntryPoint)}`);
38150 setResolvedCache('.', resolvedEntryPoint, targetWeb);
38151 return resolvedEntryPoint;
38152 }
38153 else {
38154 throw new Error(`Failed to resolve entry for package "${id}". ` +
38155 `The package may have incorrect main/module/exports specified in its package.json.`);
38156 }
38157}
38158function resolveExports(pkg, key, options, targetWeb) {
38159 const conditions = [options.isProduction ? 'production' : 'development'];
38160 if (!options.isRequire) {
38161 conditions.push('module');
38162 }
38163 if (options.conditions) {
38164 conditions.push(...options.conditions);
38165 }
38166 return resolve$1(pkg, key, {
38167 browser: targetWeb,
38168 require: options.isRequire,
38169 conditions
38170 });
38171}
38172function resolveDeepImport(id, { webResolvedImports, setResolvedCache, getResolvedCache, dir, data }, options, targetWeb) {
38173 id = '.' + id.slice(data.name.length);
38174 const cache = getResolvedCache(id, targetWeb);
38175 if (cache) {
38176 return cache;
38177 }
38178 let relativeId = id;
38179 const { exports: exportsField, browser: browserField } = data;
38180 // map relative based on exports data
38181 if (exportsField) {
38182 if (isObject$3(exportsField) && !Array.isArray(exportsField)) {
38183 relativeId = resolveExports(data, relativeId, options, targetWeb);
38184 }
38185 else {
38186 // not exposed
38187 relativeId = undefined;
38188 }
38189 if (!relativeId) {
38190 throw new Error(`Package subpath '${relativeId}' is not defined by "exports" in ` +
38191 `${path__default.join(dir, 'package.json')}.`);
38192 }
38193 }
38194 else if (targetWeb && isObject$3(browserField)) {
38195 const mapped = mapWithBrowserField(relativeId, browserField);
38196 if (mapped) {
38197 relativeId = mapped;
38198 }
38199 else if (mapped === false) {
38200 return (webResolvedImports[id] = browserExternalId);
38201 }
38202 }
38203 if (relativeId) {
38204 const resolved = tryFsResolve(path__default.join(dir, relativeId), options, !exportsField, // try index only if no exports field
38205 targetWeb);
38206 if (resolved) {
38207 isDebug$4 &&
38208 debug$a(`[node/deep-import] ${source.cyan(id)} -> ${source.dim(resolved)}`);
38209 setResolvedCache(id, resolved, targetWeb);
38210 return resolved;
38211 }
38212 }
38213}
38214function tryResolveBrowserMapping(id, importer, options, isFilePath) {
38215 let res;
38216 const pkg = importer && idToPkgMap.get(importer);
38217 if (pkg && isObject$3(pkg.data.browser)) {
38218 const mapId = isFilePath ? './' + slash$3(path__default.relative(pkg.dir, id)) : id;
38219 const browserMappedPath = mapWithBrowserField(mapId, pkg.data.browser);
38220 if (browserMappedPath) {
38221 const fsPath = path__default.join(pkg.dir, browserMappedPath);
38222 if ((res = tryFsResolve(fsPath, options))) {
38223 isDebug$4 &&
38224 debug$a(`[browser mapped] ${source.cyan(id)} -> ${source.dim(res)}`);
38225 idToPkgMap.set(res, pkg);
38226 return {
38227 id: res,
38228 moduleSideEffects: pkg.hasSideEffects(res)
38229 };
38230 }
38231 }
38232 else if (browserMappedPath === false) {
38233 return browserExternalId;
38234 }
38235 }
38236}
38237/**
38238 * given a relative path in pkg dir,
38239 * return a relative path in pkg dir,
38240 * mapped with the "map" object
38241 *
38242 * - Returning `undefined` means there is no browser mapping for this id
38243 * - Returning `false` means this id is explicitly externalized for browser
38244 */
38245function mapWithBrowserField(relativePathInPkgDir, map) {
38246 const normalizedPath = path__default.posix.normalize(relativePathInPkgDir);
38247 for (const key in map) {
38248 const normalizedKey = path__default.posix.normalize(key);
38249 if (normalizedPath === normalizedKey ||
38250 equalWithoutSuffix(normalizedPath, normalizedKey, '.js') ||
38251 equalWithoutSuffix(normalizedPath, normalizedKey, '/index.js')) {
38252 return map[key];
38253 }
38254 }
38255}
38256function equalWithoutSuffix(path, key, suffix) {
38257 return key.endsWith(suffix) && key.slice(0, -suffix.length) === path;
38258}
38259
38260/**
38261 * Heuristics for determining whether a dependency should be externalized for
38262 * server-side rendering.
38263 *
38264 * TODO right now externals are imported using require(), we probably need to
38265 * rework this when more libraries ship native ESM distributions for Node.
38266 */
38267function resolveSSRExternal(config, knownImports, ssrExternals = new Set(), seen = new Set()) {
38268 var _a, _b, _c;
38269 const { root } = config;
38270 const pkgContent = lookupFile(root, ['package.json']);
38271 if (!pkgContent) {
38272 return [];
38273 }
38274 const pkg = JSON.parse(pkgContent);
38275 const devDeps = Object.keys(pkg.devDependencies || {});
38276 const importedDeps = knownImports.map(getNpmPackageName).filter(isDefined);
38277 const deps = unique([...importedDeps, ...Object.keys(pkg.dependencies || {})]);
38278 for (const id of devDeps) {
38279 ssrExternals.add(id);
38280 seen.add(id);
38281 }
38282 const resolveOptions = {
38283 root,
38284 isProduction: false,
38285 isBuild: true
38286 };
38287 const depsToTrace = new Set();
38288 for (const id of deps) {
38289 if (seen.has(id)) {
38290 continue;
38291 }
38292 seen.add(id);
38293 let entry;
38294 let requireEntry;
38295 try {
38296 entry = (_a = tryNodeResolve(id, undefined, resolveOptions, true, undefined, true)) === null || _a === void 0 ? void 0 : _a.id;
38297 requireEntry = require.resolve(id, { paths: [root] });
38298 }
38299 catch (e) {
38300 // resolve failed, assume include
38301 continue;
38302 }
38303 if (!entry) {
38304 // no esm entry but has require entry (is this even possible?)
38305 ssrExternals.add(id);
38306 continue;
38307 }
38308 if (!entry.includes('node_modules')) {
38309 // entry is not a node dep, possibly linked - don't externalize
38310 // instead, trace its dependencies.
38311 depsToTrace.add(id);
38312 continue;
38313 }
38314 if (entry !== requireEntry) {
38315 // has separate esm/require entry, assume require entry is cjs
38316 ssrExternals.add(id);
38317 }
38318 else {
38319 // node resolve and esm resolve resolves to the same file.
38320 if (!/\.m?js$/.test(entry)) {
38321 // entry is not js, cannot externalize
38322 continue;
38323 }
38324 // check if the entry is cjs
38325 const content = fs__default.readFileSync(entry, 'utf-8');
38326 if (/\bmodule\.exports\b|\bexports[.\[]|\brequire\s*\(/.test(content)) {
38327 ssrExternals.add(id);
38328 }
38329 }
38330 }
38331 for (const id of depsToTrace) {
38332 const depRoot = path__default.dirname(resolveFrom$3(`${id}/package.json`, root));
38333 resolveSSRExternal({
38334 ...config,
38335 root: depRoot
38336 }, knownImports, ssrExternals, seen);
38337 }
38338 if ((_b = config.ssr) === null || _b === void 0 ? void 0 : _b.external) {
38339 config.ssr.external.forEach((id) => ssrExternals.add(id));
38340 }
38341 let externals = [...ssrExternals];
38342 if ((_c = config.ssr) === null || _c === void 0 ? void 0 : _c.noExternal) {
38343 const filter = createFilter$1(undefined, config.ssr.noExternal, {
38344 resolve: false
38345 });
38346 externals = externals.filter((id) => filter(id));
38347 }
38348 return externals.filter((id) => id !== 'vite');
38349}
38350function shouldExternalizeForSSR(id, externals) {
38351 const should = externals.some((e) => {
38352 if (id === e) {
38353 return true;
38354 }
38355 // deep imports, check ext before externalizing - only externalize
38356 // extension-less imports and explicit .js imports
38357 if (id.startsWith(e + '/') && (!path__default.extname(id) || id.endsWith('.js'))) {
38358 return true;
38359 }
38360 });
38361 return should;
38362}
38363function getNpmPackageName(importPath) {
38364 const parts = importPath.split('/');
38365 if (parts[0].startsWith('@')) {
38366 if (!parts[1])
38367 return null;
38368 return `${parts[0]}/${parts[1]}`;
38369 }
38370 else {
38371 return parts[0];
38372 }
38373}
38374
38375function ssrManifestPlugin(config) {
38376 // module id => preload assets mapping
38377 const ssrManifest = {};
38378 const base = config.base;
38379 return {
38380 name: 'vite:manifest',
38381 generateBundle(_options, bundle) {
38382 for (const file in bundle) {
38383 const chunk = bundle[file];
38384 if (chunk.type === 'chunk') {
38385 // links for certain entry chunks are already generated in static HTML
38386 // in those cases we only need to record info for non-entry chunks
38387 const cssFiles = chunk.isEntry
38388 ? null
38389 : chunkToEmittedCssFileMap.get(chunk);
38390 const assetFiles = chunkToEmittedAssetsMap.get(chunk);
38391 for (const id in chunk.modules) {
38392 const normalizedId = normalizePath$3(path$A.relative(config.root, id));
38393 const mappedChunks = ssrManifest[normalizedId] || (ssrManifest[normalizedId] = []);
38394 if (!chunk.isEntry) {
38395 mappedChunks.push(base + chunk.fileName);
38396 }
38397 if (cssFiles) {
38398 cssFiles.forEach((file) => {
38399 mappedChunks.push(base + file);
38400 });
38401 }
38402 if (assetFiles) {
38403 assetFiles.forEach((file) => {
38404 mappedChunks.push(base + file);
38405 });
38406 }
38407 }
38408 }
38409 }
38410 this.emitFile({
38411 fileName: 'ssr-manifest.json',
38412 type: 'asset',
38413 source: JSON.stringify(ssrManifest, null, 2)
38414 });
38415 }
38416 };
38417}
38418
38419// Reserved word lists for various dialects of the language
38420
38421var reservedWords = {
38422 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
38423 5: "class enum extends super const export import",
38424 6: "enum",
38425 strict: "implements interface let package private protected public static yield",
38426 strictBind: "eval arguments"
38427};
38428
38429// And the keywords
38430
38431var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";
38432
38433var keywords = {
38434 5: ecma5AndLessKeywords,
38435 "5module": ecma5AndLessKeywords + " export import",
38436 6: ecma5AndLessKeywords + " const class extends export import super"
38437};
38438
38439var keywordRelationalOperator = /^in(stanceof)?$/;
38440
38441// ## Character categories
38442
38443// Big ugly regular expressions that match characters in the
38444// whitespace, identifier, and identifier-start categories. These
38445// are only applied when a character is found to actually have a
38446// code point above 128.
38447// Generated by `bin/generate-identifier-regex.js`.
38448var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08c7\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
38449var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
38450
38451var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
38452var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
38453
38454nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
38455
38456// These are a run-length and offset encoded representation of the
38457// >0xffff code points that are a valid part of identifiers. The
38458// offset starts at 0x10000, and each pair of numbers represents an
38459// offset to the next range, and then a size of the range. They were
38460// generated by bin/generate-identifier-regex.js
38461
38462// eslint-disable-next-line comma-spacing
38463var astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,349,41,7,1,79,28,11,0,9,21,107,20,28,22,13,52,76,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,230,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,35,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,190,0,80,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,689,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,43,8,8952,286,50,2,18,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,2357,44,11,6,17,0,370,43,1301,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42717,35,4148,12,221,3,5761,15,7472,3104,541,1507,4938];
38464
38465// eslint-disable-next-line comma-spacing
38466var astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,370,1,154,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,9,135,4,60,6,26,9,1014,0,2,54,8,3,82,0,12,1,19628,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,262,6,10,9,419,13,1495,6,110,6,6,9,4759,9,787719,239];
38467
38468// This has a complexity linear to the value of the code. The
38469// assumption is that looking up astral identifier characters is
38470// rare.
38471function isInAstralSet(code, set) {
38472 var pos = 0x10000;
38473 for (var i = 0; i < set.length; i += 2) {
38474 pos += set[i];
38475 if (pos > code) { return false }
38476 pos += set[i + 1];
38477 if (pos >= code) { return true }
38478 }
38479}
38480
38481// Test whether a given character code starts an identifier.
38482
38483function isIdentifierStart(code, astral) {
38484 if (code < 65) { return code === 36 }
38485 if (code < 91) { return true }
38486 if (code < 97) { return code === 95 }
38487 if (code < 123) { return true }
38488 if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
38489 if (astral === false) { return false }
38490 return isInAstralSet(code, astralIdentifierStartCodes)
38491}
38492
38493// Test whether a given character is part of an identifier.
38494
38495function isIdentifierChar(code, astral) {
38496 if (code < 48) { return code === 36 }
38497 if (code < 58) { return true }
38498 if (code < 65) { return false }
38499 if (code < 91) { return true }
38500 if (code < 97) { return code === 95 }
38501 if (code < 123) { return true }
38502 if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
38503 if (astral === false) { return false }
38504 return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
38505}
38506
38507// ## Token types
38508
38509// The assignment of fine-grained, information-carrying type objects
38510// allows the tokenizer to store the information it has about a
38511// token in a way that is very cheap for the parser to look up.
38512
38513// All token type variables start with an underscore, to make them
38514// easy to recognize.
38515
38516// The `beforeExpr` property is used to disambiguate between regular
38517// expressions and divisions. It is set on all token types that can
38518// be followed by an expression (thus, a slash after them would be a
38519// regular expression).
38520//
38521// The `startsExpr` property is used to check if the token ends a
38522// `yield` expression. It is set on all token types that either can
38523// directly start an expression (like a quotation mark) or can
38524// continue an expression (like the body of a string).
38525//
38526// `isLoop` marks a keyword as starting a loop, which is important
38527// to know when parsing a label, in order to allow or disallow
38528// continue jumps to that label.
38529
38530var TokenType = function TokenType(label, conf) {
38531 if ( conf === void 0 ) conf = {};
38532
38533 this.label = label;
38534 this.keyword = conf.keyword;
38535 this.beforeExpr = !!conf.beforeExpr;
38536 this.startsExpr = !!conf.startsExpr;
38537 this.isLoop = !!conf.isLoop;
38538 this.isAssign = !!conf.isAssign;
38539 this.prefix = !!conf.prefix;
38540 this.postfix = !!conf.postfix;
38541 this.binop = conf.binop || null;
38542 this.updateContext = null;
38543};
38544
38545function binop(name, prec) {
38546 return new TokenType(name, {beforeExpr: true, binop: prec})
38547}
38548var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};
38549
38550// Map keyword names to token types.
38551
38552var keywords$1 = {};
38553
38554// Succinct definitions of keyword token types
38555function kw(name, options) {
38556 if ( options === void 0 ) options = {};
38557
38558 options.keyword = name;
38559 return keywords$1[name] = new TokenType(name, options)
38560}
38561
38562var types = {
38563 num: new TokenType("num", startsExpr),
38564 regexp: new TokenType("regexp", startsExpr),
38565 string: new TokenType("string", startsExpr),
38566 name: new TokenType("name", startsExpr),
38567 privateId: new TokenType("privateId", startsExpr),
38568 eof: new TokenType("eof"),
38569
38570 // Punctuation token types.
38571 bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
38572 bracketR: new TokenType("]"),
38573 braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
38574 braceR: new TokenType("}"),
38575 parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
38576 parenR: new TokenType(")"),
38577 comma: new TokenType(",", beforeExpr),
38578 semi: new TokenType(";", beforeExpr),
38579 colon: new TokenType(":", beforeExpr),
38580 dot: new TokenType("."),
38581 question: new TokenType("?", beforeExpr),
38582 questionDot: new TokenType("?."),
38583 arrow: new TokenType("=>", beforeExpr),
38584 template: new TokenType("template"),
38585 invalidTemplate: new TokenType("invalidTemplate"),
38586 ellipsis: new TokenType("...", beforeExpr),
38587 backQuote: new TokenType("`", startsExpr),
38588 dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
38589
38590 // Operators. These carry several kinds of properties to help the
38591 // parser use them properly (the presence of these properties is
38592 // what categorizes them as operators).
38593 //
38594 // `binop`, when present, specifies that this operator is a binary
38595 // operator, and will refer to its precedence.
38596 //
38597 // `prefix` and `postfix` mark the operator as a prefix or postfix
38598 // unary operator.
38599 //
38600 // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
38601 // binary operators with a very low precedence, that should result
38602 // in AssignmentExpression nodes.
38603
38604 eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
38605 assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
38606 incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
38607 prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
38608 logicalOR: binop("||", 1),
38609 logicalAND: binop("&&", 2),
38610 bitwiseOR: binop("|", 3),
38611 bitwiseXOR: binop("^", 4),
38612 bitwiseAND: binop("&", 5),
38613 equality: binop("==/!=/===/!==", 6),
38614 relational: binop("</>/<=/>=", 7),
38615 bitShift: binop("<</>>/>>>", 8),
38616 plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
38617 modulo: binop("%", 10),
38618 star: binop("*", 10),
38619 slash: binop("/", 10),
38620 starstar: new TokenType("**", {beforeExpr: true}),
38621 coalesce: binop("??", 1),
38622
38623 // Keyword token types.
38624 _break: kw("break"),
38625 _case: kw("case", beforeExpr),
38626 _catch: kw("catch"),
38627 _continue: kw("continue"),
38628 _debugger: kw("debugger"),
38629 _default: kw("default", beforeExpr),
38630 _do: kw("do", {isLoop: true, beforeExpr: true}),
38631 _else: kw("else", beforeExpr),
38632 _finally: kw("finally"),
38633 _for: kw("for", {isLoop: true}),
38634 _function: kw("function", startsExpr),
38635 _if: kw("if"),
38636 _return: kw("return", beforeExpr),
38637 _switch: kw("switch"),
38638 _throw: kw("throw", beforeExpr),
38639 _try: kw("try"),
38640 _var: kw("var"),
38641 _const: kw("const"),
38642 _while: kw("while", {isLoop: true}),
38643 _with: kw("with"),
38644 _new: kw("new", {beforeExpr: true, startsExpr: true}),
38645 _this: kw("this", startsExpr),
38646 _super: kw("super", startsExpr),
38647 _class: kw("class", startsExpr),
38648 _extends: kw("extends", beforeExpr),
38649 _export: kw("export"),
38650 _import: kw("import", startsExpr),
38651 _null: kw("null", startsExpr),
38652 _true: kw("true", startsExpr),
38653 _false: kw("false", startsExpr),
38654 _in: kw("in", {beforeExpr: true, binop: 7}),
38655 _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
38656 _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
38657 _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
38658 _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
38659};
38660
38661// Matches a whole line break (where CRLF is considered a single
38662// line break). Used to count lines.
38663
38664var lineBreak = /\r\n?|\n|\u2028|\u2029/;
38665var lineBreakG = new RegExp(lineBreak.source, "g");
38666
38667function isNewLine(code, ecma2019String) {
38668 return code === 10 || code === 13 || (!ecma2019String && (code === 0x2028 || code === 0x2029))
38669}
38670
38671var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
38672
38673var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
38674
38675var ref = Object.prototype;
38676var hasOwnProperty$1 = ref.hasOwnProperty;
38677var toString$1 = ref.toString;
38678
38679// Checks if an object has a property.
38680
38681function has(obj, propName) {
38682 return hasOwnProperty$1.call(obj, propName)
38683}
38684
38685var isArray = Array.isArray || (function (obj) { return (
38686 toString$1.call(obj) === "[object Array]"
38687); });
38688
38689function wordsRegexp(words) {
38690 return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
38691}
38692
38693// These are used when `options.locations` is on, for the
38694// `startLoc` and `endLoc` properties.
38695
38696var Position = function Position(line, col) {
38697 this.line = line;
38698 this.column = col;
38699};
38700
38701Position.prototype.offset = function offset (n) {
38702 return new Position(this.line, this.column + n)
38703};
38704
38705var SourceLocation = function SourceLocation(p, start, end) {
38706 this.start = start;
38707 this.end = end;
38708 if (p.sourceFile !== null) { this.source = p.sourceFile; }
38709};
38710
38711// The `getLineInfo` function is mostly useful when the
38712// `locations` option is off (for performance reasons) and you
38713// want to find the line/column position for a given character
38714// offset. `input` should be the code string that the offset refers
38715// into.
38716
38717function getLineInfo(input, offset) {
38718 for (var line = 1, cur = 0;;) {
38719 lineBreakG.lastIndex = cur;
38720 var match = lineBreakG.exec(input);
38721 if (match && match.index < offset) {
38722 ++line;
38723 cur = match.index + match[0].length;
38724 } else {
38725 return new Position(line, offset - cur)
38726 }
38727 }
38728}
38729
38730// A second argument must be given to configure the parser process.
38731// These options are recognized (only `ecmaVersion` is required):
38732
38733var defaultOptions = {
38734 // `ecmaVersion` indicates the ECMAScript version to parse. Must be
38735 // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
38736 // (2019), 11 (2020), 12 (2021), 13 (2022), or `"latest"` (the
38737 // latest version the library supports). This influences support
38738 // for strict mode, the set of reserved words, and support for
38739 // new syntax features.
38740 ecmaVersion: null,
38741 // `sourceType` indicates the mode the code should be parsed in.
38742 // Can be either `"script"` or `"module"`. This influences global
38743 // strict mode and parsing of `import` and `export` declarations.
38744 sourceType: "script",
38745 // `onInsertedSemicolon` can be a callback that will be called
38746 // when a semicolon is automatically inserted. It will be passed
38747 // the position of the comma as an offset, and if `locations` is
38748 // enabled, it is given the location as a `{line, column}` object
38749 // as second argument.
38750 onInsertedSemicolon: null,
38751 // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
38752 // trailing commas.
38753 onTrailingComma: null,
38754 // By default, reserved words are only enforced if ecmaVersion >= 5.
38755 // Set `allowReserved` to a boolean value to explicitly turn this on
38756 // an off. When this option has the value "never", reserved words
38757 // and keywords can also not be used as property names.
38758 allowReserved: null,
38759 // When enabled, a return at the top level is not considered an
38760 // error.
38761 allowReturnOutsideFunction: false,
38762 // When enabled, import/export statements are not constrained to
38763 // appearing at the top of the program, and an import.meta expression
38764 // in a script isn't considered an error.
38765 allowImportExportEverywhere: false,
38766 // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022.
38767 // When enabled, await identifiers are allowed to appear at the top-level scope,
38768 // but they are still not allowed in non-async functions.
38769 allowAwaitOutsideFunction: null,
38770 // When enabled, super identifiers are not constrained to
38771 // appearing in methods and do not raise an error when they appear elsewhere.
38772 allowSuperOutsideMethod: null,
38773 // When enabled, hashbang directive in the beginning of file
38774 // is allowed and treated as a line comment.
38775 allowHashBang: false,
38776 // When `locations` is on, `loc` properties holding objects with
38777 // `start` and `end` properties in `{line, column}` form (with
38778 // line being 1-based and column 0-based) will be attached to the
38779 // nodes.
38780 locations: false,
38781 // A function can be passed as `onToken` option, which will
38782 // cause Acorn to call that function with object in the same
38783 // format as tokens returned from `tokenizer().getToken()`. Note
38784 // that you are not allowed to call the parser from the
38785 // callback—that will corrupt its internal state.
38786 onToken: null,
38787 // A function can be passed as `onComment` option, which will
38788 // cause Acorn to call that function with `(block, text, start,
38789 // end)` parameters whenever a comment is skipped. `block` is a
38790 // boolean indicating whether this is a block (`/* */`) comment,
38791 // `text` is the content of the comment, and `start` and `end` are
38792 // character offsets that denote the start and end of the comment.
38793 // When the `locations` option is on, two more parameters are
38794 // passed, the full `{line, column}` locations of the start and
38795 // end of the comments. Note that you are not allowed to call the
38796 // parser from the callback—that will corrupt its internal state.
38797 onComment: null,
38798 // Nodes have their start and end characters offsets recorded in
38799 // `start` and `end` properties (directly on the node, rather than
38800 // the `loc` object, which holds line/column data. To also add a
38801 // [semi-standardized][range] `range` property holding a `[start,
38802 // end]` array with the same numbers, set the `ranges` option to
38803 // `true`.
38804 //
38805 // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
38806 ranges: false,
38807 // It is possible to parse multiple files into a single AST by
38808 // passing the tree produced by parsing the first file as
38809 // `program` option in subsequent parses. This will add the
38810 // toplevel forms of the parsed file to the `Program` (top) node
38811 // of an existing parse tree.
38812 program: null,
38813 // When `locations` is on, you can pass this to record the source
38814 // file in every node's `loc` object.
38815 sourceFile: null,
38816 // This value, if given, is stored in every node, whether
38817 // `locations` is on or off.
38818 directSourceFile: null,
38819 // When enabled, parenthesized expressions are represented by
38820 // (non-standard) ParenthesizedExpression nodes
38821 preserveParens: false
38822};
38823
38824// Interpret and default an options object
38825
38826var warnedAboutEcmaVersion = false;
38827
38828function getOptions(opts) {
38829 var options = {};
38830
38831 for (var opt in defaultOptions)
38832 { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; }
38833
38834 if (options.ecmaVersion === "latest") {
38835 options.ecmaVersion = 1e8;
38836 } else if (options.ecmaVersion == null) {
38837 if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
38838 warnedAboutEcmaVersion = true;
38839 console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
38840 }
38841 options.ecmaVersion = 11;
38842 } else if (options.ecmaVersion >= 2015) {
38843 options.ecmaVersion -= 2009;
38844 }
38845
38846 if (options.allowReserved == null)
38847 { options.allowReserved = options.ecmaVersion < 5; }
38848
38849 if (isArray(options.onToken)) {
38850 var tokens = options.onToken;
38851 options.onToken = function (token) { return tokens.push(token); };
38852 }
38853 if (isArray(options.onComment))
38854 { options.onComment = pushComment(options, options.onComment); }
38855
38856 return options
38857}
38858
38859function pushComment(options, array) {
38860 return function(block, text, start, end, startLoc, endLoc) {
38861 var comment = {
38862 type: block ? "Block" : "Line",
38863 value: text,
38864 start: start,
38865 end: end
38866 };
38867 if (options.locations)
38868 { comment.loc = new SourceLocation(this, startLoc, endLoc); }
38869 if (options.ranges)
38870 { comment.range = [start, end]; }
38871 array.push(comment);
38872 }
38873}
38874
38875// Each scope gets a bitset that may contain these flags
38876var
38877 SCOPE_TOP = 1,
38878 SCOPE_FUNCTION = 2,
38879 SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION,
38880 SCOPE_ASYNC = 4,
38881 SCOPE_GENERATOR = 8,
38882 SCOPE_ARROW = 16,
38883 SCOPE_SIMPLE_CATCH = 32,
38884 SCOPE_SUPER = 64,
38885 SCOPE_DIRECT_SUPER = 128;
38886
38887function functionFlags(async, generator) {
38888 return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)
38889}
38890
38891// Used in checkLVal* and declareName to determine the type of a binding
38892var
38893 BIND_NONE = 0, // Not a binding
38894 BIND_VAR = 1, // Var-style binding
38895 BIND_LEXICAL = 2, // Let- or const-style binding
38896 BIND_FUNCTION = 3, // Function declaration
38897 BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding
38898 BIND_OUTSIDE = 5; // Special case for function names as bound inside the function
38899
38900var Parser = function Parser(options, input, startPos) {
38901 this.options = options = getOptions(options);
38902 this.sourceFile = options.sourceFile;
38903 this.keywords = wordsRegexp(keywords[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
38904 var reserved = "";
38905 if (options.allowReserved !== true) {
38906 reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
38907 if (options.sourceType === "module") { reserved += " await"; }
38908 }
38909 this.reservedWords = wordsRegexp(reserved);
38910 var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
38911 this.reservedWordsStrict = wordsRegexp(reservedStrict);
38912 this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
38913 this.input = String(input);
38914
38915 // Used to signal to callers of `readWord1` whether the word
38916 // contained any escape sequences. This is needed because words with
38917 // escape sequences must not be interpreted as keywords.
38918 this.containsEsc = false;
38919
38920 // Set up token state
38921
38922 // The current position of the tokenizer in the input.
38923 if (startPos) {
38924 this.pos = startPos;
38925 this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
38926 this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
38927 } else {
38928 this.pos = this.lineStart = 0;
38929 this.curLine = 1;
38930 }
38931
38932 // Properties of the current token:
38933 // Its type
38934 this.type = types.eof;
38935 // For tokens that include more information than their type, the value
38936 this.value = null;
38937 // Its start and end offset
38938 this.start = this.end = this.pos;
38939 // And, if locations are used, the {line, column} object
38940 // corresponding to those offsets
38941 this.startLoc = this.endLoc = this.curPosition();
38942
38943 // Position information for the previous token
38944 this.lastTokEndLoc = this.lastTokStartLoc = null;
38945 this.lastTokStart = this.lastTokEnd = this.pos;
38946
38947 // The context stack is used to superficially track syntactic
38948 // context to predict whether a regular expression is allowed in a
38949 // given position.
38950 this.context = this.initialContext();
38951 this.exprAllowed = true;
38952
38953 // Figure out if it's a module code.
38954 this.inModule = options.sourceType === "module";
38955 this.strict = this.inModule || this.strictDirective(this.pos);
38956
38957 // Used to signify the start of a potential arrow function
38958 this.potentialArrowAt = -1;
38959 this.potentialArrowInForAwait = false;
38960
38961 // Positions to delayed-check that yield/await does not exist in default parameters.
38962 this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
38963 // Labels in scope.
38964 this.labels = [];
38965 // Thus-far undefined exports.
38966 this.undefinedExports = Object.create(null);
38967
38968 // If enabled, skip leading hashbang line.
38969 if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
38970 { this.skipLineComment(2); }
38971
38972 // Scope tracking for duplicate variable names (see scope.js)
38973 this.scopeStack = [];
38974 this.enterScope(SCOPE_TOP);
38975
38976 // For RegExp validation
38977 this.regexpState = null;
38978
38979 // The stack of private names.
38980 // Each element has two properties: 'declared' and 'used'.
38981 // When it exited from the outermost class definition, all used private names must be declared.
38982 this.privateNameStack = [];
38983};
38984
38985var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },canAwait: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },inNonArrowFunction: { configurable: true } };
38986
38987Parser.prototype.parse = function parse () {
38988 var node = this.options.program || this.startNode();
38989 this.nextToken();
38990 return this.parseTopLevel(node)
38991};
38992
38993prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
38994prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit };
38995prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit };
38996prototypeAccessors.canAwait.get = function () {
38997 for (var i = this.scopeStack.length - 1; i >= 0; i--) {
38998 var scope = this.scopeStack[i];
38999 if (scope.inClassFieldInit) { return false }
39000 if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 }
39001 }
39002 return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction
39003};
39004prototypeAccessors.allowSuper.get = function () {
39005 var ref = this.currentThisScope();
39006 var flags = ref.flags;
39007 var inClassFieldInit = ref.inClassFieldInit;
39008 return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod
39009};
39010prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
39011prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };
39012prototypeAccessors.inNonArrowFunction.get = function () {
39013 var ref = this.currentThisScope();
39014 var flags = ref.flags;
39015 var inClassFieldInit = ref.inClassFieldInit;
39016 return (flags & SCOPE_FUNCTION) > 0 || inClassFieldInit
39017};
39018
39019Parser.extend = function extend () {
39020 var plugins = [], len = arguments.length;
39021 while ( len-- ) plugins[ len ] = arguments[ len ];
39022
39023 var cls = this;
39024 for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }
39025 return cls
39026};
39027
39028Parser.parse = function parse (input, options) {
39029 return new this(options, input).parse()
39030};
39031
39032Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {
39033 var parser = new this(options, input, pos);
39034 parser.nextToken();
39035 return parser.parseExpression()
39036};
39037
39038Parser.tokenizer = function tokenizer (input, options) {
39039 return new this(options, input)
39040};
39041
39042Object.defineProperties( Parser.prototype, prototypeAccessors );
39043
39044var pp = Parser.prototype;
39045
39046// ## Parser utilities
39047
39048var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/;
39049pp.strictDirective = function(start) {
39050 for (;;) {
39051 // Try to find string literal.
39052 skipWhiteSpace.lastIndex = start;
39053 start += skipWhiteSpace.exec(this.input)[0].length;
39054 var match = literal.exec(this.input.slice(start));
39055 if (!match) { return false }
39056 if ((match[1] || match[2]) === "use strict") {
39057 skipWhiteSpace.lastIndex = start + match[0].length;
39058 var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
39059 var next = this.input.charAt(end);
39060 return next === ";" || next === "}" ||
39061 (lineBreak.test(spaceAfter[0]) &&
39062 !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))
39063 }
39064 start += match[0].length;
39065
39066 // Skip semicolon, if any.
39067 skipWhiteSpace.lastIndex = start;
39068 start += skipWhiteSpace.exec(this.input)[0].length;
39069 if (this.input[start] === ";")
39070 { start++; }
39071 }
39072};
39073
39074// Predicate that tests whether the next token is of the given
39075// type, and if yes, consumes it as a side effect.
39076
39077pp.eat = function(type) {
39078 if (this.type === type) {
39079 this.next();
39080 return true
39081 } else {
39082 return false
39083 }
39084};
39085
39086// Tests whether parsed token is a contextual keyword.
39087
39088pp.isContextual = function(name) {
39089 return this.type === types.name && this.value === name && !this.containsEsc
39090};
39091
39092// Consumes contextual keyword if possible.
39093
39094pp.eatContextual = function(name) {
39095 if (!this.isContextual(name)) { return false }
39096 this.next();
39097 return true
39098};
39099
39100// Asserts that following token is given contextual keyword.
39101
39102pp.expectContextual = function(name) {
39103 if (!this.eatContextual(name)) { this.unexpected(); }
39104};
39105
39106// Test whether a semicolon can be inserted at the current position.
39107
39108pp.canInsertSemicolon = function() {
39109 return this.type === types.eof ||
39110 this.type === types.braceR ||
39111 lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
39112};
39113
39114pp.insertSemicolon = function() {
39115 if (this.canInsertSemicolon()) {
39116 if (this.options.onInsertedSemicolon)
39117 { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
39118 return true
39119 }
39120};
39121
39122// Consume a semicolon, or, failing that, see if we are allowed to
39123// pretend that there is a semicolon at this position.
39124
39125pp.semicolon = function() {
39126 if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected(); }
39127};
39128
39129pp.afterTrailingComma = function(tokType, notNext) {
39130 if (this.type === tokType) {
39131 if (this.options.onTrailingComma)
39132 { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
39133 if (!notNext)
39134 { this.next(); }
39135 return true
39136 }
39137};
39138
39139// Expect a token of a given type. If found, consume it, otherwise,
39140// raise an unexpected token error.
39141
39142pp.expect = function(type) {
39143 this.eat(type) || this.unexpected();
39144};
39145
39146// Raise an unexpected token error.
39147
39148pp.unexpected = function(pos) {
39149 this.raise(pos != null ? pos : this.start, "Unexpected token");
39150};
39151
39152function DestructuringErrors() {
39153 this.shorthandAssign =
39154 this.trailingComma =
39155 this.parenthesizedAssign =
39156 this.parenthesizedBind =
39157 this.doubleProto =
39158 -1;
39159}
39160
39161pp.checkPatternErrors = function(refDestructuringErrors, isAssign) {
39162 if (!refDestructuringErrors) { return }
39163 if (refDestructuringErrors.trailingComma > -1)
39164 { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
39165 var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
39166 if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); }
39167};
39168
39169pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
39170 if (!refDestructuringErrors) { return false }
39171 var shorthandAssign = refDestructuringErrors.shorthandAssign;
39172 var doubleProto = refDestructuringErrors.doubleProto;
39173 if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
39174 if (shorthandAssign >= 0)
39175 { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
39176 if (doubleProto >= 0)
39177 { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
39178};
39179
39180pp.checkYieldAwaitInDefaultParams = function() {
39181 if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
39182 { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
39183 if (this.awaitPos)
39184 { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
39185};
39186
39187pp.isSimpleAssignTarget = function(expr) {
39188 if (expr.type === "ParenthesizedExpression")
39189 { return this.isSimpleAssignTarget(expr.expression) }
39190 return expr.type === "Identifier" || expr.type === "MemberExpression"
39191};
39192
39193var pp$1 = Parser.prototype;
39194
39195// ### Statement parsing
39196
39197// Parse a program. Initializes the parser, reads any number of
39198// statements, and wraps them in a Program node. Optionally takes a
39199// `program` argument. If present, the statements will be appended
39200// to its body instead of creating a new node.
39201
39202pp$1.parseTopLevel = function(node) {
39203 var exports = Object.create(null);
39204 if (!node.body) { node.body = []; }
39205 while (this.type !== types.eof) {
39206 var stmt = this.parseStatement(null, true, exports);
39207 node.body.push(stmt);
39208 }
39209 if (this.inModule)
39210 { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
39211 {
39212 var name = list[i];
39213
39214 this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));
39215 } }
39216 this.adaptDirectivePrologue(node.body);
39217 this.next();
39218 node.sourceType = this.options.sourceType;
39219 return this.finishNode(node, "Program")
39220};
39221
39222var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
39223
39224pp$1.isLet = function(context) {
39225 if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
39226 skipWhiteSpace.lastIndex = this.pos;
39227 var skip = skipWhiteSpace.exec(this.input);
39228 var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
39229 // For ambiguous cases, determine if a LexicalDeclaration (or only a
39230 // Statement) is allowed here. If context is not empty then only a Statement
39231 // is allowed. However, `let [` is an explicit negative lookahead for
39232 // ExpressionStatement, so special-case it first.
39233 if (nextCh === 91 || nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '[', '/', astral
39234 if (context) { return false }
39235
39236 if (nextCh === 123) { return true } // '{'
39237 if (isIdentifierStart(nextCh, true)) {
39238 var pos = next + 1;
39239 while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; }
39240 if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true }
39241 var ident = this.input.slice(next, pos);
39242 if (!keywordRelationalOperator.test(ident)) { return true }
39243 }
39244 return false
39245};
39246
39247// check 'async [no LineTerminator here] function'
39248// - 'async /*foo*/ function' is OK.
39249// - 'async /*\n*/ function' is invalid.
39250pp$1.isAsyncFunction = function() {
39251 if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
39252 { return false }
39253
39254 skipWhiteSpace.lastIndex = this.pos;
39255 var skip = skipWhiteSpace.exec(this.input);
39256 var next = this.pos + skip[0].length, after;
39257 return !lineBreak.test(this.input.slice(this.pos, next)) &&
39258 this.input.slice(next, next + 8) === "function" &&
39259 (next + 8 === this.input.length ||
39260 !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00))
39261};
39262
39263// Parse a single statement.
39264//
39265// If expecting a statement and finding a slash operator, parse a
39266// regular expression literal. This is to handle cases like
39267// `if (foo) /blah/.exec(foo)`, where looking at the previous token
39268// does not help.
39269
39270pp$1.parseStatement = function(context, topLevel, exports) {
39271 var starttype = this.type, node = this.startNode(), kind;
39272
39273 if (this.isLet(context)) {
39274 starttype = types._var;
39275 kind = "let";
39276 }
39277
39278 // Most types of statements are recognized by the keyword they
39279 // start with. Many are trivial to parse, some require a bit of
39280 // complexity.
39281
39282 switch (starttype) {
39283 case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
39284 case types._debugger: return this.parseDebuggerStatement(node)
39285 case types._do: return this.parseDoStatement(node)
39286 case types._for: return this.parseForStatement(node)
39287 case types._function:
39288 // Function as sole body of either an if statement or a labeled statement
39289 // works, but not when it is part of a labeled statement that is the sole
39290 // body of an if statement.
39291 if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }
39292 return this.parseFunctionStatement(node, false, !context)
39293 case types._class:
39294 if (context) { this.unexpected(); }
39295 return this.parseClass(node, true)
39296 case types._if: return this.parseIfStatement(node)
39297 case types._return: return this.parseReturnStatement(node)
39298 case types._switch: return this.parseSwitchStatement(node)
39299 case types._throw: return this.parseThrowStatement(node)
39300 case types._try: return this.parseTryStatement(node)
39301 case types._const: case types._var:
39302 kind = kind || this.value;
39303 if (context && kind !== "var") { this.unexpected(); }
39304 return this.parseVarStatement(node, kind)
39305 case types._while: return this.parseWhileStatement(node)
39306 case types._with: return this.parseWithStatement(node)
39307 case types.braceL: return this.parseBlock(true, node)
39308 case types.semi: return this.parseEmptyStatement(node)
39309 case types._export:
39310 case types._import:
39311 if (this.options.ecmaVersion > 10 && starttype === types._import) {
39312 skipWhiteSpace.lastIndex = this.pos;
39313 var skip = skipWhiteSpace.exec(this.input);
39314 var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
39315 if (nextCh === 40 || nextCh === 46) // '(' or '.'
39316 { return this.parseExpressionStatement(node, this.parseExpression()) }
39317 }
39318
39319 if (!this.options.allowImportExportEverywhere) {
39320 if (!topLevel)
39321 { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
39322 if (!this.inModule)
39323 { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
39324 }
39325 return starttype === types._import ? this.parseImport(node) : this.parseExport(node, exports)
39326
39327 // If the statement does not start with a statement keyword or a
39328 // brace, it's an ExpressionStatement or LabeledStatement. We
39329 // simply start parsing an expression, and afterwards, if the
39330 // next token is a colon and the expression was a simple
39331 // Identifier node, we switch to interpreting it as a label.
39332 default:
39333 if (this.isAsyncFunction()) {
39334 if (context) { this.unexpected(); }
39335 this.next();
39336 return this.parseFunctionStatement(node, true, !context)
39337 }
39338
39339 var maybeName = this.value, expr = this.parseExpression();
39340 if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon))
39341 { return this.parseLabeledStatement(node, maybeName, expr, context) }
39342 else { return this.parseExpressionStatement(node, expr) }
39343 }
39344};
39345
39346pp$1.parseBreakContinueStatement = function(node, keyword) {
39347 var isBreak = keyword === "break";
39348 this.next();
39349 if (this.eat(types.semi) || this.insertSemicolon()) { node.label = null; }
39350 else if (this.type !== types.name) { this.unexpected(); }
39351 else {
39352 node.label = this.parseIdent();
39353 this.semicolon();
39354 }
39355
39356 // Verify that there is an actual destination to break or
39357 // continue to.
39358 var i = 0;
39359 for (; i < this.labels.length; ++i) {
39360 var lab = this.labels[i];
39361 if (node.label == null || lab.name === node.label.name) {
39362 if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
39363 if (node.label && isBreak) { break }
39364 }
39365 }
39366 if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
39367 return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
39368};
39369
39370pp$1.parseDebuggerStatement = function(node) {
39371 this.next();
39372 this.semicolon();
39373 return this.finishNode(node, "DebuggerStatement")
39374};
39375
39376pp$1.parseDoStatement = function(node) {
39377 this.next();
39378 this.labels.push(loopLabel);
39379 node.body = this.parseStatement("do");
39380 this.labels.pop();
39381 this.expect(types._while);
39382 node.test = this.parseParenExpression();
39383 if (this.options.ecmaVersion >= 6)
39384 { this.eat(types.semi); }
39385 else
39386 { this.semicolon(); }
39387 return this.finishNode(node, "DoWhileStatement")
39388};
39389
39390// Disambiguating between a `for` and a `for`/`in` or `for`/`of`
39391// loop is non-trivial. Basically, we have to parse the init `var`
39392// statement or expression, disallowing the `in` operator (see
39393// the second parameter to `parseExpression`), and then check
39394// whether the next token is `in` or `of`. When there is no init
39395// part (semicolon immediately after the opening parenthesis), it
39396// is a regular `for` loop.
39397
39398pp$1.parseForStatement = function(node) {
39399 this.next();
39400 var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1;
39401 this.labels.push(loopLabel);
39402 this.enterScope(0);
39403 this.expect(types.parenL);
39404 if (this.type === types.semi) {
39405 if (awaitAt > -1) { this.unexpected(awaitAt); }
39406 return this.parseFor(node, null)
39407 }
39408 var isLet = this.isLet();
39409 if (this.type === types._var || this.type === types._const || isLet) {
39410 var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
39411 this.next();
39412 this.parseVar(init$1, true, kind);
39413 this.finishNode(init$1, "VariableDeclaration");
39414 if ((this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {
39415 if (this.options.ecmaVersion >= 9) {
39416 if (this.type === types._in) {
39417 if (awaitAt > -1) { this.unexpected(awaitAt); }
39418 } else { node.await = awaitAt > -1; }
39419 }
39420 return this.parseForIn(node, init$1)
39421 }
39422 if (awaitAt > -1) { this.unexpected(awaitAt); }
39423 return this.parseFor(node, init$1)
39424 }
39425 var refDestructuringErrors = new DestructuringErrors;
39426 var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors);
39427 if (this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
39428 if (this.options.ecmaVersion >= 9) {
39429 if (this.type === types._in) {
39430 if (awaitAt > -1) { this.unexpected(awaitAt); }
39431 } else { node.await = awaitAt > -1; }
39432 }
39433 this.toAssignable(init, false, refDestructuringErrors);
39434 this.checkLValPattern(init);
39435 return this.parseForIn(node, init)
39436 } else {
39437 this.checkExpressionErrors(refDestructuringErrors, true);
39438 }
39439 if (awaitAt > -1) { this.unexpected(awaitAt); }
39440 return this.parseFor(node, init)
39441};
39442
39443pp$1.parseFunctionStatement = function(node, isAsync, declarationPosition) {
39444 this.next();
39445 return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
39446};
39447
39448pp$1.parseIfStatement = function(node) {
39449 this.next();
39450 node.test = this.parseParenExpression();
39451 // allow function declarations in branches, but only in non-strict mode
39452 node.consequent = this.parseStatement("if");
39453 node.alternate = this.eat(types._else) ? this.parseStatement("if") : null;
39454 return this.finishNode(node, "IfStatement")
39455};
39456
39457pp$1.parseReturnStatement = function(node) {
39458 if (!this.inFunction && !this.options.allowReturnOutsideFunction)
39459 { this.raise(this.start, "'return' outside of function"); }
39460 this.next();
39461
39462 // In `return` (and `break`/`continue`), the keywords with
39463 // optional arguments, we eagerly look for a semicolon or the
39464 // possibility to insert one.
39465
39466 if (this.eat(types.semi) || this.insertSemicolon()) { node.argument = null; }
39467 else { node.argument = this.parseExpression(); this.semicolon(); }
39468 return this.finishNode(node, "ReturnStatement")
39469};
39470
39471pp$1.parseSwitchStatement = function(node) {
39472 this.next();
39473 node.discriminant = this.parseParenExpression();
39474 node.cases = [];
39475 this.expect(types.braceL);
39476 this.labels.push(switchLabel);
39477 this.enterScope(0);
39478
39479 // Statements under must be grouped (by label) in SwitchCase
39480 // nodes. `cur` is used to keep the node that we are currently
39481 // adding statements to.
39482
39483 var cur;
39484 for (var sawDefault = false; this.type !== types.braceR;) {
39485 if (this.type === types._case || this.type === types._default) {
39486 var isCase = this.type === types._case;
39487 if (cur) { this.finishNode(cur, "SwitchCase"); }
39488 node.cases.push(cur = this.startNode());
39489 cur.consequent = [];
39490 this.next();
39491 if (isCase) {
39492 cur.test = this.parseExpression();
39493 } else {
39494 if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }
39495 sawDefault = true;
39496 cur.test = null;
39497 }
39498 this.expect(types.colon);
39499 } else {
39500 if (!cur) { this.unexpected(); }
39501 cur.consequent.push(this.parseStatement(null));
39502 }
39503 }
39504 this.exitScope();
39505 if (cur) { this.finishNode(cur, "SwitchCase"); }
39506 this.next(); // Closing brace
39507 this.labels.pop();
39508 return this.finishNode(node, "SwitchStatement")
39509};
39510
39511pp$1.parseThrowStatement = function(node) {
39512 this.next();
39513 if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
39514 { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
39515 node.argument = this.parseExpression();
39516 this.semicolon();
39517 return this.finishNode(node, "ThrowStatement")
39518};
39519
39520// Reused empty array added for node fields that are always empty.
39521
39522var empty = [];
39523
39524pp$1.parseTryStatement = function(node) {
39525 this.next();
39526 node.block = this.parseBlock();
39527 node.handler = null;
39528 if (this.type === types._catch) {
39529 var clause = this.startNode();
39530 this.next();
39531 if (this.eat(types.parenL)) {
39532 clause.param = this.parseBindingAtom();
39533 var simple = clause.param.type === "Identifier";
39534 this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
39535 this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
39536 this.expect(types.parenR);
39537 } else {
39538 if (this.options.ecmaVersion < 10) { this.unexpected(); }
39539 clause.param = null;
39540 this.enterScope(0);
39541 }
39542 clause.body = this.parseBlock(false);
39543 this.exitScope();
39544 node.handler = this.finishNode(clause, "CatchClause");
39545 }
39546 node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;
39547 if (!node.handler && !node.finalizer)
39548 { this.raise(node.start, "Missing catch or finally clause"); }
39549 return this.finishNode(node, "TryStatement")
39550};
39551
39552pp$1.parseVarStatement = function(node, kind) {
39553 this.next();
39554 this.parseVar(node, false, kind);
39555 this.semicolon();
39556 return this.finishNode(node, "VariableDeclaration")
39557};
39558
39559pp$1.parseWhileStatement = function(node) {
39560 this.next();
39561 node.test = this.parseParenExpression();
39562 this.labels.push(loopLabel);
39563 node.body = this.parseStatement("while");
39564 this.labels.pop();
39565 return this.finishNode(node, "WhileStatement")
39566};
39567
39568pp$1.parseWithStatement = function(node) {
39569 if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
39570 this.next();
39571 node.object = this.parseParenExpression();
39572 node.body = this.parseStatement("with");
39573 return this.finishNode(node, "WithStatement")
39574};
39575
39576pp$1.parseEmptyStatement = function(node) {
39577 this.next();
39578 return this.finishNode(node, "EmptyStatement")
39579};
39580
39581pp$1.parseLabeledStatement = function(node, maybeName, expr, context) {
39582 for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)
39583 {
39584 var label = list[i$1];
39585
39586 if (label.name === maybeName)
39587 { this.raise(expr.start, "Label '" + maybeName + "' is already declared");
39588 } }
39589 var kind = this.type.isLoop ? "loop" : this.type === types._switch ? "switch" : null;
39590 for (var i = this.labels.length - 1; i >= 0; i--) {
39591 var label$1 = this.labels[i];
39592 if (label$1.statementStart === node.start) {
39593 // Update information about previous labels on this node
39594 label$1.statementStart = this.start;
39595 label$1.kind = kind;
39596 } else { break }
39597 }
39598 this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
39599 node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
39600 this.labels.pop();
39601 node.label = expr;
39602 return this.finishNode(node, "LabeledStatement")
39603};
39604
39605pp$1.parseExpressionStatement = function(node, expr) {
39606 node.expression = expr;
39607 this.semicolon();
39608 return this.finishNode(node, "ExpressionStatement")
39609};
39610
39611// Parse a semicolon-enclosed block of statements, handling `"use
39612// strict"` declarations when `allowStrict` is true (used for
39613// function bodies).
39614
39615pp$1.parseBlock = function(createNewLexicalScope, node, exitStrict) {
39616 if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
39617 if ( node === void 0 ) node = this.startNode();
39618
39619 node.body = [];
39620 this.expect(types.braceL);
39621 if (createNewLexicalScope) { this.enterScope(0); }
39622 while (this.type !== types.braceR) {
39623 var stmt = this.parseStatement(null);
39624 node.body.push(stmt);
39625 }
39626 if (exitStrict) { this.strict = false; }
39627 this.next();
39628 if (createNewLexicalScope) { this.exitScope(); }
39629 return this.finishNode(node, "BlockStatement")
39630};
39631
39632// Parse a regular `for` loop. The disambiguation code in
39633// `parseStatement` will already have parsed the init statement or
39634// expression.
39635
39636pp$1.parseFor = function(node, init) {
39637 node.init = init;
39638 this.expect(types.semi);
39639 node.test = this.type === types.semi ? null : this.parseExpression();
39640 this.expect(types.semi);
39641 node.update = this.type === types.parenR ? null : this.parseExpression();
39642 this.expect(types.parenR);
39643 node.body = this.parseStatement("for");
39644 this.exitScope();
39645 this.labels.pop();
39646 return this.finishNode(node, "ForStatement")
39647};
39648
39649// Parse a `for`/`in` and `for`/`of` loop, which are almost
39650// same from parser's perspective.
39651
39652pp$1.parseForIn = function(node, init) {
39653 var isForIn = this.type === types._in;
39654 this.next();
39655
39656 if (
39657 init.type === "VariableDeclaration" &&
39658 init.declarations[0].init != null &&
39659 (
39660 !isForIn ||
39661 this.options.ecmaVersion < 8 ||
39662 this.strict ||
39663 init.kind !== "var" ||
39664 init.declarations[0].id.type !== "Identifier"
39665 )
39666 ) {
39667 this.raise(
39668 init.start,
39669 ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
39670 );
39671 }
39672 node.left = init;
39673 node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
39674 this.expect(types.parenR);
39675 node.body = this.parseStatement("for");
39676 this.exitScope();
39677 this.labels.pop();
39678 return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
39679};
39680
39681// Parse a list of variable declarations.
39682
39683pp$1.parseVar = function(node, isFor, kind) {
39684 node.declarations = [];
39685 node.kind = kind;
39686 for (;;) {
39687 var decl = this.startNode();
39688 this.parseVarId(decl, kind);
39689 if (this.eat(types.eq)) {
39690 decl.init = this.parseMaybeAssign(isFor);
39691 } else if (kind === "const" && !(this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
39692 this.unexpected();
39693 } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types._in || this.isContextual("of")))) {
39694 this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
39695 } else {
39696 decl.init = null;
39697 }
39698 node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
39699 if (!this.eat(types.comma)) { break }
39700 }
39701 return node
39702};
39703
39704pp$1.parseVarId = function(decl, kind) {
39705 decl.id = this.parseBindingAtom();
39706 this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
39707};
39708
39709var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;
39710
39711// Parse a function declaration or literal (depending on the
39712// `statement & FUNC_STATEMENT`).
39713
39714// Remove `allowExpressionBody` for 7.0.0, as it is only called with false
39715pp$1.parseFunction = function(node, statement, allowExpressionBody, isAsync) {
39716 this.initFunction(node);
39717 if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
39718 if (this.type === types.star && (statement & FUNC_HANGING_STATEMENT))
39719 { this.unexpected(); }
39720 node.generator = this.eat(types.star);
39721 }
39722 if (this.options.ecmaVersion >= 8)
39723 { node.async = !!isAsync; }
39724
39725 if (statement & FUNC_STATEMENT) {
39726 node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types.name ? null : this.parseIdent();
39727 if (node.id && !(statement & FUNC_HANGING_STATEMENT))
39728 // If it is a regular function declaration in sloppy mode, then it is
39729 // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
39730 // mode depends on properties of the current scope (see
39731 // treatFunctionsAsVar).
39732 { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }
39733 }
39734
39735 var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
39736 this.yieldPos = 0;
39737 this.awaitPos = 0;
39738 this.awaitIdentPos = 0;
39739 this.enterScope(functionFlags(node.async, node.generator));
39740
39741 if (!(statement & FUNC_STATEMENT))
39742 { node.id = this.type === types.name ? this.parseIdent() : null; }
39743
39744 this.parseFunctionParams(node);
39745 this.parseFunctionBody(node, allowExpressionBody, false);
39746
39747 this.yieldPos = oldYieldPos;
39748 this.awaitPos = oldAwaitPos;
39749 this.awaitIdentPos = oldAwaitIdentPos;
39750 return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression")
39751};
39752
39753pp$1.parseFunctionParams = function(node) {
39754 this.expect(types.parenL);
39755 node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
39756 this.checkYieldAwaitInDefaultParams();
39757};
39758
39759// Parse a class declaration or literal (depending on the
39760// `isStatement` parameter).
39761
39762pp$1.parseClass = function(node, isStatement) {
39763 this.next();
39764
39765 // ecma-262 14.6 Class Definitions
39766 // A class definition is always strict mode code.
39767 var oldStrict = this.strict;
39768 this.strict = true;
39769
39770 this.parseClassId(node, isStatement);
39771 this.parseClassSuper(node);
39772 var privateNameMap = this.enterClassBody();
39773 var classBody = this.startNode();
39774 var hadConstructor = false;
39775 classBody.body = [];
39776 this.expect(types.braceL);
39777 while (this.type !== types.braceR) {
39778 var element = this.parseClassElement(node.superClass !== null);
39779 if (element) {
39780 classBody.body.push(element);
39781 if (element.type === "MethodDefinition" && element.kind === "constructor") {
39782 if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); }
39783 hadConstructor = true;
39784 } else if (element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) {
39785 this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared"));
39786 }
39787 }
39788 }
39789 this.strict = oldStrict;
39790 this.next();
39791 node.body = this.finishNode(classBody, "ClassBody");
39792 this.exitClassBody();
39793 return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
39794};
39795
39796pp$1.parseClassElement = function(constructorAllowsSuper) {
39797 if (this.eat(types.semi)) { return null }
39798
39799 var ecmaVersion = this.options.ecmaVersion;
39800 var node = this.startNode();
39801 var keyName = "";
39802 var isGenerator = false;
39803 var isAsync = false;
39804 var kind = "method";
39805
39806 // Parse modifiers
39807 node.static = false;
39808 if (this.eatContextual("static")) {
39809 if (this.isClassElementNameStart() || this.type === types.star) {
39810 node.static = true;
39811 } else {
39812 keyName = "static";
39813 }
39814 }
39815 if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) {
39816 if ((this.isClassElementNameStart() || this.type === types.star) && !this.canInsertSemicolon()) {
39817 isAsync = true;
39818 } else {
39819 keyName = "async";
39820 }
39821 }
39822 if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types.star)) {
39823 isGenerator = true;
39824 }
39825 if (!keyName && !isAsync && !isGenerator) {
39826 var lastValue = this.value;
39827 if (this.eatContextual("get") || this.eatContextual("set")) {
39828 if (this.isClassElementNameStart()) {
39829 kind = lastValue;
39830 } else {
39831 keyName = lastValue;
39832 }
39833 }
39834 }
39835
39836 // Parse element name
39837 if (keyName) {
39838 // 'async', 'get', 'set', or 'static' were not a keyword contextually.
39839 // The last token is any of those. Make it the element name.
39840 node.computed = false;
39841 node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);
39842 node.key.name = keyName;
39843 this.finishNode(node.key, "Identifier");
39844 } else {
39845 this.parseClassElementName(node);
39846 }
39847
39848 // Parse element value
39849 if (ecmaVersion < 13 || this.type === types.parenL || kind !== "method" || isGenerator || isAsync) {
39850 var isConstructor = !node.static && checkKeyName(node, "constructor");
39851 var allowsDirectSuper = isConstructor && constructorAllowsSuper;
39852 // Couldn't move this check into the 'parseClassMethod' method for backward compatibility.
39853 if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); }
39854 node.kind = isConstructor ? "constructor" : kind;
39855 this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper);
39856 } else {
39857 this.parseClassField(node);
39858 }
39859
39860 return node
39861};
39862
39863pp$1.isClassElementNameStart = function() {
39864 return (
39865 this.type === types.name ||
39866 this.type === types.privateId ||
39867 this.type === types.num ||
39868 this.type === types.string ||
39869 this.type === types.bracketL ||
39870 this.type.keyword
39871 )
39872};
39873
39874pp$1.parseClassElementName = function(element) {
39875 if (this.type === types.privateId) {
39876 if (this.value === "constructor") {
39877 this.raise(this.start, "Classes can't have an element named '#constructor'");
39878 }
39879 element.computed = false;
39880 element.key = this.parsePrivateIdent();
39881 } else {
39882 this.parsePropertyName(element);
39883 }
39884};
39885
39886pp$1.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
39887 // Check key and flags
39888 var key = method.key;
39889 if (method.kind === "constructor") {
39890 if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
39891 if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
39892 } else if (method.static && checkKeyName(method, "prototype")) {
39893 this.raise(key.start, "Classes may not have a static property named prototype");
39894 }
39895
39896 // Parse value
39897 var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
39898
39899 // Check value
39900 if (method.kind === "get" && value.params.length !== 0)
39901 { this.raiseRecoverable(value.start, "getter should have no params"); }
39902 if (method.kind === "set" && value.params.length !== 1)
39903 { this.raiseRecoverable(value.start, "setter should have exactly one param"); }
39904 if (method.kind === "set" && value.params[0].type === "RestElement")
39905 { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); }
39906
39907 return this.finishNode(method, "MethodDefinition")
39908};
39909
39910pp$1.parseClassField = function(field) {
39911 if (checkKeyName(field, "constructor")) {
39912 this.raise(field.key.start, "Classes can't have a field named 'constructor'");
39913 } else if (field.static && checkKeyName(field, "prototype")) {
39914 this.raise(field.key.start, "Classes can't have a static field named 'prototype'");
39915 }
39916
39917 if (this.eat(types.eq)) {
39918 // To raise SyntaxError if 'arguments' exists in the initializer.
39919 var scope = this.currentThisScope();
39920 var inClassFieldInit = scope.inClassFieldInit;
39921 scope.inClassFieldInit = true;
39922 field.value = this.parseMaybeAssign();
39923 scope.inClassFieldInit = inClassFieldInit;
39924 } else {
39925 field.value = null;
39926 }
39927 this.semicolon();
39928
39929 return this.finishNode(field, "PropertyDefinition")
39930};
39931
39932pp$1.parseClassId = function(node, isStatement) {
39933 if (this.type === types.name) {
39934 node.id = this.parseIdent();
39935 if (isStatement)
39936 { this.checkLValSimple(node.id, BIND_LEXICAL, false); }
39937 } else {
39938 if (isStatement === true)
39939 { this.unexpected(); }
39940 node.id = null;
39941 }
39942};
39943
39944pp$1.parseClassSuper = function(node) {
39945 node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;
39946};
39947
39948pp$1.enterClassBody = function() {
39949 var element = {declared: Object.create(null), used: []};
39950 this.privateNameStack.push(element);
39951 return element.declared
39952};
39953
39954pp$1.exitClassBody = function() {
39955 var ref = this.privateNameStack.pop();
39956 var declared = ref.declared;
39957 var used = ref.used;
39958 var len = this.privateNameStack.length;
39959 var parent = len === 0 ? null : this.privateNameStack[len - 1];
39960 for (var i = 0; i < used.length; ++i) {
39961 var id = used[i];
39962 if (!has(declared, id.name)) {
39963 if (parent) {
39964 parent.used.push(id);
39965 } else {
39966 this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class"));
39967 }
39968 }
39969 }
39970};
39971
39972function isPrivateNameConflicted(privateNameMap, element) {
39973 var name = element.key.name;
39974 var curr = privateNameMap[name];
39975
39976 var next = "true";
39977 if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
39978 next = (element.static ? "s" : "i") + element.kind;
39979 }
39980
39981 // `class { get #a(){}; static set #a(_){} }` is also conflict.
39982 if (
39983 curr === "iget" && next === "iset" ||
39984 curr === "iset" && next === "iget" ||
39985 curr === "sget" && next === "sset" ||
39986 curr === "sset" && next === "sget"
39987 ) {
39988 privateNameMap[name] = "true";
39989 return false
39990 } else if (!curr) {
39991 privateNameMap[name] = next;
39992 return false
39993 } else {
39994 return true
39995 }
39996}
39997
39998function checkKeyName(node, name) {
39999 var computed = node.computed;
40000 var key = node.key;
40001 return !computed && (
40002 key.type === "Identifier" && key.name === name ||
40003 key.type === "Literal" && key.value === name
40004 )
40005}
40006
40007// Parses module export declaration.
40008
40009pp$1.parseExport = function(node, exports) {
40010 this.next();
40011 // export * from '...'
40012 if (this.eat(types.star)) {
40013 if (this.options.ecmaVersion >= 11) {
40014 if (this.eatContextual("as")) {
40015 node.exported = this.parseIdent(true);
40016 this.checkExport(exports, node.exported.name, this.lastTokStart);
40017 } else {
40018 node.exported = null;
40019 }
40020 }
40021 this.expectContextual("from");
40022 if (this.type !== types.string) { this.unexpected(); }
40023 node.source = this.parseExprAtom();
40024 this.semicolon();
40025 return this.finishNode(node, "ExportAllDeclaration")
40026 }
40027 if (this.eat(types._default)) { // export default ...
40028 this.checkExport(exports, "default", this.lastTokStart);
40029 var isAsync;
40030 if (this.type === types._function || (isAsync = this.isAsyncFunction())) {
40031 var fNode = this.startNode();
40032 this.next();
40033 if (isAsync) { this.next(); }
40034 node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
40035 } else if (this.type === types._class) {
40036 var cNode = this.startNode();
40037 node.declaration = this.parseClass(cNode, "nullableID");
40038 } else {
40039 node.declaration = this.parseMaybeAssign();
40040 this.semicolon();
40041 }
40042 return this.finishNode(node, "ExportDefaultDeclaration")
40043 }
40044 // export var|const|let|function|class ...
40045 if (this.shouldParseExportStatement()) {
40046 node.declaration = this.parseStatement(null);
40047 if (node.declaration.type === "VariableDeclaration")
40048 { this.checkVariableExport(exports, node.declaration.declarations); }
40049 else
40050 { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); }
40051 node.specifiers = [];
40052 node.source = null;
40053 } else { // export { x, y as z } [from '...']
40054 node.declaration = null;
40055 node.specifiers = this.parseExportSpecifiers(exports);
40056 if (this.eatContextual("from")) {
40057 if (this.type !== types.string) { this.unexpected(); }
40058 node.source = this.parseExprAtom();
40059 } else {
40060 for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
40061 // check for keywords used as local names
40062 var spec = list[i];
40063
40064 this.checkUnreserved(spec.local);
40065 // check if export is defined
40066 this.checkLocalExport(spec.local);
40067 }
40068
40069 node.source = null;
40070 }
40071 this.semicolon();
40072 }
40073 return this.finishNode(node, "ExportNamedDeclaration")
40074};
40075
40076pp$1.checkExport = function(exports, name, pos) {
40077 if (!exports) { return }
40078 if (has(exports, name))
40079 { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
40080 exports[name] = true;
40081};
40082
40083pp$1.checkPatternExport = function(exports, pat) {
40084 var type = pat.type;
40085 if (type === "Identifier")
40086 { this.checkExport(exports, pat.name, pat.start); }
40087 else if (type === "ObjectPattern")
40088 { for (var i = 0, list = pat.properties; i < list.length; i += 1)
40089 {
40090 var prop = list[i];
40091
40092 this.checkPatternExport(exports, prop);
40093 } }
40094 else if (type === "ArrayPattern")
40095 { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
40096 var elt = list$1[i$1];
40097
40098 if (elt) { this.checkPatternExport(exports, elt); }
40099 } }
40100 else if (type === "Property")
40101 { this.checkPatternExport(exports, pat.value); }
40102 else if (type === "AssignmentPattern")
40103 { this.checkPatternExport(exports, pat.left); }
40104 else if (type === "RestElement")
40105 { this.checkPatternExport(exports, pat.argument); }
40106 else if (type === "ParenthesizedExpression")
40107 { this.checkPatternExport(exports, pat.expression); }
40108};
40109
40110pp$1.checkVariableExport = function(exports, decls) {
40111 if (!exports) { return }
40112 for (var i = 0, list = decls; i < list.length; i += 1)
40113 {
40114 var decl = list[i];
40115
40116 this.checkPatternExport(exports, decl.id);
40117 }
40118};
40119
40120pp$1.shouldParseExportStatement = function() {
40121 return this.type.keyword === "var" ||
40122 this.type.keyword === "const" ||
40123 this.type.keyword === "class" ||
40124 this.type.keyword === "function" ||
40125 this.isLet() ||
40126 this.isAsyncFunction()
40127};
40128
40129// Parses a comma-separated list of module exports.
40130
40131pp$1.parseExportSpecifiers = function(exports) {
40132 var nodes = [], first = true;
40133 // export { x, y as z } [from '...']
40134 this.expect(types.braceL);
40135 while (!this.eat(types.braceR)) {
40136 if (!first) {
40137 this.expect(types.comma);
40138 if (this.afterTrailingComma(types.braceR)) { break }
40139 } else { first = false; }
40140
40141 var node = this.startNode();
40142 node.local = this.parseIdent(true);
40143 node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local;
40144 this.checkExport(exports, node.exported.name, node.exported.start);
40145 nodes.push(this.finishNode(node, "ExportSpecifier"));
40146 }
40147 return nodes
40148};
40149
40150// Parses import declaration.
40151
40152pp$1.parseImport = function(node) {
40153 this.next();
40154 // import '...'
40155 if (this.type === types.string) {
40156 node.specifiers = empty;
40157 node.source = this.parseExprAtom();
40158 } else {
40159 node.specifiers = this.parseImportSpecifiers();
40160 this.expectContextual("from");
40161 node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected();
40162 }
40163 this.semicolon();
40164 return this.finishNode(node, "ImportDeclaration")
40165};
40166
40167// Parses a comma-separated list of module imports.
40168
40169pp$1.parseImportSpecifiers = function() {
40170 var nodes = [], first = true;
40171 if (this.type === types.name) {
40172 // import defaultObj, { x, y as z } from '...'
40173 var node = this.startNode();
40174 node.local = this.parseIdent();
40175 this.checkLValSimple(node.local, BIND_LEXICAL);
40176 nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
40177 if (!this.eat(types.comma)) { return nodes }
40178 }
40179 if (this.type === types.star) {
40180 var node$1 = this.startNode();
40181 this.next();
40182 this.expectContextual("as");
40183 node$1.local = this.parseIdent();
40184 this.checkLValSimple(node$1.local, BIND_LEXICAL);
40185 nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
40186 return nodes
40187 }
40188 this.expect(types.braceL);
40189 while (!this.eat(types.braceR)) {
40190 if (!first) {
40191 this.expect(types.comma);
40192 if (this.afterTrailingComma(types.braceR)) { break }
40193 } else { first = false; }
40194
40195 var node$2 = this.startNode();
40196 node$2.imported = this.parseIdent(true);
40197 if (this.eatContextual("as")) {
40198 node$2.local = this.parseIdent();
40199 } else {
40200 this.checkUnreserved(node$2.imported);
40201 node$2.local = node$2.imported;
40202 }
40203 this.checkLValSimple(node$2.local, BIND_LEXICAL);
40204 nodes.push(this.finishNode(node$2, "ImportSpecifier"));
40205 }
40206 return nodes
40207};
40208
40209// Set `ExpressionStatement#directive` property for directive prologues.
40210pp$1.adaptDirectivePrologue = function(statements) {
40211 for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
40212 statements[i].directive = statements[i].expression.raw.slice(1, -1);
40213 }
40214};
40215pp$1.isDirectiveCandidate = function(statement) {
40216 return (
40217 statement.type === "ExpressionStatement" &&
40218 statement.expression.type === "Literal" &&
40219 typeof statement.expression.value === "string" &&
40220 // Reject parenthesized strings.
40221 (this.input[statement.start] === "\"" || this.input[statement.start] === "'")
40222 )
40223};
40224
40225var pp$2 = Parser.prototype;
40226
40227// Convert existing expression atom to assignable pattern
40228// if possible.
40229
40230pp$2.toAssignable = function(node, isBinding, refDestructuringErrors) {
40231 if (this.options.ecmaVersion >= 6 && node) {
40232 switch (node.type) {
40233 case "Identifier":
40234 if (this.inAsync && node.name === "await")
40235 { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }
40236 break
40237
40238 case "ObjectPattern":
40239 case "ArrayPattern":
40240 case "AssignmentPattern":
40241 case "RestElement":
40242 break
40243
40244 case "ObjectExpression":
40245 node.type = "ObjectPattern";
40246 if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
40247 for (var i = 0, list = node.properties; i < list.length; i += 1) {
40248 var prop = list[i];
40249
40250 this.toAssignable(prop, isBinding);
40251 // Early error:
40252 // AssignmentRestProperty[Yield, Await] :
40253 // `...` DestructuringAssignmentTarget[Yield, Await]
40254 //
40255 // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
40256 if (
40257 prop.type === "RestElement" &&
40258 (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
40259 ) {
40260 this.raise(prop.argument.start, "Unexpected token");
40261 }
40262 }
40263 break
40264
40265 case "Property":
40266 // AssignmentProperty has type === "Property"
40267 if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
40268 this.toAssignable(node.value, isBinding);
40269 break
40270
40271 case "ArrayExpression":
40272 node.type = "ArrayPattern";
40273 if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
40274 this.toAssignableList(node.elements, isBinding);
40275 break
40276
40277 case "SpreadElement":
40278 node.type = "RestElement";
40279 this.toAssignable(node.argument, isBinding);
40280 if (node.argument.type === "AssignmentPattern")
40281 { this.raise(node.argument.start, "Rest elements cannot have a default value"); }
40282 break
40283
40284 case "AssignmentExpression":
40285 if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
40286 node.type = "AssignmentPattern";
40287 delete node.operator;
40288 this.toAssignable(node.left, isBinding);
40289 break
40290
40291 case "ParenthesizedExpression":
40292 this.toAssignable(node.expression, isBinding, refDestructuringErrors);
40293 break
40294
40295 case "ChainExpression":
40296 this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
40297 break
40298
40299 case "MemberExpression":
40300 if (!isBinding) { break }
40301
40302 default:
40303 this.raise(node.start, "Assigning to rvalue");
40304 }
40305 } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
40306 return node
40307};
40308
40309// Convert list of expression atoms to binding list.
40310
40311pp$2.toAssignableList = function(exprList, isBinding) {
40312 var end = exprList.length;
40313 for (var i = 0; i < end; i++) {
40314 var elt = exprList[i];
40315 if (elt) { this.toAssignable(elt, isBinding); }
40316 }
40317 if (end) {
40318 var last = exprList[end - 1];
40319 if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
40320 { this.unexpected(last.argument.start); }
40321 }
40322 return exprList
40323};
40324
40325// Parses spread element.
40326
40327pp$2.parseSpread = function(refDestructuringErrors) {
40328 var node = this.startNode();
40329 this.next();
40330 node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
40331 return this.finishNode(node, "SpreadElement")
40332};
40333
40334pp$2.parseRestBinding = function() {
40335 var node = this.startNode();
40336 this.next();
40337
40338 // RestElement inside of a function parameter must be an identifier
40339 if (this.options.ecmaVersion === 6 && this.type !== types.name)
40340 { this.unexpected(); }
40341
40342 node.argument = this.parseBindingAtom();
40343
40344 return this.finishNode(node, "RestElement")
40345};
40346
40347// Parses lvalue (assignable) atom.
40348
40349pp$2.parseBindingAtom = function() {
40350 if (this.options.ecmaVersion >= 6) {
40351 switch (this.type) {
40352 case types.bracketL:
40353 var node = this.startNode();
40354 this.next();
40355 node.elements = this.parseBindingList(types.bracketR, true, true);
40356 return this.finishNode(node, "ArrayPattern")
40357
40358 case types.braceL:
40359 return this.parseObj(true)
40360 }
40361 }
40362 return this.parseIdent()
40363};
40364
40365pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
40366 var elts = [], first = true;
40367 while (!this.eat(close)) {
40368 if (first) { first = false; }
40369 else { this.expect(types.comma); }
40370 if (allowEmpty && this.type === types.comma) {
40371 elts.push(null);
40372 } else if (allowTrailingComma && this.afterTrailingComma(close)) {
40373 break
40374 } else if (this.type === types.ellipsis) {
40375 var rest = this.parseRestBinding();
40376 this.parseBindingListItem(rest);
40377 elts.push(rest);
40378 if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
40379 this.expect(close);
40380 break
40381 } else {
40382 var elem = this.parseMaybeDefault(this.start, this.startLoc);
40383 this.parseBindingListItem(elem);
40384 elts.push(elem);
40385 }
40386 }
40387 return elts
40388};
40389
40390pp$2.parseBindingListItem = function(param) {
40391 return param
40392};
40393
40394// Parses assignment pattern around given atom if possible.
40395
40396pp$2.parseMaybeDefault = function(startPos, startLoc, left) {
40397 left = left || this.parseBindingAtom();
40398 if (this.options.ecmaVersion < 6 || !this.eat(types.eq)) { return left }
40399 var node = this.startNodeAt(startPos, startLoc);
40400 node.left = left;
40401 node.right = this.parseMaybeAssign();
40402 return this.finishNode(node, "AssignmentPattern")
40403};
40404
40405// The following three functions all verify that a node is an lvalue —
40406// something that can be bound, or assigned to. In order to do so, they perform
40407// a variety of checks:
40408//
40409// - Check that none of the bound/assigned-to identifiers are reserved words.
40410// - Record name declarations for bindings in the appropriate scope.
40411// - Check duplicate argument names, if checkClashes is set.
40412//
40413// If a complex binding pattern is encountered (e.g., object and array
40414// destructuring), the entire pattern is recursively checked.
40415//
40416// There are three versions of checkLVal*() appropriate for different
40417// circumstances:
40418//
40419// - checkLValSimple() shall be used if the syntactic construct supports
40420// nothing other than identifiers and member expressions. Parenthesized
40421// expressions are also correctly handled. This is generally appropriate for
40422// constructs for which the spec says
40423//
40424// > It is a Syntax Error if AssignmentTargetType of [the production] is not
40425// > simple.
40426//
40427// It is also appropriate for checking if an identifier is valid and not
40428// defined elsewhere, like import declarations or function/class identifiers.
40429//
40430// Examples where this is used include:
40431// a += …;
40432// import a from '…';
40433// where a is the node to be checked.
40434//
40435// - checkLValPattern() shall be used if the syntactic construct supports
40436// anything checkLValSimple() supports, as well as object and array
40437// destructuring patterns. This is generally appropriate for constructs for
40438// which the spec says
40439//
40440// > It is a Syntax Error if [the production] is neither an ObjectLiteral nor
40441// > an ArrayLiteral and AssignmentTargetType of [the production] is not
40442// > simple.
40443//
40444// Examples where this is used include:
40445// (a = …);
40446// const a = …;
40447// try { … } catch (a) { … }
40448// where a is the node to be checked.
40449//
40450// - checkLValInnerPattern() shall be used if the syntactic construct supports
40451// anything checkLValPattern() supports, as well as default assignment
40452// patterns, rest elements, and other constructs that may appear within an
40453// object or array destructuring pattern.
40454//
40455// As a special case, function parameters also use checkLValInnerPattern(),
40456// as they also support defaults and rest constructs.
40457//
40458// These functions deliberately support both assignment and binding constructs,
40459// as the logic for both is exceedingly similar. If the node is the target of
40460// an assignment, then bindingType should be set to BIND_NONE. Otherwise, it
40461// should be set to the appropriate BIND_* constant, like BIND_VAR or
40462// BIND_LEXICAL.
40463//
40464// If the function is called with a non-BIND_NONE bindingType, then
40465// additionally a checkClashes object may be specified to allow checking for
40466// duplicate argument names. checkClashes is ignored if the provided construct
40467// is an assignment (i.e., bindingType is BIND_NONE).
40468
40469pp$2.checkLValSimple = function(expr, bindingType, checkClashes) {
40470 if ( bindingType === void 0 ) bindingType = BIND_NONE;
40471
40472 var isBind = bindingType !== BIND_NONE;
40473
40474 switch (expr.type) {
40475 case "Identifier":
40476 if (this.strict && this.reservedWordsStrictBind.test(expr.name))
40477 { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
40478 if (isBind) {
40479 if (bindingType === BIND_LEXICAL && expr.name === "let")
40480 { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
40481 if (checkClashes) {
40482 if (has(checkClashes, expr.name))
40483 { this.raiseRecoverable(expr.start, "Argument name clash"); }
40484 checkClashes[expr.name] = true;
40485 }
40486 if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }
40487 }
40488 break
40489
40490 case "ChainExpression":
40491 this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
40492 break
40493
40494 case "MemberExpression":
40495 if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); }
40496 break
40497
40498 case "ParenthesizedExpression":
40499 if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); }
40500 return this.checkLValSimple(expr.expression, bindingType, checkClashes)
40501
40502 default:
40503 this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
40504 }
40505};
40506
40507pp$2.checkLValPattern = function(expr, bindingType, checkClashes) {
40508 if ( bindingType === void 0 ) bindingType = BIND_NONE;
40509
40510 switch (expr.type) {
40511 case "ObjectPattern":
40512 for (var i = 0, list = expr.properties; i < list.length; i += 1) {
40513 var prop = list[i];
40514
40515 this.checkLValInnerPattern(prop, bindingType, checkClashes);
40516 }
40517 break
40518
40519 case "ArrayPattern":
40520 for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
40521 var elem = list$1[i$1];
40522
40523 if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); }
40524 }
40525 break
40526
40527 default:
40528 this.checkLValSimple(expr, bindingType, checkClashes);
40529 }
40530};
40531
40532pp$2.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
40533 if ( bindingType === void 0 ) bindingType = BIND_NONE;
40534
40535 switch (expr.type) {
40536 case "Property":
40537 // AssignmentProperty has type === "Property"
40538 this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
40539 break
40540
40541 case "AssignmentPattern":
40542 this.checkLValPattern(expr.left, bindingType, checkClashes);
40543 break
40544
40545 case "RestElement":
40546 this.checkLValPattern(expr.argument, bindingType, checkClashes);
40547 break
40548
40549 default:
40550 this.checkLValPattern(expr, bindingType, checkClashes);
40551 }
40552};
40553
40554// A recursive descent parser operates by defining functions for all
40555
40556var pp$3 = Parser.prototype;
40557
40558// Check if property name clashes with already added.
40559// Object/class getters and setters are not allowed to clash —
40560// either with each other or with an init property — and in
40561// strict mode, init properties are also not allowed to be repeated.
40562
40563pp$3.checkPropClash = function(prop, propHash, refDestructuringErrors) {
40564 if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
40565 { return }
40566 if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
40567 { return }
40568 var key = prop.key;
40569 var name;
40570 switch (key.type) {
40571 case "Identifier": name = key.name; break
40572 case "Literal": name = String(key.value); break
40573 default: return
40574 }
40575 var kind = prop.kind;
40576 if (this.options.ecmaVersion >= 6) {
40577 if (name === "__proto__" && kind === "init") {
40578 if (propHash.proto) {
40579 if (refDestructuringErrors) {
40580 if (refDestructuringErrors.doubleProto < 0)
40581 { refDestructuringErrors.doubleProto = key.start; }
40582 // Backwards-compat kludge. Can be removed in version 6.0
40583 } else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); }
40584 }
40585 propHash.proto = true;
40586 }
40587 return
40588 }
40589 name = "$" + name;
40590 var other = propHash[name];
40591 if (other) {
40592 var redefinition;
40593 if (kind === "init") {
40594 redefinition = this.strict && other.init || other.get || other.set;
40595 } else {
40596 redefinition = other.init || other[kind];
40597 }
40598 if (redefinition)
40599 { this.raiseRecoverable(key.start, "Redefinition of property"); }
40600 } else {
40601 other = propHash[name] = {
40602 init: false,
40603 get: false,
40604 set: false
40605 };
40606 }
40607 other[kind] = true;
40608};
40609
40610// ### Expression parsing
40611
40612// These nest, from the most general expression type at the top to
40613// 'atomic', nondivisible expression types at the bottom. Most of
40614// the functions will simply let the function(s) below them parse,
40615// and, *if* the syntactic construct they handle is present, wrap
40616// the AST node that the inner parser gave them in another node.
40617
40618// Parse a full expression. The optional arguments are used to
40619// forbid the `in` operator (in for loops initalization expressions)
40620// and provide reference for storing '=' operator inside shorthand
40621// property assignment in contexts where both object expression
40622// and object pattern might appear (so it's possible to raise
40623// delayed syntax error at correct position).
40624
40625pp$3.parseExpression = function(forInit, refDestructuringErrors) {
40626 var startPos = this.start, startLoc = this.startLoc;
40627 var expr = this.parseMaybeAssign(forInit, refDestructuringErrors);
40628 if (this.type === types.comma) {
40629 var node = this.startNodeAt(startPos, startLoc);
40630 node.expressions = [expr];
40631 while (this.eat(types.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); }
40632 return this.finishNode(node, "SequenceExpression")
40633 }
40634 return expr
40635};
40636
40637// Parse an assignment expression. This includes applications of
40638// operators like `+=`.
40639
40640pp$3.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {
40641 if (this.isContextual("yield")) {
40642 if (this.inGenerator) { return this.parseYield(forInit) }
40643 // The tokenizer will assume an expression is allowed after
40644 // `yield`, but this isn't that kind of yield
40645 else { this.exprAllowed = false; }
40646 }
40647
40648 var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1;
40649 if (refDestructuringErrors) {
40650 oldParenAssign = refDestructuringErrors.parenthesizedAssign;
40651 oldTrailingComma = refDestructuringErrors.trailingComma;
40652 refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
40653 } else {
40654 refDestructuringErrors = new DestructuringErrors;
40655 ownDestructuringErrors = true;
40656 }
40657
40658 var startPos = this.start, startLoc = this.startLoc;
40659 if (this.type === types.parenL || this.type === types.name) {
40660 this.potentialArrowAt = this.start;
40661 this.potentialArrowInForAwait = forInit === "await";
40662 }
40663 var left = this.parseMaybeConditional(forInit, refDestructuringErrors);
40664 if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
40665 if (this.type.isAssign) {
40666 var node = this.startNodeAt(startPos, startLoc);
40667 node.operator = this.value;
40668 if (this.type === types.eq)
40669 { left = this.toAssignable(left, false, refDestructuringErrors); }
40670 if (!ownDestructuringErrors) {
40671 refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
40672 }
40673 if (refDestructuringErrors.shorthandAssign >= left.start)
40674 { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly
40675 if (this.type === types.eq)
40676 { this.checkLValPattern(left); }
40677 else
40678 { this.checkLValSimple(left); }
40679 node.left = left;
40680 this.next();
40681 node.right = this.parseMaybeAssign(forInit);
40682 return this.finishNode(node, "AssignmentExpression")
40683 } else {
40684 if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
40685 }
40686 if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
40687 if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
40688 return left
40689};
40690
40691// Parse a ternary conditional (`?:`) operator.
40692
40693pp$3.parseMaybeConditional = function(forInit, refDestructuringErrors) {
40694 var startPos = this.start, startLoc = this.startLoc;
40695 var expr = this.parseExprOps(forInit, refDestructuringErrors);
40696 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
40697 if (this.eat(types.question)) {
40698 var node = this.startNodeAt(startPos, startLoc);
40699 node.test = expr;
40700 node.consequent = this.parseMaybeAssign();
40701 this.expect(types.colon);
40702 node.alternate = this.parseMaybeAssign(forInit);
40703 return this.finishNode(node, "ConditionalExpression")
40704 }
40705 return expr
40706};
40707
40708// Start the precedence parser.
40709
40710pp$3.parseExprOps = function(forInit, refDestructuringErrors) {
40711 var startPos = this.start, startLoc = this.startLoc;
40712 var expr = this.parseMaybeUnary(refDestructuringErrors, false);
40713 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
40714 return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit)
40715};
40716
40717// Parse binary operators with the operator precedence parsing
40718// algorithm. `left` is the left-hand side of the operator.
40719// `minPrec` provides context that allows the function to stop and
40720// defer further parser to one of its callers when it encounters an
40721// operator that has a lower precedence than the set it is parsing.
40722
40723pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {
40724 var prec = this.type.binop;
40725 if (prec != null && (!forInit || this.type !== types._in)) {
40726 if (prec > minPrec) {
40727 var logical = this.type === types.logicalOR || this.type === types.logicalAND;
40728 var coalesce = this.type === types.coalesce;
40729 if (coalesce) {
40730 // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
40731 // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
40732 prec = types.logicalAND.binop;
40733 }
40734 var op = this.value;
40735 this.next();
40736 var startPos = this.start, startLoc = this.startLoc;
40737 var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, forInit);
40738 var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
40739 if ((logical && this.type === types.coalesce) || (coalesce && (this.type === types.logicalOR || this.type === types.logicalAND))) {
40740 this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
40741 }
40742 return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit)
40743 }
40744 }
40745 return left
40746};
40747
40748pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) {
40749 var node = this.startNodeAt(startPos, startLoc);
40750 node.left = left;
40751 node.operator = op;
40752 node.right = right;
40753 return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
40754};
40755
40756// Parse unary operators, both prefix and postfix.
40757
40758pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec) {
40759 var startPos = this.start, startLoc = this.startLoc, expr;
40760 if (this.isContextual("await") && this.canAwait) {
40761 expr = this.parseAwait();
40762 sawUnary = true;
40763 } else if (this.type.prefix) {
40764 var node = this.startNode(), update = this.type === types.incDec;
40765 node.operator = this.value;
40766 node.prefix = true;
40767 this.next();
40768 node.argument = this.parseMaybeUnary(null, true, update);
40769 this.checkExpressionErrors(refDestructuringErrors, true);
40770 if (update) { this.checkLValSimple(node.argument); }
40771 else if (this.strict && node.operator === "delete" &&
40772 node.argument.type === "Identifier")
40773 { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
40774 else if (node.operator === "delete" && isPrivateFieldAccess(node.argument))
40775 { this.raiseRecoverable(node.start, "Private fields can not be deleted"); }
40776 else { sawUnary = true; }
40777 expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
40778 } else {
40779 expr = this.parseExprSubscripts(refDestructuringErrors);
40780 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
40781 while (this.type.postfix && !this.canInsertSemicolon()) {
40782 var node$1 = this.startNodeAt(startPos, startLoc);
40783 node$1.operator = this.value;
40784 node$1.prefix = false;
40785 node$1.argument = expr;
40786 this.checkLValSimple(expr);
40787 this.next();
40788 expr = this.finishNode(node$1, "UpdateExpression");
40789 }
40790 }
40791
40792 if (!incDec && this.eat(types.starstar)) {
40793 if (sawUnary)
40794 { this.unexpected(this.lastTokStart); }
40795 else
40796 { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) }
40797 } else {
40798 return expr
40799 }
40800};
40801
40802function isPrivateFieldAccess(node) {
40803 return (
40804 node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" ||
40805 node.type === "ChainExpression" && isPrivateFieldAccess(node.expression)
40806 )
40807}
40808
40809// Parse call, dot, and `[]`-subscript expressions.
40810
40811pp$3.parseExprSubscripts = function(refDestructuringErrors) {
40812 var startPos = this.start, startLoc = this.startLoc;
40813 var expr = this.parseExprAtom(refDestructuringErrors);
40814 if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")
40815 { return expr }
40816 var result = this.parseSubscripts(expr, startPos, startLoc);
40817 if (refDestructuringErrors && result.type === "MemberExpression") {
40818 if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
40819 if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
40820 if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; }
40821 }
40822 return result
40823};
40824
40825pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) {
40826 var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
40827 this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&
40828 this.potentialArrowAt === base.start;
40829 var optionalChained = false;
40830
40831 while (true) {
40832 var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained);
40833
40834 if (element.optional) { optionalChained = true; }
40835 if (element === base || element.type === "ArrowFunctionExpression") {
40836 if (optionalChained) {
40837 var chainNode = this.startNodeAt(startPos, startLoc);
40838 chainNode.expression = element;
40839 element = this.finishNode(chainNode, "ChainExpression");
40840 }
40841 return element
40842 }
40843
40844 base = element;
40845 }
40846};
40847
40848pp$3.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained) {
40849 var optionalSupported = this.options.ecmaVersion >= 11;
40850 var optional = optionalSupported && this.eat(types.questionDot);
40851 if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }
40852
40853 var computed = this.eat(types.bracketL);
40854 if (computed || (optional && this.type !== types.parenL && this.type !== types.backQuote) || this.eat(types.dot)) {
40855 var node = this.startNodeAt(startPos, startLoc);
40856 node.object = base;
40857 if (computed) {
40858 node.property = this.parseExpression();
40859 this.expect(types.bracketR);
40860 } else if (this.type === types.privateId && base.type !== "Super") {
40861 node.property = this.parsePrivateIdent();
40862 } else {
40863 node.property = this.parseIdent(this.options.allowReserved !== "never");
40864 }
40865 node.computed = !!computed;
40866 if (optionalSupported) {
40867 node.optional = optional;
40868 }
40869 base = this.finishNode(node, "MemberExpression");
40870 } else if (!noCalls && this.eat(types.parenL)) {
40871 var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
40872 this.yieldPos = 0;
40873 this.awaitPos = 0;
40874 this.awaitIdentPos = 0;
40875 var exprList = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
40876 if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types.arrow)) {
40877 this.checkPatternErrors(refDestructuringErrors, false);
40878 this.checkYieldAwaitInDefaultParams();
40879 if (this.awaitIdentPos > 0)
40880 { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
40881 this.yieldPos = oldYieldPos;
40882 this.awaitPos = oldAwaitPos;
40883 this.awaitIdentPos = oldAwaitIdentPos;
40884 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true)
40885 }
40886 this.checkExpressionErrors(refDestructuringErrors, true);
40887 this.yieldPos = oldYieldPos || this.yieldPos;
40888 this.awaitPos = oldAwaitPos || this.awaitPos;
40889 this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
40890 var node$1 = this.startNodeAt(startPos, startLoc);
40891 node$1.callee = base;
40892 node$1.arguments = exprList;
40893 if (optionalSupported) {
40894 node$1.optional = optional;
40895 }
40896 base = this.finishNode(node$1, "CallExpression");
40897 } else if (this.type === types.backQuote) {
40898 if (optional || optionalChained) {
40899 this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
40900 }
40901 var node$2 = this.startNodeAt(startPos, startLoc);
40902 node$2.tag = base;
40903 node$2.quasi = this.parseTemplate({isTagged: true});
40904 base = this.finishNode(node$2, "TaggedTemplateExpression");
40905 }
40906 return base
40907};
40908
40909// Parse an atomic expression — either a single token that is an
40910// expression, an expression started by a keyword like `function` or
40911// `new`, or an expression wrapped in punctuation like `()`, `[]`,
40912// or `{}`.
40913
40914pp$3.parseExprAtom = function(refDestructuringErrors) {
40915 // If a division operator appears in an expression position, the
40916 // tokenizer got confused, and we force it to read a regexp instead.
40917 if (this.type === types.slash) { this.readRegexp(); }
40918
40919 var node, canBeArrow = this.potentialArrowAt === this.start;
40920 switch (this.type) {
40921 case types._super:
40922 if (!this.allowSuper)
40923 { this.raise(this.start, "'super' keyword outside a method"); }
40924 node = this.startNode();
40925 this.next();
40926 if (this.type === types.parenL && !this.allowDirectSuper)
40927 { this.raise(node.start, "super() call outside constructor of a subclass"); }
40928 // The `super` keyword can appear at below:
40929 // SuperProperty:
40930 // super [ Expression ]
40931 // super . IdentifierName
40932 // SuperCall:
40933 // super ( Arguments )
40934 if (this.type !== types.dot && this.type !== types.bracketL && this.type !== types.parenL)
40935 { this.unexpected(); }
40936 return this.finishNode(node, "Super")
40937
40938 case types._this:
40939 node = this.startNode();
40940 this.next();
40941 return this.finishNode(node, "ThisExpression")
40942
40943 case types.name:
40944 var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
40945 var id = this.parseIdent(false);
40946 if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types._function))
40947 { return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true) }
40948 if (canBeArrow && !this.canInsertSemicolon()) {
40949 if (this.eat(types.arrow))
40950 { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) }
40951 if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types.name && !containsEsc &&
40952 (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {
40953 id = this.parseIdent(false);
40954 if (this.canInsertSemicolon() || !this.eat(types.arrow))
40955 { this.unexpected(); }
40956 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true)
40957 }
40958 }
40959 return id
40960
40961 case types.regexp:
40962 var value = this.value;
40963 node = this.parseLiteral(value.value);
40964 node.regex = {pattern: value.pattern, flags: value.flags};
40965 return node
40966
40967 case types.num: case types.string:
40968 return this.parseLiteral(this.value)
40969
40970 case types._null: case types._true: case types._false:
40971 node = this.startNode();
40972 node.value = this.type === types._null ? null : this.type === types._true;
40973 node.raw = this.type.keyword;
40974 this.next();
40975 return this.finishNode(node, "Literal")
40976
40977 case types.parenL:
40978 var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow);
40979 if (refDestructuringErrors) {
40980 if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
40981 { refDestructuringErrors.parenthesizedAssign = start; }
40982 if (refDestructuringErrors.parenthesizedBind < 0)
40983 { refDestructuringErrors.parenthesizedBind = start; }
40984 }
40985 return expr
40986
40987 case types.bracketL:
40988 node = this.startNode();
40989 this.next();
40990 node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors);
40991 return this.finishNode(node, "ArrayExpression")
40992
40993 case types.braceL:
40994 return this.parseObj(false, refDestructuringErrors)
40995
40996 case types._function:
40997 node = this.startNode();
40998 this.next();
40999 return this.parseFunction(node, 0)
41000
41001 case types._class:
41002 return this.parseClass(this.startNode(), false)
41003
41004 case types._new:
41005 return this.parseNew()
41006
41007 case types.backQuote:
41008 return this.parseTemplate()
41009
41010 case types._import:
41011 if (this.options.ecmaVersion >= 11) {
41012 return this.parseExprImport()
41013 } else {
41014 return this.unexpected()
41015 }
41016
41017 default:
41018 this.unexpected();
41019 }
41020};
41021
41022pp$3.parseExprImport = function() {
41023 var node = this.startNode();
41024
41025 // Consume `import` as an identifier for `import.meta`.
41026 // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.
41027 if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); }
41028 var meta = this.parseIdent(true);
41029
41030 switch (this.type) {
41031 case types.parenL:
41032 return this.parseDynamicImport(node)
41033 case types.dot:
41034 node.meta = meta;
41035 return this.parseImportMeta(node)
41036 default:
41037 this.unexpected();
41038 }
41039};
41040
41041pp$3.parseDynamicImport = function(node) {
41042 this.next(); // skip `(`
41043
41044 // Parse node.source.
41045 node.source = this.parseMaybeAssign();
41046
41047 // Verify ending.
41048 if (!this.eat(types.parenR)) {
41049 var errorPos = this.start;
41050 if (this.eat(types.comma) && this.eat(types.parenR)) {
41051 this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
41052 } else {
41053 this.unexpected(errorPos);
41054 }
41055 }
41056
41057 return this.finishNode(node, "ImportExpression")
41058};
41059
41060pp$3.parseImportMeta = function(node) {
41061 this.next(); // skip `.`
41062
41063 var containsEsc = this.containsEsc;
41064 node.property = this.parseIdent(true);
41065
41066 if (node.property.name !== "meta")
41067 { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); }
41068 if (containsEsc)
41069 { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); }
41070 if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere)
41071 { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); }
41072
41073 return this.finishNode(node, "MetaProperty")
41074};
41075
41076pp$3.parseLiteral = function(value) {
41077 var node = this.startNode();
41078 node.value = value;
41079 node.raw = this.input.slice(this.start, this.end);
41080 if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); }
41081 this.next();
41082 return this.finishNode(node, "Literal")
41083};
41084
41085pp$3.parseParenExpression = function() {
41086 this.expect(types.parenL);
41087 var val = this.parseExpression();
41088 this.expect(types.parenR);
41089 return val
41090};
41091
41092pp$3.parseParenAndDistinguishExpression = function(canBeArrow) {
41093 var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
41094 if (this.options.ecmaVersion >= 6) {
41095 this.next();
41096
41097 var innerStartPos = this.start, innerStartLoc = this.startLoc;
41098 var exprList = [], first = true, lastIsComma = false;
41099 var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
41100 this.yieldPos = 0;
41101 this.awaitPos = 0;
41102 // Do not save awaitIdentPos to allow checking awaits nested in parameters
41103 while (this.type !== types.parenR) {
41104 first ? first = false : this.expect(types.comma);
41105 if (allowTrailingComma && this.afterTrailingComma(types.parenR, true)) {
41106 lastIsComma = true;
41107 break
41108 } else if (this.type === types.ellipsis) {
41109 spreadStart = this.start;
41110 exprList.push(this.parseParenItem(this.parseRestBinding()));
41111 if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
41112 break
41113 } else {
41114 exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
41115 }
41116 }
41117 var innerEndPos = this.start, innerEndLoc = this.startLoc;
41118 this.expect(types.parenR);
41119
41120 if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) {
41121 this.checkPatternErrors(refDestructuringErrors, false);
41122 this.checkYieldAwaitInDefaultParams();
41123 this.yieldPos = oldYieldPos;
41124 this.awaitPos = oldAwaitPos;
41125 return this.parseParenArrowList(startPos, startLoc, exprList)
41126 }
41127
41128 if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
41129 if (spreadStart) { this.unexpected(spreadStart); }
41130 this.checkExpressionErrors(refDestructuringErrors, true);
41131 this.yieldPos = oldYieldPos || this.yieldPos;
41132 this.awaitPos = oldAwaitPos || this.awaitPos;
41133
41134 if (exprList.length > 1) {
41135 val = this.startNodeAt(innerStartPos, innerStartLoc);
41136 val.expressions = exprList;
41137 this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
41138 } else {
41139 val = exprList[0];
41140 }
41141 } else {
41142 val = this.parseParenExpression();
41143 }
41144
41145 if (this.options.preserveParens) {
41146 var par = this.startNodeAt(startPos, startLoc);
41147 par.expression = val;
41148 return this.finishNode(par, "ParenthesizedExpression")
41149 } else {
41150 return val
41151 }
41152};
41153
41154pp$3.parseParenItem = function(item) {
41155 return item
41156};
41157
41158pp$3.parseParenArrowList = function(startPos, startLoc, exprList) {
41159 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList)
41160};
41161
41162// New's precedence is slightly tricky. It must allow its argument to
41163// be a `[]` or dot subscript expression, but not a call — at least,
41164// not without wrapping it in parentheses. Thus, it uses the noCalls
41165// argument to parseSubscripts to prevent it from consuming the
41166// argument list.
41167
41168var empty$1 = [];
41169
41170pp$3.parseNew = function() {
41171 if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); }
41172 var node = this.startNode();
41173 var meta = this.parseIdent(true);
41174 if (this.options.ecmaVersion >= 6 && this.eat(types.dot)) {
41175 node.meta = meta;
41176 var containsEsc = this.containsEsc;
41177 node.property = this.parseIdent(true);
41178 if (node.property.name !== "target")
41179 { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); }
41180 if (containsEsc)
41181 { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); }
41182 if (!this.inNonArrowFunction)
41183 { this.raiseRecoverable(node.start, "'new.target' can only be used in functions"); }
41184 return this.finishNode(node, "MetaProperty")
41185 }
41186 var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types._import;
41187 node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
41188 if (isImport && node.callee.type === "ImportExpression") {
41189 this.raise(startPos, "Cannot use new with import()");
41190 }
41191 if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false); }
41192 else { node.arguments = empty$1; }
41193 return this.finishNode(node, "NewExpression")
41194};
41195
41196// Parse template expression.
41197
41198pp$3.parseTemplateElement = function(ref) {
41199 var isTagged = ref.isTagged;
41200
41201 var elem = this.startNode();
41202 if (this.type === types.invalidTemplate) {
41203 if (!isTagged) {
41204 this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
41205 }
41206 elem.value = {
41207 raw: this.value,
41208 cooked: null
41209 };
41210 } else {
41211 elem.value = {
41212 raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
41213 cooked: this.value
41214 };
41215 }
41216 this.next();
41217 elem.tail = this.type === types.backQuote;
41218 return this.finishNode(elem, "TemplateElement")
41219};
41220
41221pp$3.parseTemplate = function(ref) {
41222 if ( ref === void 0 ) ref = {};
41223 var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
41224
41225 var node = this.startNode();
41226 this.next();
41227 node.expressions = [];
41228 var curElt = this.parseTemplateElement({isTagged: isTagged});
41229 node.quasis = [curElt];
41230 while (!curElt.tail) {
41231 if (this.type === types.eof) { this.raise(this.pos, "Unterminated template literal"); }
41232 this.expect(types.dollarBraceL);
41233 node.expressions.push(this.parseExpression());
41234 this.expect(types.braceR);
41235 node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
41236 }
41237 this.next();
41238 return this.finishNode(node, "TemplateLiteral")
41239};
41240
41241pp$3.isAsyncProp = function(prop) {
41242 return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
41243 (this.type === types.name || this.type === types.num || this.type === types.string || this.type === types.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types.star)) &&
41244 !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
41245};
41246
41247// Parse an object literal or binding pattern.
41248
41249pp$3.parseObj = function(isPattern, refDestructuringErrors) {
41250 var node = this.startNode(), first = true, propHash = {};
41251 node.properties = [];
41252 this.next();
41253 while (!this.eat(types.braceR)) {
41254 if (!first) {
41255 this.expect(types.comma);
41256 if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types.braceR)) { break }
41257 } else { first = false; }
41258
41259 var prop = this.parseProperty(isPattern, refDestructuringErrors);
41260 if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
41261 node.properties.push(prop);
41262 }
41263 return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
41264};
41265
41266pp$3.parseProperty = function(isPattern, refDestructuringErrors) {
41267 var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
41268 if (this.options.ecmaVersion >= 9 && this.eat(types.ellipsis)) {
41269 if (isPattern) {
41270 prop.argument = this.parseIdent(false);
41271 if (this.type === types.comma) {
41272 this.raise(this.start, "Comma is not permitted after the rest element");
41273 }
41274 return this.finishNode(prop, "RestElement")
41275 }
41276 // To disallow parenthesized identifier via `this.toAssignable()`.
41277 if (this.type === types.parenL && refDestructuringErrors) {
41278 if (refDestructuringErrors.parenthesizedAssign < 0) {
41279 refDestructuringErrors.parenthesizedAssign = this.start;
41280 }
41281 if (refDestructuringErrors.parenthesizedBind < 0) {
41282 refDestructuringErrors.parenthesizedBind = this.start;
41283 }
41284 }
41285 // Parse argument.
41286 prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
41287 // To disallow trailing comma via `this.toAssignable()`.
41288 if (this.type === types.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
41289 refDestructuringErrors.trailingComma = this.start;
41290 }
41291 // Finish
41292 return this.finishNode(prop, "SpreadElement")
41293 }
41294 if (this.options.ecmaVersion >= 6) {
41295 prop.method = false;
41296 prop.shorthand = false;
41297 if (isPattern || refDestructuringErrors) {
41298 startPos = this.start;
41299 startLoc = this.startLoc;
41300 }
41301 if (!isPattern)
41302 { isGenerator = this.eat(types.star); }
41303 }
41304 var containsEsc = this.containsEsc;
41305 this.parsePropertyName(prop);
41306 if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
41307 isAsync = true;
41308 isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star);
41309 this.parsePropertyName(prop, refDestructuringErrors);
41310 } else {
41311 isAsync = false;
41312 }
41313 this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
41314 return this.finishNode(prop, "Property")
41315};
41316
41317pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
41318 if ((isGenerator || isAsync) && this.type === types.colon)
41319 { this.unexpected(); }
41320
41321 if (this.eat(types.colon)) {
41322 prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
41323 prop.kind = "init";
41324 } else if (this.options.ecmaVersion >= 6 && this.type === types.parenL) {
41325 if (isPattern) { this.unexpected(); }
41326 prop.kind = "init";
41327 prop.method = true;
41328 prop.value = this.parseMethod(isGenerator, isAsync);
41329 } else if (!isPattern && !containsEsc &&
41330 this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
41331 (prop.key.name === "get" || prop.key.name === "set") &&
41332 (this.type !== types.comma && this.type !== types.braceR && this.type !== types.eq)) {
41333 if (isGenerator || isAsync) { this.unexpected(); }
41334 prop.kind = prop.key.name;
41335 this.parsePropertyName(prop);
41336 prop.value = this.parseMethod(false);
41337 var paramCount = prop.kind === "get" ? 0 : 1;
41338 if (prop.value.params.length !== paramCount) {
41339 var start = prop.value.start;
41340 if (prop.kind === "get")
41341 { this.raiseRecoverable(start, "getter should have no params"); }
41342 else
41343 { this.raiseRecoverable(start, "setter should have exactly one param"); }
41344 } else {
41345 if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
41346 { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
41347 }
41348 } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
41349 if (isGenerator || isAsync) { this.unexpected(); }
41350 this.checkUnreserved(prop.key);
41351 if (prop.key.name === "await" && !this.awaitIdentPos)
41352 { this.awaitIdentPos = startPos; }
41353 prop.kind = "init";
41354 if (isPattern) {
41355 prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
41356 } else if (this.type === types.eq && refDestructuringErrors) {
41357 if (refDestructuringErrors.shorthandAssign < 0)
41358 { refDestructuringErrors.shorthandAssign = this.start; }
41359 prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
41360 } else {
41361 prop.value = this.copyNode(prop.key);
41362 }
41363 prop.shorthand = true;
41364 } else { this.unexpected(); }
41365};
41366
41367pp$3.parsePropertyName = function(prop) {
41368 if (this.options.ecmaVersion >= 6) {
41369 if (this.eat(types.bracketL)) {
41370 prop.computed = true;
41371 prop.key = this.parseMaybeAssign();
41372 this.expect(types.bracketR);
41373 return prop.key
41374 } else {
41375 prop.computed = false;
41376 }
41377 }
41378 return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
41379};
41380
41381// Initialize empty function node.
41382
41383pp$3.initFunction = function(node) {
41384 node.id = null;
41385 if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }
41386 if (this.options.ecmaVersion >= 8) { node.async = false; }
41387};
41388
41389// Parse object or class method.
41390
41391pp$3.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
41392 var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
41393
41394 this.initFunction(node);
41395 if (this.options.ecmaVersion >= 6)
41396 { node.generator = isGenerator; }
41397 if (this.options.ecmaVersion >= 8)
41398 { node.async = !!isAsync; }
41399
41400 this.yieldPos = 0;
41401 this.awaitPos = 0;
41402 this.awaitIdentPos = 0;
41403 this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
41404
41405 this.expect(types.parenL);
41406 node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
41407 this.checkYieldAwaitInDefaultParams();
41408 this.parseFunctionBody(node, false, true);
41409
41410 this.yieldPos = oldYieldPos;
41411 this.awaitPos = oldAwaitPos;
41412 this.awaitIdentPos = oldAwaitIdentPos;
41413 return this.finishNode(node, "FunctionExpression")
41414};
41415
41416// Parse arrow function expression with given parameters.
41417
41418pp$3.parseArrowExpression = function(node, params, isAsync) {
41419 var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
41420
41421 this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
41422 this.initFunction(node);
41423 if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }
41424
41425 this.yieldPos = 0;
41426 this.awaitPos = 0;
41427 this.awaitIdentPos = 0;
41428
41429 node.params = this.toAssignableList(params, true);
41430 this.parseFunctionBody(node, true, false);
41431
41432 this.yieldPos = oldYieldPos;
41433 this.awaitPos = oldAwaitPos;
41434 this.awaitIdentPos = oldAwaitIdentPos;
41435 return this.finishNode(node, "ArrowFunctionExpression")
41436};
41437
41438// Parse function body and check parameters.
41439
41440pp$3.parseFunctionBody = function(node, isArrowFunction, isMethod) {
41441 var isExpression = isArrowFunction && this.type !== types.braceL;
41442 var oldStrict = this.strict, useStrict = false;
41443
41444 if (isExpression) {
41445 node.body = this.parseMaybeAssign();
41446 node.expression = true;
41447 this.checkParams(node, false);
41448 } else {
41449 var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
41450 if (!oldStrict || nonSimple) {
41451 useStrict = this.strictDirective(this.end);
41452 // If this is a strict mode function, verify that argument names
41453 // are not repeated, and it does not try to bind the words `eval`
41454 // or `arguments`.
41455 if (useStrict && nonSimple)
41456 { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
41457 }
41458 // Start a new scope with regard to labels and the `inFunction`
41459 // flag (restore them to their old value afterwards).
41460 var oldLabels = this.labels;
41461 this.labels = [];
41462 if (useStrict) { this.strict = true; }
41463
41464 // Add the params to varDeclaredNames to ensure that an error is thrown
41465 // if a let/const declaration in the function clashes with one of the params.
41466 this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
41467 // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
41468 if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); }
41469 node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
41470 node.expression = false;
41471 this.adaptDirectivePrologue(node.body.body);
41472 this.labels = oldLabels;
41473 }
41474 this.exitScope();
41475};
41476
41477pp$3.isSimpleParamList = function(params) {
41478 for (var i = 0, list = params; i < list.length; i += 1)
41479 {
41480 var param = list[i];
41481
41482 if (param.type !== "Identifier") { return false
41483 } }
41484 return true
41485};
41486
41487// Checks function params for various disallowed patterns such as using "eval"
41488// or "arguments" and duplicate parameters.
41489
41490pp$3.checkParams = function(node, allowDuplicates) {
41491 var nameHash = Object.create(null);
41492 for (var i = 0, list = node.params; i < list.length; i += 1)
41493 {
41494 var param = list[i];
41495
41496 this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);
41497 }
41498};
41499
41500// Parses a comma-separated list of expressions, and returns them as
41501// an array. `close` is the token type that ends the list, and
41502// `allowEmpty` can be turned on to allow subsequent commas with
41503// nothing in between them to be parsed as `null` (which is needed
41504// for array literals).
41505
41506pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
41507 var elts = [], first = true;
41508 while (!this.eat(close)) {
41509 if (!first) {
41510 this.expect(types.comma);
41511 if (allowTrailingComma && this.afterTrailingComma(close)) { break }
41512 } else { first = false; }
41513
41514 var elt = (void 0);
41515 if (allowEmpty && this.type === types.comma)
41516 { elt = null; }
41517 else if (this.type === types.ellipsis) {
41518 elt = this.parseSpread(refDestructuringErrors);
41519 if (refDestructuringErrors && this.type === types.comma && refDestructuringErrors.trailingComma < 0)
41520 { refDestructuringErrors.trailingComma = this.start; }
41521 } else {
41522 elt = this.parseMaybeAssign(false, refDestructuringErrors);
41523 }
41524 elts.push(elt);
41525 }
41526 return elts
41527};
41528
41529pp$3.checkUnreserved = function(ref) {
41530 var start = ref.start;
41531 var end = ref.end;
41532 var name = ref.name;
41533
41534 if (this.inGenerator && name === "yield")
41535 { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }
41536 if (this.inAsync && name === "await")
41537 { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }
41538 if (this.currentThisScope().inClassFieldInit && name === "arguments")
41539 { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); }
41540 if (this.keywords.test(name))
41541 { this.raise(start, ("Unexpected keyword '" + name + "'")); }
41542 if (this.options.ecmaVersion < 6 &&
41543 this.input.slice(start, end).indexOf("\\") !== -1) { return }
41544 var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
41545 if (re.test(name)) {
41546 if (!this.inAsync && name === "await")
41547 { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }
41548 this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
41549 }
41550};
41551
41552// Parse the next token as an identifier. If `liberal` is true (used
41553// when parsing properties), it will also convert keywords into
41554// identifiers.
41555
41556pp$3.parseIdent = function(liberal, isBinding) {
41557 var node = this.startNode();
41558 if (this.type === types.name) {
41559 node.name = this.value;
41560 } else if (this.type.keyword) {
41561 node.name = this.type.keyword;
41562
41563 // To fix https://github.com/acornjs/acorn/issues/575
41564 // `class` and `function` keywords push new context into this.context.
41565 // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
41566 // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
41567 if ((node.name === "class" || node.name === "function") &&
41568 (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
41569 this.context.pop();
41570 }
41571 } else {
41572 this.unexpected();
41573 }
41574 this.next(!!liberal);
41575 this.finishNode(node, "Identifier");
41576 if (!liberal) {
41577 this.checkUnreserved(node);
41578 if (node.name === "await" && !this.awaitIdentPos)
41579 { this.awaitIdentPos = node.start; }
41580 }
41581 return node
41582};
41583
41584pp$3.parsePrivateIdent = function() {
41585 var node = this.startNode();
41586 if (this.type === types.privateId) {
41587 node.name = this.value;
41588 } else {
41589 this.unexpected();
41590 }
41591 this.next();
41592 this.finishNode(node, "PrivateIdentifier");
41593
41594 // For validating existence
41595 if (this.privateNameStack.length === 0) {
41596 this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class"));
41597 } else {
41598 this.privateNameStack[this.privateNameStack.length - 1].used.push(node);
41599 }
41600
41601 return node
41602};
41603
41604// Parses yield expression inside generator.
41605
41606pp$3.parseYield = function(forInit) {
41607 if (!this.yieldPos) { this.yieldPos = this.start; }
41608
41609 var node = this.startNode();
41610 this.next();
41611 if (this.type === types.semi || this.canInsertSemicolon() || (this.type !== types.star && !this.type.startsExpr)) {
41612 node.delegate = false;
41613 node.argument = null;
41614 } else {
41615 node.delegate = this.eat(types.star);
41616 node.argument = this.parseMaybeAssign(forInit);
41617 }
41618 return this.finishNode(node, "YieldExpression")
41619};
41620
41621pp$3.parseAwait = function() {
41622 if (!this.awaitPos) { this.awaitPos = this.start; }
41623
41624 var node = this.startNode();
41625 this.next();
41626 node.argument = this.parseMaybeUnary(null, true);
41627 return this.finishNode(node, "AwaitExpression")
41628};
41629
41630var pp$4 = Parser.prototype;
41631
41632// This function is used to raise exceptions on parse errors. It
41633// takes an offset integer (into the current `input`) to indicate
41634// the location of the error, attaches the position to the end
41635// of the error message, and then raises a `SyntaxError` with that
41636// message.
41637
41638pp$4.raise = function(pos, message) {
41639 var loc = getLineInfo(this.input, pos);
41640 message += " (" + loc.line + ":" + loc.column + ")";
41641 var err = new SyntaxError(message);
41642 err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
41643 throw err
41644};
41645
41646pp$4.raiseRecoverable = pp$4.raise;
41647
41648pp$4.curPosition = function() {
41649 if (this.options.locations) {
41650 return new Position(this.curLine, this.pos - this.lineStart)
41651 }
41652};
41653
41654var pp$5 = Parser.prototype;
41655
41656var Scope = function Scope(flags) {
41657 this.flags = flags;
41658 // A list of var-declared names in the current lexical scope
41659 this.var = [];
41660 // A list of lexically-declared names in the current lexical scope
41661 this.lexical = [];
41662 // A list of lexically-declared FunctionDeclaration names in the current lexical scope
41663 this.functions = [];
41664 // A switch to disallow the identifier reference 'arguments'
41665 this.inClassFieldInit = false;
41666};
41667
41668// The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
41669
41670pp$5.enterScope = function(flags) {
41671 this.scopeStack.push(new Scope(flags));
41672};
41673
41674pp$5.exitScope = function() {
41675 this.scopeStack.pop();
41676};
41677
41678// The spec says:
41679// > At the top level of a function, or script, function declarations are
41680// > treated like var declarations rather than like lexical declarations.
41681pp$5.treatFunctionsAsVarInScope = function(scope) {
41682 return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)
41683};
41684
41685pp$5.declareName = function(name, bindingType, pos) {
41686 var redeclared = false;
41687 if (bindingType === BIND_LEXICAL) {
41688 var scope = this.currentScope();
41689 redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
41690 scope.lexical.push(name);
41691 if (this.inModule && (scope.flags & SCOPE_TOP))
41692 { delete this.undefinedExports[name]; }
41693 } else if (bindingType === BIND_SIMPLE_CATCH) {
41694 var scope$1 = this.currentScope();
41695 scope$1.lexical.push(name);
41696 } else if (bindingType === BIND_FUNCTION) {
41697 var scope$2 = this.currentScope();
41698 if (this.treatFunctionsAsVar)
41699 { redeclared = scope$2.lexical.indexOf(name) > -1; }
41700 else
41701 { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }
41702 scope$2.functions.push(name);
41703 } else {
41704 for (var i = this.scopeStack.length - 1; i >= 0; --i) {
41705 var scope$3 = this.scopeStack[i];
41706 if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||
41707 !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
41708 redeclared = true;
41709 break
41710 }
41711 scope$3.var.push(name);
41712 if (this.inModule && (scope$3.flags & SCOPE_TOP))
41713 { delete this.undefinedExports[name]; }
41714 if (scope$3.flags & SCOPE_VAR) { break }
41715 }
41716 }
41717 if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
41718};
41719
41720pp$5.checkLocalExport = function(id) {
41721 // scope.functions must be empty as Module code is always strict.
41722 if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
41723 this.scopeStack[0].var.indexOf(id.name) === -1) {
41724 this.undefinedExports[id.name] = id;
41725 }
41726};
41727
41728pp$5.currentScope = function() {
41729 return this.scopeStack[this.scopeStack.length - 1]
41730};
41731
41732pp$5.currentVarScope = function() {
41733 for (var i = this.scopeStack.length - 1;; i--) {
41734 var scope = this.scopeStack[i];
41735 if (scope.flags & SCOPE_VAR) { return scope }
41736 }
41737};
41738
41739// Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
41740pp$5.currentThisScope = function() {
41741 for (var i = this.scopeStack.length - 1;; i--) {
41742 var scope = this.scopeStack[i];
41743 if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }
41744 }
41745};
41746
41747var Node = function Node(parser, pos, loc) {
41748 this.type = "";
41749 this.start = pos;
41750 this.end = 0;
41751 if (parser.options.locations)
41752 { this.loc = new SourceLocation(parser, loc); }
41753 if (parser.options.directSourceFile)
41754 { this.sourceFile = parser.options.directSourceFile; }
41755 if (parser.options.ranges)
41756 { this.range = [pos, 0]; }
41757};
41758
41759// Start an AST node, attaching a start offset.
41760
41761var pp$6 = Parser.prototype;
41762
41763pp$6.startNode = function() {
41764 return new Node(this, this.start, this.startLoc)
41765};
41766
41767pp$6.startNodeAt = function(pos, loc) {
41768 return new Node(this, pos, loc)
41769};
41770
41771// Finish an AST node, adding `type` and `end` properties.
41772
41773function finishNodeAt(node, type, pos, loc) {
41774 node.type = type;
41775 node.end = pos;
41776 if (this.options.locations)
41777 { node.loc.end = loc; }
41778 if (this.options.ranges)
41779 { node.range[1] = pos; }
41780 return node
41781}
41782
41783pp$6.finishNode = function(node, type) {
41784 return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
41785};
41786
41787// Finish node at given position
41788
41789pp$6.finishNodeAt = function(node, type, pos, loc) {
41790 return finishNodeAt.call(this, node, type, pos, loc)
41791};
41792
41793pp$6.copyNode = function(node) {
41794 var newNode = new Node(this, node.start, this.startLoc);
41795 for (var prop in node) { newNode[prop] = node[prop]; }
41796 return newNode
41797};
41798
41799// The algorithm used to determine whether a regexp can appear at a
41800
41801var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
41802 this.token = token;
41803 this.isExpr = !!isExpr;
41804 this.preserveSpace = !!preserveSpace;
41805 this.override = override;
41806 this.generator = !!generator;
41807};
41808
41809var types$1 = {
41810 b_stat: new TokContext("{", false),
41811 b_expr: new TokContext("{", true),
41812 b_tmpl: new TokContext("${", false),
41813 p_stat: new TokContext("(", false),
41814 p_expr: new TokContext("(", true),
41815 q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
41816 f_stat: new TokContext("function", false),
41817 f_expr: new TokContext("function", true),
41818 f_expr_gen: new TokContext("function", true, false, null, true),
41819 f_gen: new TokContext("function", false, false, null, true)
41820};
41821
41822var pp$7 = Parser.prototype;
41823
41824pp$7.initialContext = function() {
41825 return [types$1.b_stat]
41826};
41827
41828pp$7.braceIsBlock = function(prevType) {
41829 var parent = this.curContext();
41830 if (parent === types$1.f_expr || parent === types$1.f_stat)
41831 { return true }
41832 if (prevType === types.colon && (parent === types$1.b_stat || parent === types$1.b_expr))
41833 { return !parent.isExpr }
41834
41835 // The check for `tt.name && exprAllowed` detects whether we are
41836 // after a `yield` or `of` construct. See the `updateContext` for
41837 // `tt.name`.
41838 if (prevType === types._return || prevType === types.name && this.exprAllowed)
41839 { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
41840 if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow)
41841 { return true }
41842 if (prevType === types.braceL)
41843 { return parent === types$1.b_stat }
41844 if (prevType === types._var || prevType === types._const || prevType === types.name)
41845 { return false }
41846 return !this.exprAllowed
41847};
41848
41849pp$7.inGeneratorContext = function() {
41850 for (var i = this.context.length - 1; i >= 1; i--) {
41851 var context = this.context[i];
41852 if (context.token === "function")
41853 { return context.generator }
41854 }
41855 return false
41856};
41857
41858pp$7.updateContext = function(prevType) {
41859 var update, type = this.type;
41860 if (type.keyword && prevType === types.dot)
41861 { this.exprAllowed = false; }
41862 else if (update = type.updateContext)
41863 { update.call(this, prevType); }
41864 else
41865 { this.exprAllowed = type.beforeExpr; }
41866};
41867
41868// Token-specific context update code
41869
41870types.parenR.updateContext = types.braceR.updateContext = function() {
41871 if (this.context.length === 1) {
41872 this.exprAllowed = true;
41873 return
41874 }
41875 var out = this.context.pop();
41876 if (out === types$1.b_stat && this.curContext().token === "function") {
41877 out = this.context.pop();
41878 }
41879 this.exprAllowed = !out.isExpr;
41880};
41881
41882types.braceL.updateContext = function(prevType) {
41883 this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr);
41884 this.exprAllowed = true;
41885};
41886
41887types.dollarBraceL.updateContext = function() {
41888 this.context.push(types$1.b_tmpl);
41889 this.exprAllowed = true;
41890};
41891
41892types.parenL.updateContext = function(prevType) {
41893 var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while;
41894 this.context.push(statementParens ? types$1.p_stat : types$1.p_expr);
41895 this.exprAllowed = true;
41896};
41897
41898types.incDec.updateContext = function() {
41899 // tokExprAllowed stays unchanged
41900};
41901
41902types._function.updateContext = types._class.updateContext = function(prevType) {
41903 if (prevType.beforeExpr && prevType !== types._else &&
41904 !(prevType === types.semi && this.curContext() !== types$1.p_stat) &&
41905 !(prevType === types._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
41906 !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat))
41907 { this.context.push(types$1.f_expr); }
41908 else
41909 { this.context.push(types$1.f_stat); }
41910 this.exprAllowed = false;
41911};
41912
41913types.backQuote.updateContext = function() {
41914 if (this.curContext() === types$1.q_tmpl)
41915 { this.context.pop(); }
41916 else
41917 { this.context.push(types$1.q_tmpl); }
41918 this.exprAllowed = false;
41919};
41920
41921types.star.updateContext = function(prevType) {
41922 if (prevType === types._function) {
41923 var index = this.context.length - 1;
41924 if (this.context[index] === types$1.f_expr)
41925 { this.context[index] = types$1.f_expr_gen; }
41926 else
41927 { this.context[index] = types$1.f_gen; }
41928 }
41929 this.exprAllowed = true;
41930};
41931
41932types.name.updateContext = function(prevType) {
41933 var allowed = false;
41934 if (this.options.ecmaVersion >= 6 && prevType !== types.dot) {
41935 if (this.value === "of" && !this.exprAllowed ||
41936 this.value === "yield" && this.inGeneratorContext())
41937 { allowed = true; }
41938 }
41939 this.exprAllowed = allowed;
41940};
41941
41942// This file contains Unicode properties extracted from the ECMAScript
41943// specification. The lists are extracted like so:
41944// $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)
41945
41946// #table-binary-unicode-properties
41947var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";
41948var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
41949var ecma11BinaryProperties = ecma10BinaryProperties;
41950var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
41951var unicodeBinaryProperties = {
41952 9: ecma9BinaryProperties,
41953 10: ecma10BinaryProperties,
41954 11: ecma11BinaryProperties,
41955 12: ecma12BinaryProperties
41956};
41957
41958// #table-unicode-general-category-values
41959var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";
41960
41961// #table-unicode-script-values
41962var ecma9ScriptValues = "Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";
41963var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
41964var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
41965var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
41966var unicodeScriptValues = {
41967 9: ecma9ScriptValues,
41968 10: ecma10ScriptValues,
41969 11: ecma11ScriptValues,
41970 12: ecma12ScriptValues
41971};
41972
41973var data = {};
41974function buildUnicodeData(ecmaVersion) {
41975 var d = data[ecmaVersion] = {
41976 binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
41977 nonBinary: {
41978 General_Category: wordsRegexp(unicodeGeneralCategoryValues),
41979 Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
41980 }
41981 };
41982 d.nonBinary.Script_Extensions = d.nonBinary.Script;
41983
41984 d.nonBinary.gc = d.nonBinary.General_Category;
41985 d.nonBinary.sc = d.nonBinary.Script;
41986 d.nonBinary.scx = d.nonBinary.Script_Extensions;
41987}
41988buildUnicodeData(9);
41989buildUnicodeData(10);
41990buildUnicodeData(11);
41991buildUnicodeData(12);
41992
41993var pp$8 = Parser.prototype;
41994
41995var RegExpValidationState = function RegExpValidationState(parser) {
41996 this.parser = parser;
41997 this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "");
41998 this.unicodeProperties = data[parser.options.ecmaVersion >= 12 ? 12 : parser.options.ecmaVersion];
41999 this.source = "";
42000 this.flags = "";
42001 this.start = 0;
42002 this.switchU = false;
42003 this.switchN = false;
42004 this.pos = 0;
42005 this.lastIntValue = 0;
42006 this.lastStringValue = "";
42007 this.lastAssertionIsQuantifiable = false;
42008 this.numCapturingParens = 0;
42009 this.maxBackReference = 0;
42010 this.groupNames = [];
42011 this.backReferenceNames = [];
42012};
42013
42014RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {
42015 var unicode = flags.indexOf("u") !== -1;
42016 this.start = start | 0;
42017 this.source = pattern + "";
42018 this.flags = flags;
42019 this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
42020 this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
42021};
42022
42023RegExpValidationState.prototype.raise = function raise (message) {
42024 this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));
42025};
42026
42027// If u flag is given, this returns the code point at the index (it combines a surrogate pair).
42028// Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).
42029RegExpValidationState.prototype.at = function at (i, forceU) {
42030 if ( forceU === void 0 ) forceU = false;
42031
42032 var s = this.source;
42033 var l = s.length;
42034 if (i >= l) {
42035 return -1
42036 }
42037 var c = s.charCodeAt(i);
42038 if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
42039 return c
42040 }
42041 var next = s.charCodeAt(i + 1);
42042 return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c
42043};
42044
42045RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {
42046 if ( forceU === void 0 ) forceU = false;
42047
42048 var s = this.source;
42049 var l = s.length;
42050 if (i >= l) {
42051 return l
42052 }
42053 var c = s.charCodeAt(i), next;
42054 if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||
42055 (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {
42056 return i + 1
42057 }
42058 return i + 2
42059};
42060
42061RegExpValidationState.prototype.current = function current (forceU) {
42062 if ( forceU === void 0 ) forceU = false;
42063
42064 return this.at(this.pos, forceU)
42065};
42066
42067RegExpValidationState.prototype.lookahead = function lookahead (forceU) {
42068 if ( forceU === void 0 ) forceU = false;
42069
42070 return this.at(this.nextIndex(this.pos, forceU), forceU)
42071};
42072
42073RegExpValidationState.prototype.advance = function advance (forceU) {
42074 if ( forceU === void 0 ) forceU = false;
42075
42076 this.pos = this.nextIndex(this.pos, forceU);
42077};
42078
42079RegExpValidationState.prototype.eat = function eat (ch, forceU) {
42080 if ( forceU === void 0 ) forceU = false;
42081
42082 if (this.current(forceU) === ch) {
42083 this.advance(forceU);
42084 return true
42085 }
42086 return false
42087};
42088
42089function codePointToString(ch) {
42090 if (ch <= 0xFFFF) { return String.fromCharCode(ch) }
42091 ch -= 0x10000;
42092 return String.fromCharCode((ch >> 10) + 0xD800, (ch & 0x03FF) + 0xDC00)
42093}
42094
42095/**
42096 * Validate the flags part of a given RegExpLiteral.
42097 *
42098 * @param {RegExpValidationState} state The state to validate RegExp.
42099 * @returns {void}
42100 */
42101pp$8.validateRegExpFlags = function(state) {
42102 var validFlags = state.validFlags;
42103 var flags = state.flags;
42104
42105 for (var i = 0; i < flags.length; i++) {
42106 var flag = flags.charAt(i);
42107 if (validFlags.indexOf(flag) === -1) {
42108 this.raise(state.start, "Invalid regular expression flag");
42109 }
42110 if (flags.indexOf(flag, i + 1) > -1) {
42111 this.raise(state.start, "Duplicate regular expression flag");
42112 }
42113 }
42114};
42115
42116/**
42117 * Validate the pattern part of a given RegExpLiteral.
42118 *
42119 * @param {RegExpValidationState} state The state to validate RegExp.
42120 * @returns {void}
42121 */
42122pp$8.validateRegExpPattern = function(state) {
42123 this.regexp_pattern(state);
42124
42125 // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
42126 // parsing contains a |GroupName|, reparse with the goal symbol
42127 // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
42128 // exception if _P_ did not conform to the grammar, if any elements of _P_
42129 // were not matched by the parse, or if any Early Error conditions exist.
42130 if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
42131 state.switchN = true;
42132 this.regexp_pattern(state);
42133 }
42134};
42135
42136// https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern
42137pp$8.regexp_pattern = function(state) {
42138 state.pos = 0;
42139 state.lastIntValue = 0;
42140 state.lastStringValue = "";
42141 state.lastAssertionIsQuantifiable = false;
42142 state.numCapturingParens = 0;
42143 state.maxBackReference = 0;
42144 state.groupNames.length = 0;
42145 state.backReferenceNames.length = 0;
42146
42147 this.regexp_disjunction(state);
42148
42149 if (state.pos !== state.source.length) {
42150 // Make the same messages as V8.
42151 if (state.eat(0x29 /* ) */)) {
42152 state.raise("Unmatched ')'");
42153 }
42154 if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {
42155 state.raise("Lone quantifier brackets");
42156 }
42157 }
42158 if (state.maxBackReference > state.numCapturingParens) {
42159 state.raise("Invalid escape");
42160 }
42161 for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
42162 var name = list[i];
42163
42164 if (state.groupNames.indexOf(name) === -1) {
42165 state.raise("Invalid named capture referenced");
42166 }
42167 }
42168};
42169
42170// https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction
42171pp$8.regexp_disjunction = function(state) {
42172 this.regexp_alternative(state);
42173 while (state.eat(0x7C /* | */)) {
42174 this.regexp_alternative(state);
42175 }
42176
42177 // Make the same message as V8.
42178 if (this.regexp_eatQuantifier(state, true)) {
42179 state.raise("Nothing to repeat");
42180 }
42181 if (state.eat(0x7B /* { */)) {
42182 state.raise("Lone quantifier brackets");
42183 }
42184};
42185
42186// https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative
42187pp$8.regexp_alternative = function(state) {
42188 while (state.pos < state.source.length && this.regexp_eatTerm(state))
42189 { }
42190};
42191
42192// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
42193pp$8.regexp_eatTerm = function(state) {
42194 if (this.regexp_eatAssertion(state)) {
42195 // Handle `QuantifiableAssertion Quantifier` alternative.
42196 // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
42197 // is a QuantifiableAssertion.
42198 if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
42199 // Make the same message as V8.
42200 if (state.switchU) {
42201 state.raise("Invalid quantifier");
42202 }
42203 }
42204 return true
42205 }
42206
42207 if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
42208 this.regexp_eatQuantifier(state);
42209 return true
42210 }
42211
42212 return false
42213};
42214
42215// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion
42216pp$8.regexp_eatAssertion = function(state) {
42217 var start = state.pos;
42218 state.lastAssertionIsQuantifiable = false;
42219
42220 // ^, $
42221 if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {
42222 return true
42223 }
42224
42225 // \b \B
42226 if (state.eat(0x5C /* \ */)) {
42227 if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {
42228 return true
42229 }
42230 state.pos = start;
42231 }
42232
42233 // Lookahead / Lookbehind
42234 if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {
42235 var lookbehind = false;
42236 if (this.options.ecmaVersion >= 9) {
42237 lookbehind = state.eat(0x3C /* < */);
42238 }
42239 if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {
42240 this.regexp_disjunction(state);
42241 if (!state.eat(0x29 /* ) */)) {
42242 state.raise("Unterminated group");
42243 }
42244 state.lastAssertionIsQuantifiable = !lookbehind;
42245 return true
42246 }
42247 }
42248
42249 state.pos = start;
42250 return false
42251};
42252
42253// https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier
42254pp$8.regexp_eatQuantifier = function(state, noError) {
42255 if ( noError === void 0 ) noError = false;
42256
42257 if (this.regexp_eatQuantifierPrefix(state, noError)) {
42258 state.eat(0x3F /* ? */);
42259 return true
42260 }
42261 return false
42262};
42263
42264// https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
42265pp$8.regexp_eatQuantifierPrefix = function(state, noError) {
42266 return (
42267 state.eat(0x2A /* * */) ||
42268 state.eat(0x2B /* + */) ||
42269 state.eat(0x3F /* ? */) ||
42270 this.regexp_eatBracedQuantifier(state, noError)
42271 )
42272};
42273pp$8.regexp_eatBracedQuantifier = function(state, noError) {
42274 var start = state.pos;
42275 if (state.eat(0x7B /* { */)) {
42276 var min = 0, max = -1;
42277 if (this.regexp_eatDecimalDigits(state)) {
42278 min = state.lastIntValue;
42279 if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {
42280 max = state.lastIntValue;
42281 }
42282 if (state.eat(0x7D /* } */)) {
42283 // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
42284 if (max !== -1 && max < min && !noError) {
42285 state.raise("numbers out of order in {} quantifier");
42286 }
42287 return true
42288 }
42289 }
42290 if (state.switchU && !noError) {
42291 state.raise("Incomplete quantifier");
42292 }
42293 state.pos = start;
42294 }
42295 return false
42296};
42297
42298// https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
42299pp$8.regexp_eatAtom = function(state) {
42300 return (
42301 this.regexp_eatPatternCharacters(state) ||
42302 state.eat(0x2E /* . */) ||
42303 this.regexp_eatReverseSolidusAtomEscape(state) ||
42304 this.regexp_eatCharacterClass(state) ||
42305 this.regexp_eatUncapturingGroup(state) ||
42306 this.regexp_eatCapturingGroup(state)
42307 )
42308};
42309pp$8.regexp_eatReverseSolidusAtomEscape = function(state) {
42310 var start = state.pos;
42311 if (state.eat(0x5C /* \ */)) {
42312 if (this.regexp_eatAtomEscape(state)) {
42313 return true
42314 }
42315 state.pos = start;
42316 }
42317 return false
42318};
42319pp$8.regexp_eatUncapturingGroup = function(state) {
42320 var start = state.pos;
42321 if (state.eat(0x28 /* ( */)) {
42322 if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {
42323 this.regexp_disjunction(state);
42324 if (state.eat(0x29 /* ) */)) {
42325 return true
42326 }
42327 state.raise("Unterminated group");
42328 }
42329 state.pos = start;
42330 }
42331 return false
42332};
42333pp$8.regexp_eatCapturingGroup = function(state) {
42334 if (state.eat(0x28 /* ( */)) {
42335 if (this.options.ecmaVersion >= 9) {
42336 this.regexp_groupSpecifier(state);
42337 } else if (state.current() === 0x3F /* ? */) {
42338 state.raise("Invalid group");
42339 }
42340 this.regexp_disjunction(state);
42341 if (state.eat(0x29 /* ) */)) {
42342 state.numCapturingParens += 1;
42343 return true
42344 }
42345 state.raise("Unterminated group");
42346 }
42347 return false
42348};
42349
42350// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom
42351pp$8.regexp_eatExtendedAtom = function(state) {
42352 return (
42353 state.eat(0x2E /* . */) ||
42354 this.regexp_eatReverseSolidusAtomEscape(state) ||
42355 this.regexp_eatCharacterClass(state) ||
42356 this.regexp_eatUncapturingGroup(state) ||
42357 this.regexp_eatCapturingGroup(state) ||
42358 this.regexp_eatInvalidBracedQuantifier(state) ||
42359 this.regexp_eatExtendedPatternCharacter(state)
42360 )
42361};
42362
42363// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
42364pp$8.regexp_eatInvalidBracedQuantifier = function(state) {
42365 if (this.regexp_eatBracedQuantifier(state, true)) {
42366 state.raise("Nothing to repeat");
42367 }
42368 return false
42369};
42370
42371// https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter
42372pp$8.regexp_eatSyntaxCharacter = function(state) {
42373 var ch = state.current();
42374 if (isSyntaxCharacter(ch)) {
42375 state.lastIntValue = ch;
42376 state.advance();
42377 return true
42378 }
42379 return false
42380};
42381function isSyntaxCharacter(ch) {
42382 return (
42383 ch === 0x24 /* $ */ ||
42384 ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||
42385 ch === 0x2E /* . */ ||
42386 ch === 0x3F /* ? */ ||
42387 ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||
42388 ch >= 0x7B /* { */ && ch <= 0x7D /* } */
42389 )
42390}
42391
42392// https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter
42393// But eat eager.
42394pp$8.regexp_eatPatternCharacters = function(state) {
42395 var start = state.pos;
42396 var ch = 0;
42397 while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
42398 state.advance();
42399 }
42400 return state.pos !== start
42401};
42402
42403// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter
42404pp$8.regexp_eatExtendedPatternCharacter = function(state) {
42405 var ch = state.current();
42406 if (
42407 ch !== -1 &&
42408 ch !== 0x24 /* $ */ &&
42409 !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&
42410 ch !== 0x2E /* . */ &&
42411 ch !== 0x3F /* ? */ &&
42412 ch !== 0x5B /* [ */ &&
42413 ch !== 0x5E /* ^ */ &&
42414 ch !== 0x7C /* | */
42415 ) {
42416 state.advance();
42417 return true
42418 }
42419 return false
42420};
42421
42422// GroupSpecifier ::
42423// [empty]
42424// `?` GroupName
42425pp$8.regexp_groupSpecifier = function(state) {
42426 if (state.eat(0x3F /* ? */)) {
42427 if (this.regexp_eatGroupName(state)) {
42428 if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
42429 state.raise("Duplicate capture group name");
42430 }
42431 state.groupNames.push(state.lastStringValue);
42432 return
42433 }
42434 state.raise("Invalid group");
42435 }
42436};
42437
42438// GroupName ::
42439// `<` RegExpIdentifierName `>`
42440// Note: this updates `state.lastStringValue` property with the eaten name.
42441pp$8.regexp_eatGroupName = function(state) {
42442 state.lastStringValue = "";
42443 if (state.eat(0x3C /* < */)) {
42444 if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {
42445 return true
42446 }
42447 state.raise("Invalid capture group name");
42448 }
42449 return false
42450};
42451
42452// RegExpIdentifierName ::
42453// RegExpIdentifierStart
42454// RegExpIdentifierName RegExpIdentifierPart
42455// Note: this updates `state.lastStringValue` property with the eaten name.
42456pp$8.regexp_eatRegExpIdentifierName = function(state) {
42457 state.lastStringValue = "";
42458 if (this.regexp_eatRegExpIdentifierStart(state)) {
42459 state.lastStringValue += codePointToString(state.lastIntValue);
42460 while (this.regexp_eatRegExpIdentifierPart(state)) {
42461 state.lastStringValue += codePointToString(state.lastIntValue);
42462 }
42463 return true
42464 }
42465 return false
42466};
42467
42468// RegExpIdentifierStart ::
42469// UnicodeIDStart
42470// `$`
42471// `_`
42472// `\` RegExpUnicodeEscapeSequence[+U]
42473pp$8.regexp_eatRegExpIdentifierStart = function(state) {
42474 var start = state.pos;
42475 var forceU = this.options.ecmaVersion >= 11;
42476 var ch = state.current(forceU);
42477 state.advance(forceU);
42478
42479 if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
42480 ch = state.lastIntValue;
42481 }
42482 if (isRegExpIdentifierStart(ch)) {
42483 state.lastIntValue = ch;
42484 return true
42485 }
42486
42487 state.pos = start;
42488 return false
42489};
42490function isRegExpIdentifierStart(ch) {
42491 return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */
42492}
42493
42494// RegExpIdentifierPart ::
42495// UnicodeIDContinue
42496// `$`
42497// `_`
42498// `\` RegExpUnicodeEscapeSequence[+U]
42499// <ZWNJ>
42500// <ZWJ>
42501pp$8.regexp_eatRegExpIdentifierPart = function(state) {
42502 var start = state.pos;
42503 var forceU = this.options.ecmaVersion >= 11;
42504 var ch = state.current(forceU);
42505 state.advance(forceU);
42506
42507 if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
42508 ch = state.lastIntValue;
42509 }
42510 if (isRegExpIdentifierPart(ch)) {
42511 state.lastIntValue = ch;
42512 return true
42513 }
42514
42515 state.pos = start;
42516 return false
42517};
42518function isRegExpIdentifierPart(ch) {
42519 return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */
42520}
42521
42522// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
42523pp$8.regexp_eatAtomEscape = function(state) {
42524 if (
42525 this.regexp_eatBackReference(state) ||
42526 this.regexp_eatCharacterClassEscape(state) ||
42527 this.regexp_eatCharacterEscape(state) ||
42528 (state.switchN && this.regexp_eatKGroupName(state))
42529 ) {
42530 return true
42531 }
42532 if (state.switchU) {
42533 // Make the same message as V8.
42534 if (state.current() === 0x63 /* c */) {
42535 state.raise("Invalid unicode escape");
42536 }
42537 state.raise("Invalid escape");
42538 }
42539 return false
42540};
42541pp$8.regexp_eatBackReference = function(state) {
42542 var start = state.pos;
42543 if (this.regexp_eatDecimalEscape(state)) {
42544 var n = state.lastIntValue;
42545 if (state.switchU) {
42546 // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
42547 if (n > state.maxBackReference) {
42548 state.maxBackReference = n;
42549 }
42550 return true
42551 }
42552 if (n <= state.numCapturingParens) {
42553 return true
42554 }
42555 state.pos = start;
42556 }
42557 return false
42558};
42559pp$8.regexp_eatKGroupName = function(state) {
42560 if (state.eat(0x6B /* k */)) {
42561 if (this.regexp_eatGroupName(state)) {
42562 state.backReferenceNames.push(state.lastStringValue);
42563 return true
42564 }
42565 state.raise("Invalid named reference");
42566 }
42567 return false
42568};
42569
42570// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
42571pp$8.regexp_eatCharacterEscape = function(state) {
42572 return (
42573 this.regexp_eatControlEscape(state) ||
42574 this.regexp_eatCControlLetter(state) ||
42575 this.regexp_eatZero(state) ||
42576 this.regexp_eatHexEscapeSequence(state) ||
42577 this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||
42578 (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
42579 this.regexp_eatIdentityEscape(state)
42580 )
42581};
42582pp$8.regexp_eatCControlLetter = function(state) {
42583 var start = state.pos;
42584 if (state.eat(0x63 /* c */)) {
42585 if (this.regexp_eatControlLetter(state)) {
42586 return true
42587 }
42588 state.pos = start;
42589 }
42590 return false
42591};
42592pp$8.regexp_eatZero = function(state) {
42593 if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {
42594 state.lastIntValue = 0;
42595 state.advance();
42596 return true
42597 }
42598 return false
42599};
42600
42601// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape
42602pp$8.regexp_eatControlEscape = function(state) {
42603 var ch = state.current();
42604 if (ch === 0x74 /* t */) {
42605 state.lastIntValue = 0x09; /* \t */
42606 state.advance();
42607 return true
42608 }
42609 if (ch === 0x6E /* n */) {
42610 state.lastIntValue = 0x0A; /* \n */
42611 state.advance();
42612 return true
42613 }
42614 if (ch === 0x76 /* v */) {
42615 state.lastIntValue = 0x0B; /* \v */
42616 state.advance();
42617 return true
42618 }
42619 if (ch === 0x66 /* f */) {
42620 state.lastIntValue = 0x0C; /* \f */
42621 state.advance();
42622 return true
42623 }
42624 if (ch === 0x72 /* r */) {
42625 state.lastIntValue = 0x0D; /* \r */
42626 state.advance();
42627 return true
42628 }
42629 return false
42630};
42631
42632// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter
42633pp$8.regexp_eatControlLetter = function(state) {
42634 var ch = state.current();
42635 if (isControlLetter(ch)) {
42636 state.lastIntValue = ch % 0x20;
42637 state.advance();
42638 return true
42639 }
42640 return false
42641};
42642function isControlLetter(ch) {
42643 return (
42644 (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||
42645 (ch >= 0x61 /* a */ && ch <= 0x7A /* z */)
42646 )
42647}
42648
42649// https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
42650pp$8.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
42651 if ( forceU === void 0 ) forceU = false;
42652
42653 var start = state.pos;
42654 var switchU = forceU || state.switchU;
42655
42656 if (state.eat(0x75 /* u */)) {
42657 if (this.regexp_eatFixedHexDigits(state, 4)) {
42658 var lead = state.lastIntValue;
42659 if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {
42660 var leadSurrogateEnd = state.pos;
42661 if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
42662 var trail = state.lastIntValue;
42663 if (trail >= 0xDC00 && trail <= 0xDFFF) {
42664 state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
42665 return true
42666 }
42667 }
42668 state.pos = leadSurrogateEnd;
42669 state.lastIntValue = lead;
42670 }
42671 return true
42672 }
42673 if (
42674 switchU &&
42675 state.eat(0x7B /* { */) &&
42676 this.regexp_eatHexDigits(state) &&
42677 state.eat(0x7D /* } */) &&
42678 isValidUnicode(state.lastIntValue)
42679 ) {
42680 return true
42681 }
42682 if (switchU) {
42683 state.raise("Invalid unicode escape");
42684 }
42685 state.pos = start;
42686 }
42687
42688 return false
42689};
42690function isValidUnicode(ch) {
42691 return ch >= 0 && ch <= 0x10FFFF
42692}
42693
42694// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
42695pp$8.regexp_eatIdentityEscape = function(state) {
42696 if (state.switchU) {
42697 if (this.regexp_eatSyntaxCharacter(state)) {
42698 return true
42699 }
42700 if (state.eat(0x2F /* / */)) {
42701 state.lastIntValue = 0x2F; /* / */
42702 return true
42703 }
42704 return false
42705 }
42706
42707 var ch = state.current();
42708 if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {
42709 state.lastIntValue = ch;
42710 state.advance();
42711 return true
42712 }
42713
42714 return false
42715};
42716
42717// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape
42718pp$8.regexp_eatDecimalEscape = function(state) {
42719 state.lastIntValue = 0;
42720 var ch = state.current();
42721 if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {
42722 do {
42723 state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
42724 state.advance();
42725 } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)
42726 return true
42727 }
42728 return false
42729};
42730
42731// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape
42732pp$8.regexp_eatCharacterClassEscape = function(state) {
42733 var ch = state.current();
42734
42735 if (isCharacterClassEscape(ch)) {
42736 state.lastIntValue = -1;
42737 state.advance();
42738 return true
42739 }
42740
42741 if (
42742 state.switchU &&
42743 this.options.ecmaVersion >= 9 &&
42744 (ch === 0x50 /* P */ || ch === 0x70 /* p */)
42745 ) {
42746 state.lastIntValue = -1;
42747 state.advance();
42748 if (
42749 state.eat(0x7B /* { */) &&
42750 this.regexp_eatUnicodePropertyValueExpression(state) &&
42751 state.eat(0x7D /* } */)
42752 ) {
42753 return true
42754 }
42755 state.raise("Invalid property name");
42756 }
42757
42758 return false
42759};
42760function isCharacterClassEscape(ch) {
42761 return (
42762 ch === 0x64 /* d */ ||
42763 ch === 0x44 /* D */ ||
42764 ch === 0x73 /* s */ ||
42765 ch === 0x53 /* S */ ||
42766 ch === 0x77 /* w */ ||
42767 ch === 0x57 /* W */
42768 )
42769}
42770
42771// UnicodePropertyValueExpression ::
42772// UnicodePropertyName `=` UnicodePropertyValue
42773// LoneUnicodePropertyNameOrValue
42774pp$8.regexp_eatUnicodePropertyValueExpression = function(state) {
42775 var start = state.pos;
42776
42777 // UnicodePropertyName `=` UnicodePropertyValue
42778 if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
42779 var name = state.lastStringValue;
42780 if (this.regexp_eatUnicodePropertyValue(state)) {
42781 var value = state.lastStringValue;
42782 this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
42783 return true
42784 }
42785 }
42786 state.pos = start;
42787
42788 // LoneUnicodePropertyNameOrValue
42789 if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
42790 var nameOrValue = state.lastStringValue;
42791 this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
42792 return true
42793 }
42794 return false
42795};
42796pp$8.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
42797 if (!has(state.unicodeProperties.nonBinary, name))
42798 { state.raise("Invalid property name"); }
42799 if (!state.unicodeProperties.nonBinary[name].test(value))
42800 { state.raise("Invalid property value"); }
42801};
42802pp$8.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
42803 if (!state.unicodeProperties.binary.test(nameOrValue))
42804 { state.raise("Invalid property name"); }
42805};
42806
42807// UnicodePropertyName ::
42808// UnicodePropertyNameCharacters
42809pp$8.regexp_eatUnicodePropertyName = function(state) {
42810 var ch = 0;
42811 state.lastStringValue = "";
42812 while (isUnicodePropertyNameCharacter(ch = state.current())) {
42813 state.lastStringValue += codePointToString(ch);
42814 state.advance();
42815 }
42816 return state.lastStringValue !== ""
42817};
42818function isUnicodePropertyNameCharacter(ch) {
42819 return isControlLetter(ch) || ch === 0x5F /* _ */
42820}
42821
42822// UnicodePropertyValue ::
42823// UnicodePropertyValueCharacters
42824pp$8.regexp_eatUnicodePropertyValue = function(state) {
42825 var ch = 0;
42826 state.lastStringValue = "";
42827 while (isUnicodePropertyValueCharacter(ch = state.current())) {
42828 state.lastStringValue += codePointToString(ch);
42829 state.advance();
42830 }
42831 return state.lastStringValue !== ""
42832};
42833function isUnicodePropertyValueCharacter(ch) {
42834 return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)
42835}
42836
42837// LoneUnicodePropertyNameOrValue ::
42838// UnicodePropertyValueCharacters
42839pp$8.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
42840 return this.regexp_eatUnicodePropertyValue(state)
42841};
42842
42843// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
42844pp$8.regexp_eatCharacterClass = function(state) {
42845 if (state.eat(0x5B /* [ */)) {
42846 state.eat(0x5E /* ^ */);
42847 this.regexp_classRanges(state);
42848 if (state.eat(0x5D /* ] */)) {
42849 return true
42850 }
42851 // Unreachable since it threw "unterminated regular expression" error before.
42852 state.raise("Unterminated character class");
42853 }
42854 return false
42855};
42856
42857// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
42858// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
42859// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
42860pp$8.regexp_classRanges = function(state) {
42861 while (this.regexp_eatClassAtom(state)) {
42862 var left = state.lastIntValue;
42863 if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {
42864 var right = state.lastIntValue;
42865 if (state.switchU && (left === -1 || right === -1)) {
42866 state.raise("Invalid character class");
42867 }
42868 if (left !== -1 && right !== -1 && left > right) {
42869 state.raise("Range out of order in character class");
42870 }
42871 }
42872 }
42873};
42874
42875// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom
42876// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash
42877pp$8.regexp_eatClassAtom = function(state) {
42878 var start = state.pos;
42879
42880 if (state.eat(0x5C /* \ */)) {
42881 if (this.regexp_eatClassEscape(state)) {
42882 return true
42883 }
42884 if (state.switchU) {
42885 // Make the same message as V8.
42886 var ch$1 = state.current();
42887 if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {
42888 state.raise("Invalid class escape");
42889 }
42890 state.raise("Invalid escape");
42891 }
42892 state.pos = start;
42893 }
42894
42895 var ch = state.current();
42896 if (ch !== 0x5D /* ] */) {
42897 state.lastIntValue = ch;
42898 state.advance();
42899 return true
42900 }
42901
42902 return false
42903};
42904
42905// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape
42906pp$8.regexp_eatClassEscape = function(state) {
42907 var start = state.pos;
42908
42909 if (state.eat(0x62 /* b */)) {
42910 state.lastIntValue = 0x08; /* <BS> */
42911 return true
42912 }
42913
42914 if (state.switchU && state.eat(0x2D /* - */)) {
42915 state.lastIntValue = 0x2D; /* - */
42916 return true
42917 }
42918
42919 if (!state.switchU && state.eat(0x63 /* c */)) {
42920 if (this.regexp_eatClassControlLetter(state)) {
42921 return true
42922 }
42923 state.pos = start;
42924 }
42925
42926 return (
42927 this.regexp_eatCharacterClassEscape(state) ||
42928 this.regexp_eatCharacterEscape(state)
42929 )
42930};
42931
42932// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter
42933pp$8.regexp_eatClassControlLetter = function(state) {
42934 var ch = state.current();
42935 if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {
42936 state.lastIntValue = ch % 0x20;
42937 state.advance();
42938 return true
42939 }
42940 return false
42941};
42942
42943// https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
42944pp$8.regexp_eatHexEscapeSequence = function(state) {
42945 var start = state.pos;
42946 if (state.eat(0x78 /* x */)) {
42947 if (this.regexp_eatFixedHexDigits(state, 2)) {
42948 return true
42949 }
42950 if (state.switchU) {
42951 state.raise("Invalid escape");
42952 }
42953 state.pos = start;
42954 }
42955 return false
42956};
42957
42958// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits
42959pp$8.regexp_eatDecimalDigits = function(state) {
42960 var start = state.pos;
42961 var ch = 0;
42962 state.lastIntValue = 0;
42963 while (isDecimalDigit(ch = state.current())) {
42964 state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
42965 state.advance();
42966 }
42967 return state.pos !== start
42968};
42969function isDecimalDigit(ch) {
42970 return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */
42971}
42972
42973// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits
42974pp$8.regexp_eatHexDigits = function(state) {
42975 var start = state.pos;
42976 var ch = 0;
42977 state.lastIntValue = 0;
42978 while (isHexDigit(ch = state.current())) {
42979 state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
42980 state.advance();
42981 }
42982 return state.pos !== start
42983};
42984function isHexDigit(ch) {
42985 return (
42986 (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||
42987 (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||
42988 (ch >= 0x61 /* a */ && ch <= 0x66 /* f */)
42989 )
42990}
42991function hexToInt(ch) {
42992 if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {
42993 return 10 + (ch - 0x41 /* A */)
42994 }
42995 if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {
42996 return 10 + (ch - 0x61 /* a */)
42997 }
42998 return ch - 0x30 /* 0 */
42999}
43000
43001// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence
43002// Allows only 0-377(octal) i.e. 0-255(decimal).
43003pp$8.regexp_eatLegacyOctalEscapeSequence = function(state) {
43004 if (this.regexp_eatOctalDigit(state)) {
43005 var n1 = state.lastIntValue;
43006 if (this.regexp_eatOctalDigit(state)) {
43007 var n2 = state.lastIntValue;
43008 if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
43009 state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
43010 } else {
43011 state.lastIntValue = n1 * 8 + n2;
43012 }
43013 } else {
43014 state.lastIntValue = n1;
43015 }
43016 return true
43017 }
43018 return false
43019};
43020
43021// https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit
43022pp$8.regexp_eatOctalDigit = function(state) {
43023 var ch = state.current();
43024 if (isOctalDigit(ch)) {
43025 state.lastIntValue = ch - 0x30; /* 0 */
43026 state.advance();
43027 return true
43028 }
43029 state.lastIntValue = 0;
43030 return false
43031};
43032function isOctalDigit(ch) {
43033 return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */
43034}
43035
43036// https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits
43037// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit
43038// And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
43039pp$8.regexp_eatFixedHexDigits = function(state, length) {
43040 var start = state.pos;
43041 state.lastIntValue = 0;
43042 for (var i = 0; i < length; ++i) {
43043 var ch = state.current();
43044 if (!isHexDigit(ch)) {
43045 state.pos = start;
43046 return false
43047 }
43048 state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
43049 state.advance();
43050 }
43051 return true
43052};
43053
43054// Object type used to represent tokens. Note that normally, tokens
43055// simply exist as properties on the parser object. This is only
43056// used for the onToken callback and the external tokenizer.
43057
43058var Token = function Token(p) {
43059 this.type = p.type;
43060 this.value = p.value;
43061 this.start = p.start;
43062 this.end = p.end;
43063 if (p.options.locations)
43064 { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
43065 if (p.options.ranges)
43066 { this.range = [p.start, p.end]; }
43067};
43068
43069// ## Tokenizer
43070
43071var pp$9 = Parser.prototype;
43072
43073// Move to the next token
43074
43075pp$9.next = function(ignoreEscapeSequenceInKeyword) {
43076 if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)
43077 { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); }
43078 if (this.options.onToken)
43079 { this.options.onToken(new Token(this)); }
43080
43081 this.lastTokEnd = this.end;
43082 this.lastTokStart = this.start;
43083 this.lastTokEndLoc = this.endLoc;
43084 this.lastTokStartLoc = this.startLoc;
43085 this.nextToken();
43086};
43087
43088pp$9.getToken = function() {
43089 this.next();
43090 return new Token(this)
43091};
43092
43093// If we're in an ES6 environment, make parsers iterable
43094if (typeof Symbol !== "undefined")
43095 { pp$9[Symbol.iterator] = function() {
43096 var this$1$1 = this;
43097
43098 return {
43099 next: function () {
43100 var token = this$1$1.getToken();
43101 return {
43102 done: token.type === types.eof,
43103 value: token
43104 }
43105 }
43106 }
43107 }; }
43108
43109// Toggle strict mode. Re-reads the next number or string to please
43110// pedantic tests (`"use strict"; 010;` should fail).
43111
43112pp$9.curContext = function() {
43113 return this.context[this.context.length - 1]
43114};
43115
43116// Read a single token, updating the parser object's token-related
43117// properties.
43118
43119pp$9.nextToken = function() {
43120 var curContext = this.curContext();
43121 if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
43122
43123 this.start = this.pos;
43124 if (this.options.locations) { this.startLoc = this.curPosition(); }
43125 if (this.pos >= this.input.length) { return this.finishToken(types.eof) }
43126
43127 if (curContext.override) { return curContext.override(this) }
43128 else { this.readToken(this.fullCharCodeAtPos()); }
43129};
43130
43131pp$9.readToken = function(code) {
43132 // Identifier or keyword. '\uXXXX' sequences are allowed in
43133 // identifiers, so '\' also dispatches to that.
43134 if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
43135 { return this.readWord() }
43136
43137 return this.getTokenFromCode(code)
43138};
43139
43140pp$9.fullCharCodeAtPos = function() {
43141 var code = this.input.charCodeAt(this.pos);
43142 if (code <= 0xd7ff || code >= 0xdc00) { return code }
43143 var next = this.input.charCodeAt(this.pos + 1);
43144 return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00
43145};
43146
43147pp$9.skipBlockComment = function() {
43148 var startLoc = this.options.onComment && this.curPosition();
43149 var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
43150 if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
43151 this.pos = end + 2;
43152 if (this.options.locations) {
43153 lineBreakG.lastIndex = start;
43154 var match;
43155 while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {
43156 ++this.curLine;
43157 this.lineStart = match.index + match[0].length;
43158 }
43159 }
43160 if (this.options.onComment)
43161 { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
43162 startLoc, this.curPosition()); }
43163};
43164
43165pp$9.skipLineComment = function(startSkip) {
43166 var start = this.pos;
43167 var startLoc = this.options.onComment && this.curPosition();
43168 var ch = this.input.charCodeAt(this.pos += startSkip);
43169 while (this.pos < this.input.length && !isNewLine(ch)) {
43170 ch = this.input.charCodeAt(++this.pos);
43171 }
43172 if (this.options.onComment)
43173 { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
43174 startLoc, this.curPosition()); }
43175};
43176
43177// Called at the start of the parse and after every token. Skips
43178// whitespace and comments, and.
43179
43180pp$9.skipSpace = function() {
43181 loop: while (this.pos < this.input.length) {
43182 var ch = this.input.charCodeAt(this.pos);
43183 switch (ch) {
43184 case 32: case 160: // ' '
43185 ++this.pos;
43186 break
43187 case 13:
43188 if (this.input.charCodeAt(this.pos + 1) === 10) {
43189 ++this.pos;
43190 }
43191 case 10: case 8232: case 8233:
43192 ++this.pos;
43193 if (this.options.locations) {
43194 ++this.curLine;
43195 this.lineStart = this.pos;
43196 }
43197 break
43198 case 47: // '/'
43199 switch (this.input.charCodeAt(this.pos + 1)) {
43200 case 42: // '*'
43201 this.skipBlockComment();
43202 break
43203 case 47:
43204 this.skipLineComment(2);
43205 break
43206 default:
43207 break loop
43208 }
43209 break
43210 default:
43211 if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
43212 ++this.pos;
43213 } else {
43214 break loop
43215 }
43216 }
43217 }
43218};
43219
43220// Called at the end of every token. Sets `end`, `val`, and
43221// maintains `context` and `exprAllowed`, and skips the space after
43222// the token, so that the next one's `start` will point at the
43223// right position.
43224
43225pp$9.finishToken = function(type, val) {
43226 this.end = this.pos;
43227 if (this.options.locations) { this.endLoc = this.curPosition(); }
43228 var prevType = this.type;
43229 this.type = type;
43230 this.value = val;
43231
43232 this.updateContext(prevType);
43233};
43234
43235// ### Token reading
43236
43237// This is the function that is called to fetch the next token. It
43238// is somewhat obscure, because it works in character codes rather
43239// than characters, and because operator parsing has been inlined
43240// into it.
43241//
43242// All in the name of speed.
43243//
43244pp$9.readToken_dot = function() {
43245 var next = this.input.charCodeAt(this.pos + 1);
43246 if (next >= 48 && next <= 57) { return this.readNumber(true) }
43247 var next2 = this.input.charCodeAt(this.pos + 2);
43248 if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
43249 this.pos += 3;
43250 return this.finishToken(types.ellipsis)
43251 } else {
43252 ++this.pos;
43253 return this.finishToken(types.dot)
43254 }
43255};
43256
43257pp$9.readToken_slash = function() { // '/'
43258 var next = this.input.charCodeAt(this.pos + 1);
43259 if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
43260 if (next === 61) { return this.finishOp(types.assign, 2) }
43261 return this.finishOp(types.slash, 1)
43262};
43263
43264pp$9.readToken_mult_modulo_exp = function(code) { // '%*'
43265 var next = this.input.charCodeAt(this.pos + 1);
43266 var size = 1;
43267 var tokentype = code === 42 ? types.star : types.modulo;
43268
43269 // exponentiation operator ** and **=
43270 if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
43271 ++size;
43272 tokentype = types.starstar;
43273 next = this.input.charCodeAt(this.pos + 2);
43274 }
43275
43276 if (next === 61) { return this.finishOp(types.assign, size + 1) }
43277 return this.finishOp(tokentype, size)
43278};
43279
43280pp$9.readToken_pipe_amp = function(code) { // '|&'
43281 var next = this.input.charCodeAt(this.pos + 1);
43282 if (next === code) {
43283 if (this.options.ecmaVersion >= 12) {
43284 var next2 = this.input.charCodeAt(this.pos + 2);
43285 if (next2 === 61) { return this.finishOp(types.assign, 3) }
43286 }
43287 return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2)
43288 }
43289 if (next === 61) { return this.finishOp(types.assign, 2) }
43290 return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1)
43291};
43292
43293pp$9.readToken_caret = function() { // '^'
43294 var next = this.input.charCodeAt(this.pos + 1);
43295 if (next === 61) { return this.finishOp(types.assign, 2) }
43296 return this.finishOp(types.bitwiseXOR, 1)
43297};
43298
43299pp$9.readToken_plus_min = function(code) { // '+-'
43300 var next = this.input.charCodeAt(this.pos + 1);
43301 if (next === code) {
43302 if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&
43303 (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
43304 // A `-->` line comment
43305 this.skipLineComment(3);
43306 this.skipSpace();
43307 return this.nextToken()
43308 }
43309 return this.finishOp(types.incDec, 2)
43310 }
43311 if (next === 61) { return this.finishOp(types.assign, 2) }
43312 return this.finishOp(types.plusMin, 1)
43313};
43314
43315pp$9.readToken_lt_gt = function(code) { // '<>'
43316 var next = this.input.charCodeAt(this.pos + 1);
43317 var size = 1;
43318 if (next === code) {
43319 size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
43320 if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types.assign, size + 1) }
43321 return this.finishOp(types.bitShift, size)
43322 }
43323 if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&
43324 this.input.charCodeAt(this.pos + 3) === 45) {
43325 // `<!--`, an XML-style comment that should be interpreted as a line comment
43326 this.skipLineComment(4);
43327 this.skipSpace();
43328 return this.nextToken()
43329 }
43330 if (next === 61) { size = 2; }
43331 return this.finishOp(types.relational, size)
43332};
43333
43334pp$9.readToken_eq_excl = function(code) { // '=!'
43335 var next = this.input.charCodeAt(this.pos + 1);
43336 if (next === 61) { return this.finishOp(types.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
43337 if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
43338 this.pos += 2;
43339 return this.finishToken(types.arrow)
43340 }
43341 return this.finishOp(code === 61 ? types.eq : types.prefix, 1)
43342};
43343
43344pp$9.readToken_question = function() { // '?'
43345 var ecmaVersion = this.options.ecmaVersion;
43346 if (ecmaVersion >= 11) {
43347 var next = this.input.charCodeAt(this.pos + 1);
43348 if (next === 46) {
43349 var next2 = this.input.charCodeAt(this.pos + 2);
43350 if (next2 < 48 || next2 > 57) { return this.finishOp(types.questionDot, 2) }
43351 }
43352 if (next === 63) {
43353 if (ecmaVersion >= 12) {
43354 var next2$1 = this.input.charCodeAt(this.pos + 2);
43355 if (next2$1 === 61) { return this.finishOp(types.assign, 3) }
43356 }
43357 return this.finishOp(types.coalesce, 2)
43358 }
43359 }
43360 return this.finishOp(types.question, 1)
43361};
43362
43363pp$9.readToken_numberSign = function() { // '#'
43364 var ecmaVersion = this.options.ecmaVersion;
43365 var code = 35; // '#'
43366 if (ecmaVersion >= 13) {
43367 ++this.pos;
43368 code = this.fullCharCodeAtPos();
43369 if (isIdentifierStart(code, true) || code === 92 /* '\' */) {
43370 return this.finishToken(types.privateId, this.readWord1())
43371 }
43372 }
43373
43374 this.raise(this.pos, "Unexpected character '" + codePointToString$1(code) + "'");
43375};
43376
43377pp$9.getTokenFromCode = function(code) {
43378 switch (code) {
43379 // The interpretation of a dot depends on whether it is followed
43380 // by a digit or another two dots.
43381 case 46: // '.'
43382 return this.readToken_dot()
43383
43384 // Punctuation tokens.
43385 case 40: ++this.pos; return this.finishToken(types.parenL)
43386 case 41: ++this.pos; return this.finishToken(types.parenR)
43387 case 59: ++this.pos; return this.finishToken(types.semi)
43388 case 44: ++this.pos; return this.finishToken(types.comma)
43389 case 91: ++this.pos; return this.finishToken(types.bracketL)
43390 case 93: ++this.pos; return this.finishToken(types.bracketR)
43391 case 123: ++this.pos; return this.finishToken(types.braceL)
43392 case 125: ++this.pos; return this.finishToken(types.braceR)
43393 case 58: ++this.pos; return this.finishToken(types.colon)
43394
43395 case 96: // '`'
43396 if (this.options.ecmaVersion < 6) { break }
43397 ++this.pos;
43398 return this.finishToken(types.backQuote)
43399
43400 case 48: // '0'
43401 var next = this.input.charCodeAt(this.pos + 1);
43402 if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
43403 if (this.options.ecmaVersion >= 6) {
43404 if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
43405 if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
43406 }
43407
43408 // Anything else beginning with a digit is an integer, octal
43409 // number, or float.
43410 case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
43411 return this.readNumber(false)
43412
43413 // Quotes produce strings.
43414 case 34: case 39: // '"', "'"
43415 return this.readString(code)
43416
43417 // Operators are parsed inline in tiny state machines. '=' (61) is
43418 // often referred to. `finishOp` simply skips the amount of
43419 // characters it is given as second argument, and returns a token
43420 // of the type given by its first argument.
43421
43422 case 47: // '/'
43423 return this.readToken_slash()
43424
43425 case 37: case 42: // '%*'
43426 return this.readToken_mult_modulo_exp(code)
43427
43428 case 124: case 38: // '|&'
43429 return this.readToken_pipe_amp(code)
43430
43431 case 94: // '^'
43432 return this.readToken_caret()
43433
43434 case 43: case 45: // '+-'
43435 return this.readToken_plus_min(code)
43436
43437 case 60: case 62: // '<>'
43438 return this.readToken_lt_gt(code)
43439
43440 case 61: case 33: // '=!'
43441 return this.readToken_eq_excl(code)
43442
43443 case 63: // '?'
43444 return this.readToken_question()
43445
43446 case 126: // '~'
43447 return this.finishOp(types.prefix, 1)
43448
43449 case 35: // '#'
43450 return this.readToken_numberSign()
43451 }
43452
43453 this.raise(this.pos, "Unexpected character '" + codePointToString$1(code) + "'");
43454};
43455
43456pp$9.finishOp = function(type, size) {
43457 var str = this.input.slice(this.pos, this.pos + size);
43458 this.pos += size;
43459 return this.finishToken(type, str)
43460};
43461
43462pp$9.readRegexp = function() {
43463 var escaped, inClass, start = this.pos;
43464 for (;;) {
43465 if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }
43466 var ch = this.input.charAt(this.pos);
43467 if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }
43468 if (!escaped) {
43469 if (ch === "[") { inClass = true; }
43470 else if (ch === "]" && inClass) { inClass = false; }
43471 else if (ch === "/" && !inClass) { break }
43472 escaped = ch === "\\";
43473 } else { escaped = false; }
43474 ++this.pos;
43475 }
43476 var pattern = this.input.slice(start, this.pos);
43477 ++this.pos;
43478 var flagsStart = this.pos;
43479 var flags = this.readWord1();
43480 if (this.containsEsc) { this.unexpected(flagsStart); }
43481
43482 // Validate pattern
43483 var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
43484 state.reset(start, pattern, flags);
43485 this.validateRegExpFlags(state);
43486 this.validateRegExpPattern(state);
43487
43488 // Create Literal#value property value.
43489 var value = null;
43490 try {
43491 value = new RegExp(pattern, flags);
43492 } catch (e) {
43493 // ESTree requires null if it failed to instantiate RegExp object.
43494 // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral
43495 }
43496
43497 return this.finishToken(types.regexp, {pattern: pattern, flags: flags, value: value})
43498};
43499
43500// Read an integer in the given radix. Return null if zero digits
43501// were read, the integer value otherwise. When `len` is given, this
43502// will return `null` unless the integer has exactly `len` digits.
43503
43504pp$9.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
43505 // `len` is used for character escape sequences. In that case, disallow separators.
43506 var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined;
43507
43508 // `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b)
43509 // and isn't fraction part nor exponent part. In that case, if the first digit
43510 // is zero then disallow separators.
43511 var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
43512
43513 var start = this.pos, total = 0, lastCode = 0;
43514 for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {
43515 var code = this.input.charCodeAt(this.pos), val = (void 0);
43516
43517 if (allowSeparators && code === 95) {
43518 if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); }
43519 if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); }
43520 if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); }
43521 lastCode = code;
43522 continue
43523 }
43524
43525 if (code >= 97) { val = code - 97 + 10; } // a
43526 else if (code >= 65) { val = code - 65 + 10; } // A
43527 else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
43528 else { val = Infinity; }
43529 if (val >= radix) { break }
43530 lastCode = code;
43531 total = total * radix + val;
43532 }
43533
43534 if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); }
43535 if (this.pos === start || len != null && this.pos - start !== len) { return null }
43536
43537 return total
43538};
43539
43540function stringToNumber(str, isLegacyOctalNumericLiteral) {
43541 if (isLegacyOctalNumericLiteral) {
43542 return parseInt(str, 8)
43543 }
43544
43545 // `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value.
43546 return parseFloat(str.replace(/_/g, ""))
43547}
43548
43549function stringToBigInt(str) {
43550 if (typeof BigInt !== "function") {
43551 return null
43552 }
43553
43554 // `BigInt(value)` throws syntax error if the string contains numeric separators.
43555 return BigInt(str.replace(/_/g, ""))
43556}
43557
43558pp$9.readRadixNumber = function(radix) {
43559 var start = this.pos;
43560 this.pos += 2; // 0x
43561 var val = this.readInt(radix);
43562 if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
43563 if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
43564 val = stringToBigInt(this.input.slice(start, this.pos));
43565 ++this.pos;
43566 } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
43567 return this.finishToken(types.num, val)
43568};
43569
43570// Read an integer, octal integer, or floating-point number.
43571
43572pp$9.readNumber = function(startsWithDot) {
43573 var start = this.pos;
43574 if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); }
43575 var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
43576 if (octal && this.strict) { this.raise(start, "Invalid number"); }
43577 var next = this.input.charCodeAt(this.pos);
43578 if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
43579 var val$1 = stringToBigInt(this.input.slice(start, this.pos));
43580 ++this.pos;
43581 if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
43582 return this.finishToken(types.num, val$1)
43583 }
43584 if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }
43585 if (next === 46 && !octal) { // '.'
43586 ++this.pos;
43587 this.readInt(10);
43588 next = this.input.charCodeAt(this.pos);
43589 }
43590 if ((next === 69 || next === 101) && !octal) { // 'eE'
43591 next = this.input.charCodeAt(++this.pos);
43592 if (next === 43 || next === 45) { ++this.pos; } // '+-'
43593 if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
43594 }
43595 if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
43596
43597 var val = stringToNumber(this.input.slice(start, this.pos), octal);
43598 return this.finishToken(types.num, val)
43599};
43600
43601// Read a string value, interpreting backslash-escapes.
43602
43603pp$9.readCodePoint = function() {
43604 var ch = this.input.charCodeAt(this.pos), code;
43605
43606 if (ch === 123) { // '{'
43607 if (this.options.ecmaVersion < 6) { this.unexpected(); }
43608 var codePos = ++this.pos;
43609 code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
43610 ++this.pos;
43611 if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
43612 } else {
43613 code = this.readHexChar(4);
43614 }
43615 return code
43616};
43617
43618function codePointToString$1(code) {
43619 // UTF-16 Decoding
43620 if (code <= 0xFFFF) { return String.fromCharCode(code) }
43621 code -= 0x10000;
43622 return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
43623}
43624
43625pp$9.readString = function(quote) {
43626 var out = "", chunkStart = ++this.pos;
43627 for (;;) {
43628 if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }
43629 var ch = this.input.charCodeAt(this.pos);
43630 if (ch === quote) { break }
43631 if (ch === 92) { // '\'
43632 out += this.input.slice(chunkStart, this.pos);
43633 out += this.readEscapedChar(false);
43634 chunkStart = this.pos;
43635 } else {
43636 if (isNewLine(ch, this.options.ecmaVersion >= 10)) { this.raise(this.start, "Unterminated string constant"); }
43637 ++this.pos;
43638 }
43639 }
43640 out += this.input.slice(chunkStart, this.pos++);
43641 return this.finishToken(types.string, out)
43642};
43643
43644// Reads template string tokens.
43645
43646var INVALID_TEMPLATE_ESCAPE_ERROR = {};
43647
43648pp$9.tryReadTemplateToken = function() {
43649 this.inTemplateElement = true;
43650 try {
43651 this.readTmplToken();
43652 } catch (err) {
43653 if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
43654 this.readInvalidTemplateToken();
43655 } else {
43656 throw err
43657 }
43658 }
43659
43660 this.inTemplateElement = false;
43661};
43662
43663pp$9.invalidStringToken = function(position, message) {
43664 if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
43665 throw INVALID_TEMPLATE_ESCAPE_ERROR
43666 } else {
43667 this.raise(position, message);
43668 }
43669};
43670
43671pp$9.readTmplToken = function() {
43672 var out = "", chunkStart = this.pos;
43673 for (;;) {
43674 if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }
43675 var ch = this.input.charCodeAt(this.pos);
43676 if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'
43677 if (this.pos === this.start && (this.type === types.template || this.type === types.invalidTemplate)) {
43678 if (ch === 36) {
43679 this.pos += 2;
43680 return this.finishToken(types.dollarBraceL)
43681 } else {
43682 ++this.pos;
43683 return this.finishToken(types.backQuote)
43684 }
43685 }
43686 out += this.input.slice(chunkStart, this.pos);
43687 return this.finishToken(types.template, out)
43688 }
43689 if (ch === 92) { // '\'
43690 out += this.input.slice(chunkStart, this.pos);
43691 out += this.readEscapedChar(true);
43692 chunkStart = this.pos;
43693 } else if (isNewLine(ch)) {
43694 out += this.input.slice(chunkStart, this.pos);
43695 ++this.pos;
43696 switch (ch) {
43697 case 13:
43698 if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }
43699 case 10:
43700 out += "\n";
43701 break
43702 default:
43703 out += String.fromCharCode(ch);
43704 break
43705 }
43706 if (this.options.locations) {
43707 ++this.curLine;
43708 this.lineStart = this.pos;
43709 }
43710 chunkStart = this.pos;
43711 } else {
43712 ++this.pos;
43713 }
43714 }
43715};
43716
43717// Reads a template token to search for the end, without validating any escape sequences
43718pp$9.readInvalidTemplateToken = function() {
43719 for (; this.pos < this.input.length; this.pos++) {
43720 switch (this.input[this.pos]) {
43721 case "\\":
43722 ++this.pos;
43723 break
43724
43725 case "$":
43726 if (this.input[this.pos + 1] !== "{") {
43727 break
43728 }
43729 // falls through
43730
43731 case "`":
43732 return this.finishToken(types.invalidTemplate, this.input.slice(this.start, this.pos))
43733
43734 // no default
43735 }
43736 }
43737 this.raise(this.start, "Unterminated template");
43738};
43739
43740// Used to read escaped characters
43741
43742pp$9.readEscapedChar = function(inTemplate) {
43743 var ch = this.input.charCodeAt(++this.pos);
43744 ++this.pos;
43745 switch (ch) {
43746 case 110: return "\n" // 'n' -> '\n'
43747 case 114: return "\r" // 'r' -> '\r'
43748 case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
43749 case 117: return codePointToString$1(this.readCodePoint()) // 'u'
43750 case 116: return "\t" // 't' -> '\t'
43751 case 98: return "\b" // 'b' -> '\b'
43752 case 118: return "\u000b" // 'v' -> '\u000b'
43753 case 102: return "\f" // 'f' -> '\f'
43754 case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
43755 case 10: // ' \n'
43756 if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
43757 return ""
43758 case 56:
43759 case 57:
43760 if (this.strict) {
43761 this.invalidStringToken(
43762 this.pos - 1,
43763 "Invalid escape sequence"
43764 );
43765 }
43766 if (inTemplate) {
43767 var codePos = this.pos - 1;
43768
43769 this.invalidStringToken(
43770 codePos,
43771 "Invalid escape sequence in template string"
43772 );
43773
43774 return null
43775 }
43776 default:
43777 if (ch >= 48 && ch <= 55) {
43778 var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
43779 var octal = parseInt(octalStr, 8);
43780 if (octal > 255) {
43781 octalStr = octalStr.slice(0, -1);
43782 octal = parseInt(octalStr, 8);
43783 }
43784 this.pos += octalStr.length - 1;
43785 ch = this.input.charCodeAt(this.pos);
43786 if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
43787 this.invalidStringToken(
43788 this.pos - 1 - octalStr.length,
43789 inTemplate
43790 ? "Octal literal in template string"
43791 : "Octal literal in strict mode"
43792 );
43793 }
43794 return String.fromCharCode(octal)
43795 }
43796 if (isNewLine(ch)) {
43797 // Unicode new line characters after \ get removed from output in both
43798 // template literals and strings
43799 return ""
43800 }
43801 return String.fromCharCode(ch)
43802 }
43803};
43804
43805// Used to read character escape sequences ('\x', '\u', '\U').
43806
43807pp$9.readHexChar = function(len) {
43808 var codePos = this.pos;
43809 var n = this.readInt(16, len);
43810 if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
43811 return n
43812};
43813
43814// Read an identifier, and return it as a string. Sets `this.containsEsc`
43815// to whether the word contained a '\u' escape.
43816//
43817// Incrementally adds only escaped chars, adding other chunks as-is
43818// as a micro-optimization.
43819
43820pp$9.readWord1 = function() {
43821 this.containsEsc = false;
43822 var word = "", first = true, chunkStart = this.pos;
43823 var astral = this.options.ecmaVersion >= 6;
43824 while (this.pos < this.input.length) {
43825 var ch = this.fullCharCodeAtPos();
43826 if (isIdentifierChar(ch, astral)) {
43827 this.pos += ch <= 0xffff ? 1 : 2;
43828 } else if (ch === 92) { // "\"
43829 this.containsEsc = true;
43830 word += this.input.slice(chunkStart, this.pos);
43831 var escStart = this.pos;
43832 if (this.input.charCodeAt(++this.pos) !== 117) // "u"
43833 { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }
43834 ++this.pos;
43835 var esc = this.readCodePoint();
43836 if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
43837 { this.invalidStringToken(escStart, "Invalid Unicode escape"); }
43838 word += codePointToString$1(esc);
43839 chunkStart = this.pos;
43840 } else {
43841 break
43842 }
43843 first = false;
43844 }
43845 return word + this.input.slice(chunkStart, this.pos)
43846};
43847
43848// Read an identifier or keyword token. Will check for reserved
43849// words when necessary.
43850
43851pp$9.readWord = function() {
43852 var word = this.readWord1();
43853 var type = types.name;
43854 if (this.keywords.test(word)) {
43855 type = keywords$1[word];
43856 }
43857 return this.finishToken(type, word)
43858};
43859
43860// Acorn is a tiny, fast JavaScript parser written in JavaScript.
43861
43862var version = "8.4.1";
43863
43864Parser.acorn = {
43865 Parser: Parser,
43866 version: version,
43867 defaultOptions: defaultOptions,
43868 Position: Position,
43869 SourceLocation: SourceLocation,
43870 getLineInfo: getLineInfo,
43871 Node: Node,
43872 TokenType: TokenType,
43873 tokTypes: types,
43874 keywordTypes: keywords$1,
43875 TokContext: TokContext,
43876 tokContexts: types$1,
43877 isIdentifierChar: isIdentifierChar,
43878 isIdentifierStart: isIdentifierStart,
43879 Token: Token,
43880 isNewLine: isNewLine,
43881 lineBreak: lineBreak,
43882 lineBreakG: lineBreakG,
43883 nonASCIIwhitespace: nonASCIIwhitespace
43884};
43885
43886// The main exported interface (under `self.acorn` when in the
43887// browser) is a `parse` function that takes a code string and
43888// returns an abstract syntax tree as specified by [Mozilla parser
43889// API][api].
43890//
43891// [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
43892
43893function parse$c(input, options) {
43894 return Parser.parse(input, options)
43895}
43896
43897// This function tries to parse a single expression at a given
43898// offset in a string. Useful for parsing mixed-language formats
43899// that embed JavaScript expressions.
43900
43901function parseExpressionAt(input, pos, options) {
43902 return Parser.parseExpressionAt(input, pos, options)
43903}
43904
43905// Acorn is organized as a tokenizer and a recursive-descent parser.
43906// The `tokenizer` export provides an interface to the tokenizer.
43907
43908function tokenizer(input, options) {
43909 return Parser.tokenizer(input, options)
43910}
43911
43912var acorn$1 = {
43913 __proto__: null,
43914 Node: Node,
43915 Parser: Parser,
43916 Position: Position,
43917 SourceLocation: SourceLocation,
43918 TokContext: TokContext,
43919 Token: Token,
43920 TokenType: TokenType,
43921 defaultOptions: defaultOptions,
43922 getLineInfo: getLineInfo,
43923 isIdentifierChar: isIdentifierChar,
43924 isIdentifierStart: isIdentifierStart,
43925 isNewLine: isNewLine,
43926 keywordTypes: keywords$1,
43927 lineBreak: lineBreak,
43928 lineBreakG: lineBreakG,
43929 nonASCIIwhitespace: nonASCIIwhitespace,
43930 parse: parse$c,
43931 parseExpressionAt: parseExpressionAt,
43932 tokContexts: types$1,
43933 tokTypes: types,
43934 tokenizer: tokenizer,
43935 version: version
43936};
43937
43938var acorn = {exports: {}};
43939
43940(function (module, exports) {
43941(function (global, factory) {
43942 factory(exports) ;
43943}(commonjsGlobal, (function (exports) {
43944 // Reserved word lists for various dialects of the language
43945
43946 var reservedWords = {
43947 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
43948 5: "class enum extends super const export import",
43949 6: "enum",
43950 strict: "implements interface let package private protected public static yield",
43951 strictBind: "eval arguments"
43952 };
43953
43954 // And the keywords
43955
43956 var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";
43957
43958 var keywords = {
43959 5: ecma5AndLessKeywords,
43960 "5module": ecma5AndLessKeywords + " export import",
43961 6: ecma5AndLessKeywords + " const class extends export import super"
43962 };
43963
43964 var keywordRelationalOperator = /^in(stanceof)?$/;
43965
43966 // ## Character categories
43967
43968 // Big ugly regular expressions that match characters in the
43969 // whitespace, identifier, and identifier-start categories. These
43970 // are only applied when a character is found to actually have a
43971 // code point above 128.
43972 // Generated by `bin/generate-identifier-regex.js`.
43973 var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08c7\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
43974 var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
43975
43976 var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
43977 var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
43978
43979 nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
43980
43981 // These are a run-length and offset encoded representation of the
43982 // >0xffff code points that are a valid part of identifiers. The
43983 // offset starts at 0x10000, and each pair of numbers represents an
43984 // offset to the next range, and then a size of the range. They were
43985 // generated by bin/generate-identifier-regex.js
43986
43987 // eslint-disable-next-line comma-spacing
43988 var astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,349,41,7,1,79,28,11,0,9,21,107,20,28,22,13,52,76,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,230,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,35,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,190,0,80,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,689,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,43,8,8952,286,50,2,18,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,2357,44,11,6,17,0,370,43,1301,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42717,35,4148,12,221,3,5761,15,7472,3104,541,1507,4938];
43989
43990 // eslint-disable-next-line comma-spacing
43991 var astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,370,1,154,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,9,135,4,60,6,26,9,1014,0,2,54,8,3,82,0,12,1,19628,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,262,6,10,9,419,13,1495,6,110,6,6,9,4759,9,787719,239];
43992
43993 // This has a complexity linear to the value of the code. The
43994 // assumption is that looking up astral identifier characters is
43995 // rare.
43996 function isInAstralSet(code, set) {
43997 var pos = 0x10000;
43998 for (var i = 0; i < set.length; i += 2) {
43999 pos += set[i];
44000 if (pos > code) { return false }
44001 pos += set[i + 1];
44002 if (pos >= code) { return true }
44003 }
44004 }
44005
44006 // Test whether a given character code starts an identifier.
44007
44008 function isIdentifierStart(code, astral) {
44009 if (code < 65) { return code === 36 }
44010 if (code < 91) { return true }
44011 if (code < 97) { return code === 95 }
44012 if (code < 123) { return true }
44013 if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
44014 if (astral === false) { return false }
44015 return isInAstralSet(code, astralIdentifierStartCodes)
44016 }
44017
44018 // Test whether a given character is part of an identifier.
44019
44020 function isIdentifierChar(code, astral) {
44021 if (code < 48) { return code === 36 }
44022 if (code < 58) { return true }
44023 if (code < 65) { return false }
44024 if (code < 91) { return true }
44025 if (code < 97) { return code === 95 }
44026 if (code < 123) { return true }
44027 if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
44028 if (astral === false) { return false }
44029 return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
44030 }
44031
44032 // ## Token types
44033
44034 // The assignment of fine-grained, information-carrying type objects
44035 // allows the tokenizer to store the information it has about a
44036 // token in a way that is very cheap for the parser to look up.
44037
44038 // All token type variables start with an underscore, to make them
44039 // easy to recognize.
44040
44041 // The `beforeExpr` property is used to disambiguate between regular
44042 // expressions and divisions. It is set on all token types that can
44043 // be followed by an expression (thus, a slash after them would be a
44044 // regular expression).
44045 //
44046 // The `startsExpr` property is used to check if the token ends a
44047 // `yield` expression. It is set on all token types that either can
44048 // directly start an expression (like a quotation mark) or can
44049 // continue an expression (like the body of a string).
44050 //
44051 // `isLoop` marks a keyword as starting a loop, which is important
44052 // to know when parsing a label, in order to allow or disallow
44053 // continue jumps to that label.
44054
44055 var TokenType = function TokenType(label, conf) {
44056 if ( conf === void 0 ) conf = {};
44057
44058 this.label = label;
44059 this.keyword = conf.keyword;
44060 this.beforeExpr = !!conf.beforeExpr;
44061 this.startsExpr = !!conf.startsExpr;
44062 this.isLoop = !!conf.isLoop;
44063 this.isAssign = !!conf.isAssign;
44064 this.prefix = !!conf.prefix;
44065 this.postfix = !!conf.postfix;
44066 this.binop = conf.binop || null;
44067 this.updateContext = null;
44068 };
44069
44070 function binop(name, prec) {
44071 return new TokenType(name, {beforeExpr: true, binop: prec})
44072 }
44073 var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};
44074
44075 // Map keyword names to token types.
44076
44077 var keywords$1 = {};
44078
44079 // Succinct definitions of keyword token types
44080 function kw(name, options) {
44081 if ( options === void 0 ) options = {};
44082
44083 options.keyword = name;
44084 return keywords$1[name] = new TokenType(name, options)
44085 }
44086
44087 var types = {
44088 num: new TokenType("num", startsExpr),
44089 regexp: new TokenType("regexp", startsExpr),
44090 string: new TokenType("string", startsExpr),
44091 name: new TokenType("name", startsExpr),
44092 privateId: new TokenType("privateId", startsExpr),
44093 eof: new TokenType("eof"),
44094
44095 // Punctuation token types.
44096 bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
44097 bracketR: new TokenType("]"),
44098 braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
44099 braceR: new TokenType("}"),
44100 parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
44101 parenR: new TokenType(")"),
44102 comma: new TokenType(",", beforeExpr),
44103 semi: new TokenType(";", beforeExpr),
44104 colon: new TokenType(":", beforeExpr),
44105 dot: new TokenType("."),
44106 question: new TokenType("?", beforeExpr),
44107 questionDot: new TokenType("?."),
44108 arrow: new TokenType("=>", beforeExpr),
44109 template: new TokenType("template"),
44110 invalidTemplate: new TokenType("invalidTemplate"),
44111 ellipsis: new TokenType("...", beforeExpr),
44112 backQuote: new TokenType("`", startsExpr),
44113 dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
44114
44115 // Operators. These carry several kinds of properties to help the
44116 // parser use them properly (the presence of these properties is
44117 // what categorizes them as operators).
44118 //
44119 // `binop`, when present, specifies that this operator is a binary
44120 // operator, and will refer to its precedence.
44121 //
44122 // `prefix` and `postfix` mark the operator as a prefix or postfix
44123 // unary operator.
44124 //
44125 // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
44126 // binary operators with a very low precedence, that should result
44127 // in AssignmentExpression nodes.
44128
44129 eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
44130 assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
44131 incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
44132 prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
44133 logicalOR: binop("||", 1),
44134 logicalAND: binop("&&", 2),
44135 bitwiseOR: binop("|", 3),
44136 bitwiseXOR: binop("^", 4),
44137 bitwiseAND: binop("&", 5),
44138 equality: binop("==/!=/===/!==", 6),
44139 relational: binop("</>/<=/>=", 7),
44140 bitShift: binop("<</>>/>>>", 8),
44141 plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
44142 modulo: binop("%", 10),
44143 star: binop("*", 10),
44144 slash: binop("/", 10),
44145 starstar: new TokenType("**", {beforeExpr: true}),
44146 coalesce: binop("??", 1),
44147
44148 // Keyword token types.
44149 _break: kw("break"),
44150 _case: kw("case", beforeExpr),
44151 _catch: kw("catch"),
44152 _continue: kw("continue"),
44153 _debugger: kw("debugger"),
44154 _default: kw("default", beforeExpr),
44155 _do: kw("do", {isLoop: true, beforeExpr: true}),
44156 _else: kw("else", beforeExpr),
44157 _finally: kw("finally"),
44158 _for: kw("for", {isLoop: true}),
44159 _function: kw("function", startsExpr),
44160 _if: kw("if"),
44161 _return: kw("return", beforeExpr),
44162 _switch: kw("switch"),
44163 _throw: kw("throw", beforeExpr),
44164 _try: kw("try"),
44165 _var: kw("var"),
44166 _const: kw("const"),
44167 _while: kw("while", {isLoop: true}),
44168 _with: kw("with"),
44169 _new: kw("new", {beforeExpr: true, startsExpr: true}),
44170 _this: kw("this", startsExpr),
44171 _super: kw("super", startsExpr),
44172 _class: kw("class", startsExpr),
44173 _extends: kw("extends", beforeExpr),
44174 _export: kw("export"),
44175 _import: kw("import", startsExpr),
44176 _null: kw("null", startsExpr),
44177 _true: kw("true", startsExpr),
44178 _false: kw("false", startsExpr),
44179 _in: kw("in", {beforeExpr: true, binop: 7}),
44180 _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
44181 _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
44182 _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
44183 _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
44184 };
44185
44186 // Matches a whole line break (where CRLF is considered a single
44187 // line break). Used to count lines.
44188
44189 var lineBreak = /\r\n?|\n|\u2028|\u2029/;
44190 var lineBreakG = new RegExp(lineBreak.source, "g");
44191
44192 function isNewLine(code, ecma2019String) {
44193 return code === 10 || code === 13 || (!ecma2019String && (code === 0x2028 || code === 0x2029))
44194 }
44195
44196 var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
44197
44198 var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
44199
44200 var ref = Object.prototype;
44201 var hasOwnProperty = ref.hasOwnProperty;
44202 var toString = ref.toString;
44203
44204 // Checks if an object has a property.
44205
44206 function has(obj, propName) {
44207 return hasOwnProperty.call(obj, propName)
44208 }
44209
44210 var isArray = Array.isArray || (function (obj) { return (
44211 toString.call(obj) === "[object Array]"
44212 ); });
44213
44214 function wordsRegexp(words) {
44215 return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
44216 }
44217
44218 // These are used when `options.locations` is on, for the
44219 // `startLoc` and `endLoc` properties.
44220
44221 var Position = function Position(line, col) {
44222 this.line = line;
44223 this.column = col;
44224 };
44225
44226 Position.prototype.offset = function offset (n) {
44227 return new Position(this.line, this.column + n)
44228 };
44229
44230 var SourceLocation = function SourceLocation(p, start, end) {
44231 this.start = start;
44232 this.end = end;
44233 if (p.sourceFile !== null) { this.source = p.sourceFile; }
44234 };
44235
44236 // The `getLineInfo` function is mostly useful when the
44237 // `locations` option is off (for performance reasons) and you
44238 // want to find the line/column position for a given character
44239 // offset. `input` should be the code string that the offset refers
44240 // into.
44241
44242 function getLineInfo(input, offset) {
44243 for (var line = 1, cur = 0;;) {
44244 lineBreakG.lastIndex = cur;
44245 var match = lineBreakG.exec(input);
44246 if (match && match.index < offset) {
44247 ++line;
44248 cur = match.index + match[0].length;
44249 } else {
44250 return new Position(line, offset - cur)
44251 }
44252 }
44253 }
44254
44255 // A second argument must be given to configure the parser process.
44256 // These options are recognized (only `ecmaVersion` is required):
44257
44258 var defaultOptions = {
44259 // `ecmaVersion` indicates the ECMAScript version to parse. Must be
44260 // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
44261 // (2019), 11 (2020), 12 (2021), 13 (2022), or `"latest"` (the
44262 // latest version the library supports). This influences support
44263 // for strict mode, the set of reserved words, and support for
44264 // new syntax features.
44265 ecmaVersion: null,
44266 // `sourceType` indicates the mode the code should be parsed in.
44267 // Can be either `"script"` or `"module"`. This influences global
44268 // strict mode and parsing of `import` and `export` declarations.
44269 sourceType: "script",
44270 // `onInsertedSemicolon` can be a callback that will be called
44271 // when a semicolon is automatically inserted. It will be passed
44272 // the position of the comma as an offset, and if `locations` is
44273 // enabled, it is given the location as a `{line, column}` object
44274 // as second argument.
44275 onInsertedSemicolon: null,
44276 // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
44277 // trailing commas.
44278 onTrailingComma: null,
44279 // By default, reserved words are only enforced if ecmaVersion >= 5.
44280 // Set `allowReserved` to a boolean value to explicitly turn this on
44281 // an off. When this option has the value "never", reserved words
44282 // and keywords can also not be used as property names.
44283 allowReserved: null,
44284 // When enabled, a return at the top level is not considered an
44285 // error.
44286 allowReturnOutsideFunction: false,
44287 // When enabled, import/export statements are not constrained to
44288 // appearing at the top of the program, and an import.meta expression
44289 // in a script isn't considered an error.
44290 allowImportExportEverywhere: false,
44291 // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022.
44292 // When enabled, await identifiers are allowed to appear at the top-level scope,
44293 // but they are still not allowed in non-async functions.
44294 allowAwaitOutsideFunction: null,
44295 // When enabled, super identifiers are not constrained to
44296 // appearing in methods and do not raise an error when they appear elsewhere.
44297 allowSuperOutsideMethod: null,
44298 // When enabled, hashbang directive in the beginning of file
44299 // is allowed and treated as a line comment.
44300 allowHashBang: false,
44301 // When `locations` is on, `loc` properties holding objects with
44302 // `start` and `end` properties in `{line, column}` form (with
44303 // line being 1-based and column 0-based) will be attached to the
44304 // nodes.
44305 locations: false,
44306 // A function can be passed as `onToken` option, which will
44307 // cause Acorn to call that function with object in the same
44308 // format as tokens returned from `tokenizer().getToken()`. Note
44309 // that you are not allowed to call the parser from the
44310 // callback—that will corrupt its internal state.
44311 onToken: null,
44312 // A function can be passed as `onComment` option, which will
44313 // cause Acorn to call that function with `(block, text, start,
44314 // end)` parameters whenever a comment is skipped. `block` is a
44315 // boolean indicating whether this is a block (`/* */`) comment,
44316 // `text` is the content of the comment, and `start` and `end` are
44317 // character offsets that denote the start and end of the comment.
44318 // When the `locations` option is on, two more parameters are
44319 // passed, the full `{line, column}` locations of the start and
44320 // end of the comments. Note that you are not allowed to call the
44321 // parser from the callback—that will corrupt its internal state.
44322 onComment: null,
44323 // Nodes have their start and end characters offsets recorded in
44324 // `start` and `end` properties (directly on the node, rather than
44325 // the `loc` object, which holds line/column data. To also add a
44326 // [semi-standardized][range] `range` property holding a `[start,
44327 // end]` array with the same numbers, set the `ranges` option to
44328 // `true`.
44329 //
44330 // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
44331 ranges: false,
44332 // It is possible to parse multiple files into a single AST by
44333 // passing the tree produced by parsing the first file as
44334 // `program` option in subsequent parses. This will add the
44335 // toplevel forms of the parsed file to the `Program` (top) node
44336 // of an existing parse tree.
44337 program: null,
44338 // When `locations` is on, you can pass this to record the source
44339 // file in every node's `loc` object.
44340 sourceFile: null,
44341 // This value, if given, is stored in every node, whether
44342 // `locations` is on or off.
44343 directSourceFile: null,
44344 // When enabled, parenthesized expressions are represented by
44345 // (non-standard) ParenthesizedExpression nodes
44346 preserveParens: false
44347 };
44348
44349 // Interpret and default an options object
44350
44351 var warnedAboutEcmaVersion = false;
44352
44353 function getOptions(opts) {
44354 var options = {};
44355
44356 for (var opt in defaultOptions)
44357 { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; }
44358
44359 if (options.ecmaVersion === "latest") {
44360 options.ecmaVersion = 1e8;
44361 } else if (options.ecmaVersion == null) {
44362 if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
44363 warnedAboutEcmaVersion = true;
44364 console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
44365 }
44366 options.ecmaVersion = 11;
44367 } else if (options.ecmaVersion >= 2015) {
44368 options.ecmaVersion -= 2009;
44369 }
44370
44371 if (options.allowReserved == null)
44372 { options.allowReserved = options.ecmaVersion < 5; }
44373
44374 if (isArray(options.onToken)) {
44375 var tokens = options.onToken;
44376 options.onToken = function (token) { return tokens.push(token); };
44377 }
44378 if (isArray(options.onComment))
44379 { options.onComment = pushComment(options, options.onComment); }
44380
44381 return options
44382 }
44383
44384 function pushComment(options, array) {
44385 return function(block, text, start, end, startLoc, endLoc) {
44386 var comment = {
44387 type: block ? "Block" : "Line",
44388 value: text,
44389 start: start,
44390 end: end
44391 };
44392 if (options.locations)
44393 { comment.loc = new SourceLocation(this, startLoc, endLoc); }
44394 if (options.ranges)
44395 { comment.range = [start, end]; }
44396 array.push(comment);
44397 }
44398 }
44399
44400 // Each scope gets a bitset that may contain these flags
44401 var
44402 SCOPE_TOP = 1,
44403 SCOPE_FUNCTION = 2,
44404 SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION,
44405 SCOPE_ASYNC = 4,
44406 SCOPE_GENERATOR = 8,
44407 SCOPE_ARROW = 16,
44408 SCOPE_SIMPLE_CATCH = 32,
44409 SCOPE_SUPER = 64,
44410 SCOPE_DIRECT_SUPER = 128;
44411
44412 function functionFlags(async, generator) {
44413 return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)
44414 }
44415
44416 // Used in checkLVal* and declareName to determine the type of a binding
44417 var
44418 BIND_NONE = 0, // Not a binding
44419 BIND_VAR = 1, // Var-style binding
44420 BIND_LEXICAL = 2, // Let- or const-style binding
44421 BIND_FUNCTION = 3, // Function declaration
44422 BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding
44423 BIND_OUTSIDE = 5; // Special case for function names as bound inside the function
44424
44425 var Parser = function Parser(options, input, startPos) {
44426 this.options = options = getOptions(options);
44427 this.sourceFile = options.sourceFile;
44428 this.keywords = wordsRegexp(keywords[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
44429 var reserved = "";
44430 if (options.allowReserved !== true) {
44431 reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
44432 if (options.sourceType === "module") { reserved += " await"; }
44433 }
44434 this.reservedWords = wordsRegexp(reserved);
44435 var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
44436 this.reservedWordsStrict = wordsRegexp(reservedStrict);
44437 this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
44438 this.input = String(input);
44439
44440 // Used to signal to callers of `readWord1` whether the word
44441 // contained any escape sequences. This is needed because words with
44442 // escape sequences must not be interpreted as keywords.
44443 this.containsEsc = false;
44444
44445 // Set up token state
44446
44447 // The current position of the tokenizer in the input.
44448 if (startPos) {
44449 this.pos = startPos;
44450 this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
44451 this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
44452 } else {
44453 this.pos = this.lineStart = 0;
44454 this.curLine = 1;
44455 }
44456
44457 // Properties of the current token:
44458 // Its type
44459 this.type = types.eof;
44460 // For tokens that include more information than their type, the value
44461 this.value = null;
44462 // Its start and end offset
44463 this.start = this.end = this.pos;
44464 // And, if locations are used, the {line, column} object
44465 // corresponding to those offsets
44466 this.startLoc = this.endLoc = this.curPosition();
44467
44468 // Position information for the previous token
44469 this.lastTokEndLoc = this.lastTokStartLoc = null;
44470 this.lastTokStart = this.lastTokEnd = this.pos;
44471
44472 // The context stack is used to superficially track syntactic
44473 // context to predict whether a regular expression is allowed in a
44474 // given position.
44475 this.context = this.initialContext();
44476 this.exprAllowed = true;
44477
44478 // Figure out if it's a module code.
44479 this.inModule = options.sourceType === "module";
44480 this.strict = this.inModule || this.strictDirective(this.pos);
44481
44482 // Used to signify the start of a potential arrow function
44483 this.potentialArrowAt = -1;
44484 this.potentialArrowInForAwait = false;
44485
44486 // Positions to delayed-check that yield/await does not exist in default parameters.
44487 this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
44488 // Labels in scope.
44489 this.labels = [];
44490 // Thus-far undefined exports.
44491 this.undefinedExports = Object.create(null);
44492
44493 // If enabled, skip leading hashbang line.
44494 if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
44495 { this.skipLineComment(2); }
44496
44497 // Scope tracking for duplicate variable names (see scope.js)
44498 this.scopeStack = [];
44499 this.enterScope(SCOPE_TOP);
44500
44501 // For RegExp validation
44502 this.regexpState = null;
44503
44504 // The stack of private names.
44505 // Each element has two properties: 'declared' and 'used'.
44506 // When it exited from the outermost class definition, all used private names must be declared.
44507 this.privateNameStack = [];
44508 };
44509
44510 var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },canAwait: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },inNonArrowFunction: { configurable: true } };
44511
44512 Parser.prototype.parse = function parse () {
44513 var node = this.options.program || this.startNode();
44514 this.nextToken();
44515 return this.parseTopLevel(node)
44516 };
44517
44518 prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
44519 prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit };
44520 prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit };
44521 prototypeAccessors.canAwait.get = function () {
44522 for (var i = this.scopeStack.length - 1; i >= 0; i--) {
44523 var scope = this.scopeStack[i];
44524 if (scope.inClassFieldInit) { return false }
44525 if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 }
44526 }
44527 return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction
44528 };
44529 prototypeAccessors.allowSuper.get = function () {
44530 var ref = this.currentThisScope();
44531 var flags = ref.flags;
44532 var inClassFieldInit = ref.inClassFieldInit;
44533 return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod
44534 };
44535 prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
44536 prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };
44537 prototypeAccessors.inNonArrowFunction.get = function () {
44538 var ref = this.currentThisScope();
44539 var flags = ref.flags;
44540 var inClassFieldInit = ref.inClassFieldInit;
44541 return (flags & SCOPE_FUNCTION) > 0 || inClassFieldInit
44542 };
44543
44544 Parser.extend = function extend () {
44545 var plugins = [], len = arguments.length;
44546 while ( len-- ) plugins[ len ] = arguments[ len ];
44547
44548 var cls = this;
44549 for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }
44550 return cls
44551 };
44552
44553 Parser.parse = function parse (input, options) {
44554 return new this(options, input).parse()
44555 };
44556
44557 Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {
44558 var parser = new this(options, input, pos);
44559 parser.nextToken();
44560 return parser.parseExpression()
44561 };
44562
44563 Parser.tokenizer = function tokenizer (input, options) {
44564 return new this(options, input)
44565 };
44566
44567 Object.defineProperties( Parser.prototype, prototypeAccessors );
44568
44569 var pp = Parser.prototype;
44570
44571 // ## Parser utilities
44572
44573 var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/;
44574 pp.strictDirective = function(start) {
44575 for (;;) {
44576 // Try to find string literal.
44577 skipWhiteSpace.lastIndex = start;
44578 start += skipWhiteSpace.exec(this.input)[0].length;
44579 var match = literal.exec(this.input.slice(start));
44580 if (!match) { return false }
44581 if ((match[1] || match[2]) === "use strict") {
44582 skipWhiteSpace.lastIndex = start + match[0].length;
44583 var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
44584 var next = this.input.charAt(end);
44585 return next === ";" || next === "}" ||
44586 (lineBreak.test(spaceAfter[0]) &&
44587 !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))
44588 }
44589 start += match[0].length;
44590
44591 // Skip semicolon, if any.
44592 skipWhiteSpace.lastIndex = start;
44593 start += skipWhiteSpace.exec(this.input)[0].length;
44594 if (this.input[start] === ";")
44595 { start++; }
44596 }
44597 };
44598
44599 // Predicate that tests whether the next token is of the given
44600 // type, and if yes, consumes it as a side effect.
44601
44602 pp.eat = function(type) {
44603 if (this.type === type) {
44604 this.next();
44605 return true
44606 } else {
44607 return false
44608 }
44609 };
44610
44611 // Tests whether parsed token is a contextual keyword.
44612
44613 pp.isContextual = function(name) {
44614 return this.type === types.name && this.value === name && !this.containsEsc
44615 };
44616
44617 // Consumes contextual keyword if possible.
44618
44619 pp.eatContextual = function(name) {
44620 if (!this.isContextual(name)) { return false }
44621 this.next();
44622 return true
44623 };
44624
44625 // Asserts that following token is given contextual keyword.
44626
44627 pp.expectContextual = function(name) {
44628 if (!this.eatContextual(name)) { this.unexpected(); }
44629 };
44630
44631 // Test whether a semicolon can be inserted at the current position.
44632
44633 pp.canInsertSemicolon = function() {
44634 return this.type === types.eof ||
44635 this.type === types.braceR ||
44636 lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
44637 };
44638
44639 pp.insertSemicolon = function() {
44640 if (this.canInsertSemicolon()) {
44641 if (this.options.onInsertedSemicolon)
44642 { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
44643 return true
44644 }
44645 };
44646
44647 // Consume a semicolon, or, failing that, see if we are allowed to
44648 // pretend that there is a semicolon at this position.
44649
44650 pp.semicolon = function() {
44651 if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected(); }
44652 };
44653
44654 pp.afterTrailingComma = function(tokType, notNext) {
44655 if (this.type === tokType) {
44656 if (this.options.onTrailingComma)
44657 { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
44658 if (!notNext)
44659 { this.next(); }
44660 return true
44661 }
44662 };
44663
44664 // Expect a token of a given type. If found, consume it, otherwise,
44665 // raise an unexpected token error.
44666
44667 pp.expect = function(type) {
44668 this.eat(type) || this.unexpected();
44669 };
44670
44671 // Raise an unexpected token error.
44672
44673 pp.unexpected = function(pos) {
44674 this.raise(pos != null ? pos : this.start, "Unexpected token");
44675 };
44676
44677 function DestructuringErrors() {
44678 this.shorthandAssign =
44679 this.trailingComma =
44680 this.parenthesizedAssign =
44681 this.parenthesizedBind =
44682 this.doubleProto =
44683 -1;
44684 }
44685
44686 pp.checkPatternErrors = function(refDestructuringErrors, isAssign) {
44687 if (!refDestructuringErrors) { return }
44688 if (refDestructuringErrors.trailingComma > -1)
44689 { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
44690 var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
44691 if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); }
44692 };
44693
44694 pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
44695 if (!refDestructuringErrors) { return false }
44696 var shorthandAssign = refDestructuringErrors.shorthandAssign;
44697 var doubleProto = refDestructuringErrors.doubleProto;
44698 if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
44699 if (shorthandAssign >= 0)
44700 { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
44701 if (doubleProto >= 0)
44702 { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
44703 };
44704
44705 pp.checkYieldAwaitInDefaultParams = function() {
44706 if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
44707 { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
44708 if (this.awaitPos)
44709 { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
44710 };
44711
44712 pp.isSimpleAssignTarget = function(expr) {
44713 if (expr.type === "ParenthesizedExpression")
44714 { return this.isSimpleAssignTarget(expr.expression) }
44715 return expr.type === "Identifier" || expr.type === "MemberExpression"
44716 };
44717
44718 var pp$1 = Parser.prototype;
44719
44720 // ### Statement parsing
44721
44722 // Parse a program. Initializes the parser, reads any number of
44723 // statements, and wraps them in a Program node. Optionally takes a
44724 // `program` argument. If present, the statements will be appended
44725 // to its body instead of creating a new node.
44726
44727 pp$1.parseTopLevel = function(node) {
44728 var exports = Object.create(null);
44729 if (!node.body) { node.body = []; }
44730 while (this.type !== types.eof) {
44731 var stmt = this.parseStatement(null, true, exports);
44732 node.body.push(stmt);
44733 }
44734 if (this.inModule)
44735 { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
44736 {
44737 var name = list[i];
44738
44739 this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));
44740 } }
44741 this.adaptDirectivePrologue(node.body);
44742 this.next();
44743 node.sourceType = this.options.sourceType;
44744 return this.finishNode(node, "Program")
44745 };
44746
44747 var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
44748
44749 pp$1.isLet = function(context) {
44750 if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
44751 skipWhiteSpace.lastIndex = this.pos;
44752 var skip = skipWhiteSpace.exec(this.input);
44753 var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
44754 // For ambiguous cases, determine if a LexicalDeclaration (or only a
44755 // Statement) is allowed here. If context is not empty then only a Statement
44756 // is allowed. However, `let [` is an explicit negative lookahead for
44757 // ExpressionStatement, so special-case it first.
44758 if (nextCh === 91 || nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '[', '/', astral
44759 if (context) { return false }
44760
44761 if (nextCh === 123) { return true } // '{'
44762 if (isIdentifierStart(nextCh, true)) {
44763 var pos = next + 1;
44764 while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; }
44765 if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true }
44766 var ident = this.input.slice(next, pos);
44767 if (!keywordRelationalOperator.test(ident)) { return true }
44768 }
44769 return false
44770 };
44771
44772 // check 'async [no LineTerminator here] function'
44773 // - 'async /*foo*/ function' is OK.
44774 // - 'async /*\n*/ function' is invalid.
44775 pp$1.isAsyncFunction = function() {
44776 if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
44777 { return false }
44778
44779 skipWhiteSpace.lastIndex = this.pos;
44780 var skip = skipWhiteSpace.exec(this.input);
44781 var next = this.pos + skip[0].length, after;
44782 return !lineBreak.test(this.input.slice(this.pos, next)) &&
44783 this.input.slice(next, next + 8) === "function" &&
44784 (next + 8 === this.input.length ||
44785 !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00))
44786 };
44787
44788 // Parse a single statement.
44789 //
44790 // If expecting a statement and finding a slash operator, parse a
44791 // regular expression literal. This is to handle cases like
44792 // `if (foo) /blah/.exec(foo)`, where looking at the previous token
44793 // does not help.
44794
44795 pp$1.parseStatement = function(context, topLevel, exports) {
44796 var starttype = this.type, node = this.startNode(), kind;
44797
44798 if (this.isLet(context)) {
44799 starttype = types._var;
44800 kind = "let";
44801 }
44802
44803 // Most types of statements are recognized by the keyword they
44804 // start with. Many are trivial to parse, some require a bit of
44805 // complexity.
44806
44807 switch (starttype) {
44808 case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
44809 case types._debugger: return this.parseDebuggerStatement(node)
44810 case types._do: return this.parseDoStatement(node)
44811 case types._for: return this.parseForStatement(node)
44812 case types._function:
44813 // Function as sole body of either an if statement or a labeled statement
44814 // works, but not when it is part of a labeled statement that is the sole
44815 // body of an if statement.
44816 if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }
44817 return this.parseFunctionStatement(node, false, !context)
44818 case types._class:
44819 if (context) { this.unexpected(); }
44820 return this.parseClass(node, true)
44821 case types._if: return this.parseIfStatement(node)
44822 case types._return: return this.parseReturnStatement(node)
44823 case types._switch: return this.parseSwitchStatement(node)
44824 case types._throw: return this.parseThrowStatement(node)
44825 case types._try: return this.parseTryStatement(node)
44826 case types._const: case types._var:
44827 kind = kind || this.value;
44828 if (context && kind !== "var") { this.unexpected(); }
44829 return this.parseVarStatement(node, kind)
44830 case types._while: return this.parseWhileStatement(node)
44831 case types._with: return this.parseWithStatement(node)
44832 case types.braceL: return this.parseBlock(true, node)
44833 case types.semi: return this.parseEmptyStatement(node)
44834 case types._export:
44835 case types._import:
44836 if (this.options.ecmaVersion > 10 && starttype === types._import) {
44837 skipWhiteSpace.lastIndex = this.pos;
44838 var skip = skipWhiteSpace.exec(this.input);
44839 var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
44840 if (nextCh === 40 || nextCh === 46) // '(' or '.'
44841 { return this.parseExpressionStatement(node, this.parseExpression()) }
44842 }
44843
44844 if (!this.options.allowImportExportEverywhere) {
44845 if (!topLevel)
44846 { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
44847 if (!this.inModule)
44848 { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
44849 }
44850 return starttype === types._import ? this.parseImport(node) : this.parseExport(node, exports)
44851
44852 // If the statement does not start with a statement keyword or a
44853 // brace, it's an ExpressionStatement or LabeledStatement. We
44854 // simply start parsing an expression, and afterwards, if the
44855 // next token is a colon and the expression was a simple
44856 // Identifier node, we switch to interpreting it as a label.
44857 default:
44858 if (this.isAsyncFunction()) {
44859 if (context) { this.unexpected(); }
44860 this.next();
44861 return this.parseFunctionStatement(node, true, !context)
44862 }
44863
44864 var maybeName = this.value, expr = this.parseExpression();
44865 if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon))
44866 { return this.parseLabeledStatement(node, maybeName, expr, context) }
44867 else { return this.parseExpressionStatement(node, expr) }
44868 }
44869 };
44870
44871 pp$1.parseBreakContinueStatement = function(node, keyword) {
44872 var isBreak = keyword === "break";
44873 this.next();
44874 if (this.eat(types.semi) || this.insertSemicolon()) { node.label = null; }
44875 else if (this.type !== types.name) { this.unexpected(); }
44876 else {
44877 node.label = this.parseIdent();
44878 this.semicolon();
44879 }
44880
44881 // Verify that there is an actual destination to break or
44882 // continue to.
44883 var i = 0;
44884 for (; i < this.labels.length; ++i) {
44885 var lab = this.labels[i];
44886 if (node.label == null || lab.name === node.label.name) {
44887 if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
44888 if (node.label && isBreak) { break }
44889 }
44890 }
44891 if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
44892 return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
44893 };
44894
44895 pp$1.parseDebuggerStatement = function(node) {
44896 this.next();
44897 this.semicolon();
44898 return this.finishNode(node, "DebuggerStatement")
44899 };
44900
44901 pp$1.parseDoStatement = function(node) {
44902 this.next();
44903 this.labels.push(loopLabel);
44904 node.body = this.parseStatement("do");
44905 this.labels.pop();
44906 this.expect(types._while);
44907 node.test = this.parseParenExpression();
44908 if (this.options.ecmaVersion >= 6)
44909 { this.eat(types.semi); }
44910 else
44911 { this.semicolon(); }
44912 return this.finishNode(node, "DoWhileStatement")
44913 };
44914
44915 // Disambiguating between a `for` and a `for`/`in` or `for`/`of`
44916 // loop is non-trivial. Basically, we have to parse the init `var`
44917 // statement or expression, disallowing the `in` operator (see
44918 // the second parameter to `parseExpression`), and then check
44919 // whether the next token is `in` or `of`. When there is no init
44920 // part (semicolon immediately after the opening parenthesis), it
44921 // is a regular `for` loop.
44922
44923 pp$1.parseForStatement = function(node) {
44924 this.next();
44925 var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1;
44926 this.labels.push(loopLabel);
44927 this.enterScope(0);
44928 this.expect(types.parenL);
44929 if (this.type === types.semi) {
44930 if (awaitAt > -1) { this.unexpected(awaitAt); }
44931 return this.parseFor(node, null)
44932 }
44933 var isLet = this.isLet();
44934 if (this.type === types._var || this.type === types._const || isLet) {
44935 var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
44936 this.next();
44937 this.parseVar(init$1, true, kind);
44938 this.finishNode(init$1, "VariableDeclaration");
44939 if ((this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {
44940 if (this.options.ecmaVersion >= 9) {
44941 if (this.type === types._in) {
44942 if (awaitAt > -1) { this.unexpected(awaitAt); }
44943 } else { node.await = awaitAt > -1; }
44944 }
44945 return this.parseForIn(node, init$1)
44946 }
44947 if (awaitAt > -1) { this.unexpected(awaitAt); }
44948 return this.parseFor(node, init$1)
44949 }
44950 var refDestructuringErrors = new DestructuringErrors;
44951 var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors);
44952 if (this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
44953 if (this.options.ecmaVersion >= 9) {
44954 if (this.type === types._in) {
44955 if (awaitAt > -1) { this.unexpected(awaitAt); }
44956 } else { node.await = awaitAt > -1; }
44957 }
44958 this.toAssignable(init, false, refDestructuringErrors);
44959 this.checkLValPattern(init);
44960 return this.parseForIn(node, init)
44961 } else {
44962 this.checkExpressionErrors(refDestructuringErrors, true);
44963 }
44964 if (awaitAt > -1) { this.unexpected(awaitAt); }
44965 return this.parseFor(node, init)
44966 };
44967
44968 pp$1.parseFunctionStatement = function(node, isAsync, declarationPosition) {
44969 this.next();
44970 return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
44971 };
44972
44973 pp$1.parseIfStatement = function(node) {
44974 this.next();
44975 node.test = this.parseParenExpression();
44976 // allow function declarations in branches, but only in non-strict mode
44977 node.consequent = this.parseStatement("if");
44978 node.alternate = this.eat(types._else) ? this.parseStatement("if") : null;
44979 return this.finishNode(node, "IfStatement")
44980 };
44981
44982 pp$1.parseReturnStatement = function(node) {
44983 if (!this.inFunction && !this.options.allowReturnOutsideFunction)
44984 { this.raise(this.start, "'return' outside of function"); }
44985 this.next();
44986
44987 // In `return` (and `break`/`continue`), the keywords with
44988 // optional arguments, we eagerly look for a semicolon or the
44989 // possibility to insert one.
44990
44991 if (this.eat(types.semi) || this.insertSemicolon()) { node.argument = null; }
44992 else { node.argument = this.parseExpression(); this.semicolon(); }
44993 return this.finishNode(node, "ReturnStatement")
44994 };
44995
44996 pp$1.parseSwitchStatement = function(node) {
44997 this.next();
44998 node.discriminant = this.parseParenExpression();
44999 node.cases = [];
45000 this.expect(types.braceL);
45001 this.labels.push(switchLabel);
45002 this.enterScope(0);
45003
45004 // Statements under must be grouped (by label) in SwitchCase
45005 // nodes. `cur` is used to keep the node that we are currently
45006 // adding statements to.
45007
45008 var cur;
45009 for (var sawDefault = false; this.type !== types.braceR;) {
45010 if (this.type === types._case || this.type === types._default) {
45011 var isCase = this.type === types._case;
45012 if (cur) { this.finishNode(cur, "SwitchCase"); }
45013 node.cases.push(cur = this.startNode());
45014 cur.consequent = [];
45015 this.next();
45016 if (isCase) {
45017 cur.test = this.parseExpression();
45018 } else {
45019 if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }
45020 sawDefault = true;
45021 cur.test = null;
45022 }
45023 this.expect(types.colon);
45024 } else {
45025 if (!cur) { this.unexpected(); }
45026 cur.consequent.push(this.parseStatement(null));
45027 }
45028 }
45029 this.exitScope();
45030 if (cur) { this.finishNode(cur, "SwitchCase"); }
45031 this.next(); // Closing brace
45032 this.labels.pop();
45033 return this.finishNode(node, "SwitchStatement")
45034 };
45035
45036 pp$1.parseThrowStatement = function(node) {
45037 this.next();
45038 if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
45039 { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
45040 node.argument = this.parseExpression();
45041 this.semicolon();
45042 return this.finishNode(node, "ThrowStatement")
45043 };
45044
45045 // Reused empty array added for node fields that are always empty.
45046
45047 var empty = [];
45048
45049 pp$1.parseTryStatement = function(node) {
45050 this.next();
45051 node.block = this.parseBlock();
45052 node.handler = null;
45053 if (this.type === types._catch) {
45054 var clause = this.startNode();
45055 this.next();
45056 if (this.eat(types.parenL)) {
45057 clause.param = this.parseBindingAtom();
45058 var simple = clause.param.type === "Identifier";
45059 this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
45060 this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
45061 this.expect(types.parenR);
45062 } else {
45063 if (this.options.ecmaVersion < 10) { this.unexpected(); }
45064 clause.param = null;
45065 this.enterScope(0);
45066 }
45067 clause.body = this.parseBlock(false);
45068 this.exitScope();
45069 node.handler = this.finishNode(clause, "CatchClause");
45070 }
45071 node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;
45072 if (!node.handler && !node.finalizer)
45073 { this.raise(node.start, "Missing catch or finally clause"); }
45074 return this.finishNode(node, "TryStatement")
45075 };
45076
45077 pp$1.parseVarStatement = function(node, kind) {
45078 this.next();
45079 this.parseVar(node, false, kind);
45080 this.semicolon();
45081 return this.finishNode(node, "VariableDeclaration")
45082 };
45083
45084 pp$1.parseWhileStatement = function(node) {
45085 this.next();
45086 node.test = this.parseParenExpression();
45087 this.labels.push(loopLabel);
45088 node.body = this.parseStatement("while");
45089 this.labels.pop();
45090 return this.finishNode(node, "WhileStatement")
45091 };
45092
45093 pp$1.parseWithStatement = function(node) {
45094 if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
45095 this.next();
45096 node.object = this.parseParenExpression();
45097 node.body = this.parseStatement("with");
45098 return this.finishNode(node, "WithStatement")
45099 };
45100
45101 pp$1.parseEmptyStatement = function(node) {
45102 this.next();
45103 return this.finishNode(node, "EmptyStatement")
45104 };
45105
45106 pp$1.parseLabeledStatement = function(node, maybeName, expr, context) {
45107 for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)
45108 {
45109 var label = list[i$1];
45110
45111 if (label.name === maybeName)
45112 { this.raise(expr.start, "Label '" + maybeName + "' is already declared");
45113 } }
45114 var kind = this.type.isLoop ? "loop" : this.type === types._switch ? "switch" : null;
45115 for (var i = this.labels.length - 1; i >= 0; i--) {
45116 var label$1 = this.labels[i];
45117 if (label$1.statementStart === node.start) {
45118 // Update information about previous labels on this node
45119 label$1.statementStart = this.start;
45120 label$1.kind = kind;
45121 } else { break }
45122 }
45123 this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
45124 node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
45125 this.labels.pop();
45126 node.label = expr;
45127 return this.finishNode(node, "LabeledStatement")
45128 };
45129
45130 pp$1.parseExpressionStatement = function(node, expr) {
45131 node.expression = expr;
45132 this.semicolon();
45133 return this.finishNode(node, "ExpressionStatement")
45134 };
45135
45136 // Parse a semicolon-enclosed block of statements, handling `"use
45137 // strict"` declarations when `allowStrict` is true (used for
45138 // function bodies).
45139
45140 pp$1.parseBlock = function(createNewLexicalScope, node, exitStrict) {
45141 if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
45142 if ( node === void 0 ) node = this.startNode();
45143
45144 node.body = [];
45145 this.expect(types.braceL);
45146 if (createNewLexicalScope) { this.enterScope(0); }
45147 while (this.type !== types.braceR) {
45148 var stmt = this.parseStatement(null);
45149 node.body.push(stmt);
45150 }
45151 if (exitStrict) { this.strict = false; }
45152 this.next();
45153 if (createNewLexicalScope) { this.exitScope(); }
45154 return this.finishNode(node, "BlockStatement")
45155 };
45156
45157 // Parse a regular `for` loop. The disambiguation code in
45158 // `parseStatement` will already have parsed the init statement or
45159 // expression.
45160
45161 pp$1.parseFor = function(node, init) {
45162 node.init = init;
45163 this.expect(types.semi);
45164 node.test = this.type === types.semi ? null : this.parseExpression();
45165 this.expect(types.semi);
45166 node.update = this.type === types.parenR ? null : this.parseExpression();
45167 this.expect(types.parenR);
45168 node.body = this.parseStatement("for");
45169 this.exitScope();
45170 this.labels.pop();
45171 return this.finishNode(node, "ForStatement")
45172 };
45173
45174 // Parse a `for`/`in` and `for`/`of` loop, which are almost
45175 // same from parser's perspective.
45176
45177 pp$1.parseForIn = function(node, init) {
45178 var isForIn = this.type === types._in;
45179 this.next();
45180
45181 if (
45182 init.type === "VariableDeclaration" &&
45183 init.declarations[0].init != null &&
45184 (
45185 !isForIn ||
45186 this.options.ecmaVersion < 8 ||
45187 this.strict ||
45188 init.kind !== "var" ||
45189 init.declarations[0].id.type !== "Identifier"
45190 )
45191 ) {
45192 this.raise(
45193 init.start,
45194 ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
45195 );
45196 }
45197 node.left = init;
45198 node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
45199 this.expect(types.parenR);
45200 node.body = this.parseStatement("for");
45201 this.exitScope();
45202 this.labels.pop();
45203 return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
45204 };
45205
45206 // Parse a list of variable declarations.
45207
45208 pp$1.parseVar = function(node, isFor, kind) {
45209 node.declarations = [];
45210 node.kind = kind;
45211 for (;;) {
45212 var decl = this.startNode();
45213 this.parseVarId(decl, kind);
45214 if (this.eat(types.eq)) {
45215 decl.init = this.parseMaybeAssign(isFor);
45216 } else if (kind === "const" && !(this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
45217 this.unexpected();
45218 } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types._in || this.isContextual("of")))) {
45219 this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
45220 } else {
45221 decl.init = null;
45222 }
45223 node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
45224 if (!this.eat(types.comma)) { break }
45225 }
45226 return node
45227 };
45228
45229 pp$1.parseVarId = function(decl, kind) {
45230 decl.id = this.parseBindingAtom();
45231 this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
45232 };
45233
45234 var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;
45235
45236 // Parse a function declaration or literal (depending on the
45237 // `statement & FUNC_STATEMENT`).
45238
45239 // Remove `allowExpressionBody` for 7.0.0, as it is only called with false
45240 pp$1.parseFunction = function(node, statement, allowExpressionBody, isAsync) {
45241 this.initFunction(node);
45242 if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
45243 if (this.type === types.star && (statement & FUNC_HANGING_STATEMENT))
45244 { this.unexpected(); }
45245 node.generator = this.eat(types.star);
45246 }
45247 if (this.options.ecmaVersion >= 8)
45248 { node.async = !!isAsync; }
45249
45250 if (statement & FUNC_STATEMENT) {
45251 node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types.name ? null : this.parseIdent();
45252 if (node.id && !(statement & FUNC_HANGING_STATEMENT))
45253 // If it is a regular function declaration in sloppy mode, then it is
45254 // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
45255 // mode depends on properties of the current scope (see
45256 // treatFunctionsAsVar).
45257 { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }
45258 }
45259
45260 var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
45261 this.yieldPos = 0;
45262 this.awaitPos = 0;
45263 this.awaitIdentPos = 0;
45264 this.enterScope(functionFlags(node.async, node.generator));
45265
45266 if (!(statement & FUNC_STATEMENT))
45267 { node.id = this.type === types.name ? this.parseIdent() : null; }
45268
45269 this.parseFunctionParams(node);
45270 this.parseFunctionBody(node, allowExpressionBody, false);
45271
45272 this.yieldPos = oldYieldPos;
45273 this.awaitPos = oldAwaitPos;
45274 this.awaitIdentPos = oldAwaitIdentPos;
45275 return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression")
45276 };
45277
45278 pp$1.parseFunctionParams = function(node) {
45279 this.expect(types.parenL);
45280 node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
45281 this.checkYieldAwaitInDefaultParams();
45282 };
45283
45284 // Parse a class declaration or literal (depending on the
45285 // `isStatement` parameter).
45286
45287 pp$1.parseClass = function(node, isStatement) {
45288 this.next();
45289
45290 // ecma-262 14.6 Class Definitions
45291 // A class definition is always strict mode code.
45292 var oldStrict = this.strict;
45293 this.strict = true;
45294
45295 this.parseClassId(node, isStatement);
45296 this.parseClassSuper(node);
45297 var privateNameMap = this.enterClassBody();
45298 var classBody = this.startNode();
45299 var hadConstructor = false;
45300 classBody.body = [];
45301 this.expect(types.braceL);
45302 while (this.type !== types.braceR) {
45303 var element = this.parseClassElement(node.superClass !== null);
45304 if (element) {
45305 classBody.body.push(element);
45306 if (element.type === "MethodDefinition" && element.kind === "constructor") {
45307 if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); }
45308 hadConstructor = true;
45309 } else if (element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) {
45310 this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared"));
45311 }
45312 }
45313 }
45314 this.strict = oldStrict;
45315 this.next();
45316 node.body = this.finishNode(classBody, "ClassBody");
45317 this.exitClassBody();
45318 return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
45319 };
45320
45321 pp$1.parseClassElement = function(constructorAllowsSuper) {
45322 if (this.eat(types.semi)) { return null }
45323
45324 var ecmaVersion = this.options.ecmaVersion;
45325 var node = this.startNode();
45326 var keyName = "";
45327 var isGenerator = false;
45328 var isAsync = false;
45329 var kind = "method";
45330
45331 // Parse modifiers
45332 node.static = false;
45333 if (this.eatContextual("static")) {
45334 if (this.isClassElementNameStart() || this.type === types.star) {
45335 node.static = true;
45336 } else {
45337 keyName = "static";
45338 }
45339 }
45340 if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) {
45341 if ((this.isClassElementNameStart() || this.type === types.star) && !this.canInsertSemicolon()) {
45342 isAsync = true;
45343 } else {
45344 keyName = "async";
45345 }
45346 }
45347 if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types.star)) {
45348 isGenerator = true;
45349 }
45350 if (!keyName && !isAsync && !isGenerator) {
45351 var lastValue = this.value;
45352 if (this.eatContextual("get") || this.eatContextual("set")) {
45353 if (this.isClassElementNameStart()) {
45354 kind = lastValue;
45355 } else {
45356 keyName = lastValue;
45357 }
45358 }
45359 }
45360
45361 // Parse element name
45362 if (keyName) {
45363 // 'async', 'get', 'set', or 'static' were not a keyword contextually.
45364 // The last token is any of those. Make it the element name.
45365 node.computed = false;
45366 node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);
45367 node.key.name = keyName;
45368 this.finishNode(node.key, "Identifier");
45369 } else {
45370 this.parseClassElementName(node);
45371 }
45372
45373 // Parse element value
45374 if (ecmaVersion < 13 || this.type === types.parenL || kind !== "method" || isGenerator || isAsync) {
45375 var isConstructor = !node.static && checkKeyName(node, "constructor");
45376 var allowsDirectSuper = isConstructor && constructorAllowsSuper;
45377 // Couldn't move this check into the 'parseClassMethod' method for backward compatibility.
45378 if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); }
45379 node.kind = isConstructor ? "constructor" : kind;
45380 this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper);
45381 } else {
45382 this.parseClassField(node);
45383 }
45384
45385 return node
45386 };
45387
45388 pp$1.isClassElementNameStart = function() {
45389 return (
45390 this.type === types.name ||
45391 this.type === types.privateId ||
45392 this.type === types.num ||
45393 this.type === types.string ||
45394 this.type === types.bracketL ||
45395 this.type.keyword
45396 )
45397 };
45398
45399 pp$1.parseClassElementName = function(element) {
45400 if (this.type === types.privateId) {
45401 if (this.value === "constructor") {
45402 this.raise(this.start, "Classes can't have an element named '#constructor'");
45403 }
45404 element.computed = false;
45405 element.key = this.parsePrivateIdent();
45406 } else {
45407 this.parsePropertyName(element);
45408 }
45409 };
45410
45411 pp$1.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
45412 // Check key and flags
45413 var key = method.key;
45414 if (method.kind === "constructor") {
45415 if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
45416 if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
45417 } else if (method.static && checkKeyName(method, "prototype")) {
45418 this.raise(key.start, "Classes may not have a static property named prototype");
45419 }
45420
45421 // Parse value
45422 var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
45423
45424 // Check value
45425 if (method.kind === "get" && value.params.length !== 0)
45426 { this.raiseRecoverable(value.start, "getter should have no params"); }
45427 if (method.kind === "set" && value.params.length !== 1)
45428 { this.raiseRecoverable(value.start, "setter should have exactly one param"); }
45429 if (method.kind === "set" && value.params[0].type === "RestElement")
45430 { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); }
45431
45432 return this.finishNode(method, "MethodDefinition")
45433 };
45434
45435 pp$1.parseClassField = function(field) {
45436 if (checkKeyName(field, "constructor")) {
45437 this.raise(field.key.start, "Classes can't have a field named 'constructor'");
45438 } else if (field.static && checkKeyName(field, "prototype")) {
45439 this.raise(field.key.start, "Classes can't have a static field named 'prototype'");
45440 }
45441
45442 if (this.eat(types.eq)) {
45443 // To raise SyntaxError if 'arguments' exists in the initializer.
45444 var scope = this.currentThisScope();
45445 var inClassFieldInit = scope.inClassFieldInit;
45446 scope.inClassFieldInit = true;
45447 field.value = this.parseMaybeAssign();
45448 scope.inClassFieldInit = inClassFieldInit;
45449 } else {
45450 field.value = null;
45451 }
45452 this.semicolon();
45453
45454 return this.finishNode(field, "PropertyDefinition")
45455 };
45456
45457 pp$1.parseClassId = function(node, isStatement) {
45458 if (this.type === types.name) {
45459 node.id = this.parseIdent();
45460 if (isStatement)
45461 { this.checkLValSimple(node.id, BIND_LEXICAL, false); }
45462 } else {
45463 if (isStatement === true)
45464 { this.unexpected(); }
45465 node.id = null;
45466 }
45467 };
45468
45469 pp$1.parseClassSuper = function(node) {
45470 node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;
45471 };
45472
45473 pp$1.enterClassBody = function() {
45474 var element = {declared: Object.create(null), used: []};
45475 this.privateNameStack.push(element);
45476 return element.declared
45477 };
45478
45479 pp$1.exitClassBody = function() {
45480 var ref = this.privateNameStack.pop();
45481 var declared = ref.declared;
45482 var used = ref.used;
45483 var len = this.privateNameStack.length;
45484 var parent = len === 0 ? null : this.privateNameStack[len - 1];
45485 for (var i = 0; i < used.length; ++i) {
45486 var id = used[i];
45487 if (!has(declared, id.name)) {
45488 if (parent) {
45489 parent.used.push(id);
45490 } else {
45491 this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class"));
45492 }
45493 }
45494 }
45495 };
45496
45497 function isPrivateNameConflicted(privateNameMap, element) {
45498 var name = element.key.name;
45499 var curr = privateNameMap[name];
45500
45501 var next = "true";
45502 if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
45503 next = (element.static ? "s" : "i") + element.kind;
45504 }
45505
45506 // `class { get #a(){}; static set #a(_){} }` is also conflict.
45507 if (
45508 curr === "iget" && next === "iset" ||
45509 curr === "iset" && next === "iget" ||
45510 curr === "sget" && next === "sset" ||
45511 curr === "sset" && next === "sget"
45512 ) {
45513 privateNameMap[name] = "true";
45514 return false
45515 } else if (!curr) {
45516 privateNameMap[name] = next;
45517 return false
45518 } else {
45519 return true
45520 }
45521 }
45522
45523 function checkKeyName(node, name) {
45524 var computed = node.computed;
45525 var key = node.key;
45526 return !computed && (
45527 key.type === "Identifier" && key.name === name ||
45528 key.type === "Literal" && key.value === name
45529 )
45530 }
45531
45532 // Parses module export declaration.
45533
45534 pp$1.parseExport = function(node, exports) {
45535 this.next();
45536 // export * from '...'
45537 if (this.eat(types.star)) {
45538 if (this.options.ecmaVersion >= 11) {
45539 if (this.eatContextual("as")) {
45540 node.exported = this.parseIdent(true);
45541 this.checkExport(exports, node.exported.name, this.lastTokStart);
45542 } else {
45543 node.exported = null;
45544 }
45545 }
45546 this.expectContextual("from");
45547 if (this.type !== types.string) { this.unexpected(); }
45548 node.source = this.parseExprAtom();
45549 this.semicolon();
45550 return this.finishNode(node, "ExportAllDeclaration")
45551 }
45552 if (this.eat(types._default)) { // export default ...
45553 this.checkExport(exports, "default", this.lastTokStart);
45554 var isAsync;
45555 if (this.type === types._function || (isAsync = this.isAsyncFunction())) {
45556 var fNode = this.startNode();
45557 this.next();
45558 if (isAsync) { this.next(); }
45559 node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
45560 } else if (this.type === types._class) {
45561 var cNode = this.startNode();
45562 node.declaration = this.parseClass(cNode, "nullableID");
45563 } else {
45564 node.declaration = this.parseMaybeAssign();
45565 this.semicolon();
45566 }
45567 return this.finishNode(node, "ExportDefaultDeclaration")
45568 }
45569 // export var|const|let|function|class ...
45570 if (this.shouldParseExportStatement()) {
45571 node.declaration = this.parseStatement(null);
45572 if (node.declaration.type === "VariableDeclaration")
45573 { this.checkVariableExport(exports, node.declaration.declarations); }
45574 else
45575 { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); }
45576 node.specifiers = [];
45577 node.source = null;
45578 } else { // export { x, y as z } [from '...']
45579 node.declaration = null;
45580 node.specifiers = this.parseExportSpecifiers(exports);
45581 if (this.eatContextual("from")) {
45582 if (this.type !== types.string) { this.unexpected(); }
45583 node.source = this.parseExprAtom();
45584 } else {
45585 for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
45586 // check for keywords used as local names
45587 var spec = list[i];
45588
45589 this.checkUnreserved(spec.local);
45590 // check if export is defined
45591 this.checkLocalExport(spec.local);
45592 }
45593
45594 node.source = null;
45595 }
45596 this.semicolon();
45597 }
45598 return this.finishNode(node, "ExportNamedDeclaration")
45599 };
45600
45601 pp$1.checkExport = function(exports, name, pos) {
45602 if (!exports) { return }
45603 if (has(exports, name))
45604 { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
45605 exports[name] = true;
45606 };
45607
45608 pp$1.checkPatternExport = function(exports, pat) {
45609 var type = pat.type;
45610 if (type === "Identifier")
45611 { this.checkExport(exports, pat.name, pat.start); }
45612 else if (type === "ObjectPattern")
45613 { for (var i = 0, list = pat.properties; i < list.length; i += 1)
45614 {
45615 var prop = list[i];
45616
45617 this.checkPatternExport(exports, prop);
45618 } }
45619 else if (type === "ArrayPattern")
45620 { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
45621 var elt = list$1[i$1];
45622
45623 if (elt) { this.checkPatternExport(exports, elt); }
45624 } }
45625 else if (type === "Property")
45626 { this.checkPatternExport(exports, pat.value); }
45627 else if (type === "AssignmentPattern")
45628 { this.checkPatternExport(exports, pat.left); }
45629 else if (type === "RestElement")
45630 { this.checkPatternExport(exports, pat.argument); }
45631 else if (type === "ParenthesizedExpression")
45632 { this.checkPatternExport(exports, pat.expression); }
45633 };
45634
45635 pp$1.checkVariableExport = function(exports, decls) {
45636 if (!exports) { return }
45637 for (var i = 0, list = decls; i < list.length; i += 1)
45638 {
45639 var decl = list[i];
45640
45641 this.checkPatternExport(exports, decl.id);
45642 }
45643 };
45644
45645 pp$1.shouldParseExportStatement = function() {
45646 return this.type.keyword === "var" ||
45647 this.type.keyword === "const" ||
45648 this.type.keyword === "class" ||
45649 this.type.keyword === "function" ||
45650 this.isLet() ||
45651 this.isAsyncFunction()
45652 };
45653
45654 // Parses a comma-separated list of module exports.
45655
45656 pp$1.parseExportSpecifiers = function(exports) {
45657 var nodes = [], first = true;
45658 // export { x, y as z } [from '...']
45659 this.expect(types.braceL);
45660 while (!this.eat(types.braceR)) {
45661 if (!first) {
45662 this.expect(types.comma);
45663 if (this.afterTrailingComma(types.braceR)) { break }
45664 } else { first = false; }
45665
45666 var node = this.startNode();
45667 node.local = this.parseIdent(true);
45668 node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local;
45669 this.checkExport(exports, node.exported.name, node.exported.start);
45670 nodes.push(this.finishNode(node, "ExportSpecifier"));
45671 }
45672 return nodes
45673 };
45674
45675 // Parses import declaration.
45676
45677 pp$1.parseImport = function(node) {
45678 this.next();
45679 // import '...'
45680 if (this.type === types.string) {
45681 node.specifiers = empty;
45682 node.source = this.parseExprAtom();
45683 } else {
45684 node.specifiers = this.parseImportSpecifiers();
45685 this.expectContextual("from");
45686 node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected();
45687 }
45688 this.semicolon();
45689 return this.finishNode(node, "ImportDeclaration")
45690 };
45691
45692 // Parses a comma-separated list of module imports.
45693
45694 pp$1.parseImportSpecifiers = function() {
45695 var nodes = [], first = true;
45696 if (this.type === types.name) {
45697 // import defaultObj, { x, y as z } from '...'
45698 var node = this.startNode();
45699 node.local = this.parseIdent();
45700 this.checkLValSimple(node.local, BIND_LEXICAL);
45701 nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
45702 if (!this.eat(types.comma)) { return nodes }
45703 }
45704 if (this.type === types.star) {
45705 var node$1 = this.startNode();
45706 this.next();
45707 this.expectContextual("as");
45708 node$1.local = this.parseIdent();
45709 this.checkLValSimple(node$1.local, BIND_LEXICAL);
45710 nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
45711 return nodes
45712 }
45713 this.expect(types.braceL);
45714 while (!this.eat(types.braceR)) {
45715 if (!first) {
45716 this.expect(types.comma);
45717 if (this.afterTrailingComma(types.braceR)) { break }
45718 } else { first = false; }
45719
45720 var node$2 = this.startNode();
45721 node$2.imported = this.parseIdent(true);
45722 if (this.eatContextual("as")) {
45723 node$2.local = this.parseIdent();
45724 } else {
45725 this.checkUnreserved(node$2.imported);
45726 node$2.local = node$2.imported;
45727 }
45728 this.checkLValSimple(node$2.local, BIND_LEXICAL);
45729 nodes.push(this.finishNode(node$2, "ImportSpecifier"));
45730 }
45731 return nodes
45732 };
45733
45734 // Set `ExpressionStatement#directive` property for directive prologues.
45735 pp$1.adaptDirectivePrologue = function(statements) {
45736 for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
45737 statements[i].directive = statements[i].expression.raw.slice(1, -1);
45738 }
45739 };
45740 pp$1.isDirectiveCandidate = function(statement) {
45741 return (
45742 statement.type === "ExpressionStatement" &&
45743 statement.expression.type === "Literal" &&
45744 typeof statement.expression.value === "string" &&
45745 // Reject parenthesized strings.
45746 (this.input[statement.start] === "\"" || this.input[statement.start] === "'")
45747 )
45748 };
45749
45750 var pp$2 = Parser.prototype;
45751
45752 // Convert existing expression atom to assignable pattern
45753 // if possible.
45754
45755 pp$2.toAssignable = function(node, isBinding, refDestructuringErrors) {
45756 if (this.options.ecmaVersion >= 6 && node) {
45757 switch (node.type) {
45758 case "Identifier":
45759 if (this.inAsync && node.name === "await")
45760 { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }
45761 break
45762
45763 case "ObjectPattern":
45764 case "ArrayPattern":
45765 case "AssignmentPattern":
45766 case "RestElement":
45767 break
45768
45769 case "ObjectExpression":
45770 node.type = "ObjectPattern";
45771 if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
45772 for (var i = 0, list = node.properties; i < list.length; i += 1) {
45773 var prop = list[i];
45774
45775 this.toAssignable(prop, isBinding);
45776 // Early error:
45777 // AssignmentRestProperty[Yield, Await] :
45778 // `...` DestructuringAssignmentTarget[Yield, Await]
45779 //
45780 // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
45781 if (
45782 prop.type === "RestElement" &&
45783 (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
45784 ) {
45785 this.raise(prop.argument.start, "Unexpected token");
45786 }
45787 }
45788 break
45789
45790 case "Property":
45791 // AssignmentProperty has type === "Property"
45792 if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
45793 this.toAssignable(node.value, isBinding);
45794 break
45795
45796 case "ArrayExpression":
45797 node.type = "ArrayPattern";
45798 if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
45799 this.toAssignableList(node.elements, isBinding);
45800 break
45801
45802 case "SpreadElement":
45803 node.type = "RestElement";
45804 this.toAssignable(node.argument, isBinding);
45805 if (node.argument.type === "AssignmentPattern")
45806 { this.raise(node.argument.start, "Rest elements cannot have a default value"); }
45807 break
45808
45809 case "AssignmentExpression":
45810 if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
45811 node.type = "AssignmentPattern";
45812 delete node.operator;
45813 this.toAssignable(node.left, isBinding);
45814 break
45815
45816 case "ParenthesizedExpression":
45817 this.toAssignable(node.expression, isBinding, refDestructuringErrors);
45818 break
45819
45820 case "ChainExpression":
45821 this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
45822 break
45823
45824 case "MemberExpression":
45825 if (!isBinding) { break }
45826
45827 default:
45828 this.raise(node.start, "Assigning to rvalue");
45829 }
45830 } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
45831 return node
45832 };
45833
45834 // Convert list of expression atoms to binding list.
45835
45836 pp$2.toAssignableList = function(exprList, isBinding) {
45837 var end = exprList.length;
45838 for (var i = 0; i < end; i++) {
45839 var elt = exprList[i];
45840 if (elt) { this.toAssignable(elt, isBinding); }
45841 }
45842 if (end) {
45843 var last = exprList[end - 1];
45844 if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
45845 { this.unexpected(last.argument.start); }
45846 }
45847 return exprList
45848 };
45849
45850 // Parses spread element.
45851
45852 pp$2.parseSpread = function(refDestructuringErrors) {
45853 var node = this.startNode();
45854 this.next();
45855 node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
45856 return this.finishNode(node, "SpreadElement")
45857 };
45858
45859 pp$2.parseRestBinding = function() {
45860 var node = this.startNode();
45861 this.next();
45862
45863 // RestElement inside of a function parameter must be an identifier
45864 if (this.options.ecmaVersion === 6 && this.type !== types.name)
45865 { this.unexpected(); }
45866
45867 node.argument = this.parseBindingAtom();
45868
45869 return this.finishNode(node, "RestElement")
45870 };
45871
45872 // Parses lvalue (assignable) atom.
45873
45874 pp$2.parseBindingAtom = function() {
45875 if (this.options.ecmaVersion >= 6) {
45876 switch (this.type) {
45877 case types.bracketL:
45878 var node = this.startNode();
45879 this.next();
45880 node.elements = this.parseBindingList(types.bracketR, true, true);
45881 return this.finishNode(node, "ArrayPattern")
45882
45883 case types.braceL:
45884 return this.parseObj(true)
45885 }
45886 }
45887 return this.parseIdent()
45888 };
45889
45890 pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
45891 var elts = [], first = true;
45892 while (!this.eat(close)) {
45893 if (first) { first = false; }
45894 else { this.expect(types.comma); }
45895 if (allowEmpty && this.type === types.comma) {
45896 elts.push(null);
45897 } else if (allowTrailingComma && this.afterTrailingComma(close)) {
45898 break
45899 } else if (this.type === types.ellipsis) {
45900 var rest = this.parseRestBinding();
45901 this.parseBindingListItem(rest);
45902 elts.push(rest);
45903 if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
45904 this.expect(close);
45905 break
45906 } else {
45907 var elem = this.parseMaybeDefault(this.start, this.startLoc);
45908 this.parseBindingListItem(elem);
45909 elts.push(elem);
45910 }
45911 }
45912 return elts
45913 };
45914
45915 pp$2.parseBindingListItem = function(param) {
45916 return param
45917 };
45918
45919 // Parses assignment pattern around given atom if possible.
45920
45921 pp$2.parseMaybeDefault = function(startPos, startLoc, left) {
45922 left = left || this.parseBindingAtom();
45923 if (this.options.ecmaVersion < 6 || !this.eat(types.eq)) { return left }
45924 var node = this.startNodeAt(startPos, startLoc);
45925 node.left = left;
45926 node.right = this.parseMaybeAssign();
45927 return this.finishNode(node, "AssignmentPattern")
45928 };
45929
45930 // The following three functions all verify that a node is an lvalue —
45931 // something that can be bound, or assigned to. In order to do so, they perform
45932 // a variety of checks:
45933 //
45934 // - Check that none of the bound/assigned-to identifiers are reserved words.
45935 // - Record name declarations for bindings in the appropriate scope.
45936 // - Check duplicate argument names, if checkClashes is set.
45937 //
45938 // If a complex binding pattern is encountered (e.g., object and array
45939 // destructuring), the entire pattern is recursively checked.
45940 //
45941 // There are three versions of checkLVal*() appropriate for different
45942 // circumstances:
45943 //
45944 // - checkLValSimple() shall be used if the syntactic construct supports
45945 // nothing other than identifiers and member expressions. Parenthesized
45946 // expressions are also correctly handled. This is generally appropriate for
45947 // constructs for which the spec says
45948 //
45949 // > It is a Syntax Error if AssignmentTargetType of [the production] is not
45950 // > simple.
45951 //
45952 // It is also appropriate for checking if an identifier is valid and not
45953 // defined elsewhere, like import declarations or function/class identifiers.
45954 //
45955 // Examples where this is used include:
45956 // a += …;
45957 // import a from '…';
45958 // where a is the node to be checked.
45959 //
45960 // - checkLValPattern() shall be used if the syntactic construct supports
45961 // anything checkLValSimple() supports, as well as object and array
45962 // destructuring patterns. This is generally appropriate for constructs for
45963 // which the spec says
45964 //
45965 // > It is a Syntax Error if [the production] is neither an ObjectLiteral nor
45966 // > an ArrayLiteral and AssignmentTargetType of [the production] is not
45967 // > simple.
45968 //
45969 // Examples where this is used include:
45970 // (a = …);
45971 // const a = …;
45972 // try { … } catch (a) { … }
45973 // where a is the node to be checked.
45974 //
45975 // - checkLValInnerPattern() shall be used if the syntactic construct supports
45976 // anything checkLValPattern() supports, as well as default assignment
45977 // patterns, rest elements, and other constructs that may appear within an
45978 // object or array destructuring pattern.
45979 //
45980 // As a special case, function parameters also use checkLValInnerPattern(),
45981 // as they also support defaults and rest constructs.
45982 //
45983 // These functions deliberately support both assignment and binding constructs,
45984 // as the logic for both is exceedingly similar. If the node is the target of
45985 // an assignment, then bindingType should be set to BIND_NONE. Otherwise, it
45986 // should be set to the appropriate BIND_* constant, like BIND_VAR or
45987 // BIND_LEXICAL.
45988 //
45989 // If the function is called with a non-BIND_NONE bindingType, then
45990 // additionally a checkClashes object may be specified to allow checking for
45991 // duplicate argument names. checkClashes is ignored if the provided construct
45992 // is an assignment (i.e., bindingType is BIND_NONE).
45993
45994 pp$2.checkLValSimple = function(expr, bindingType, checkClashes) {
45995 if ( bindingType === void 0 ) bindingType = BIND_NONE;
45996
45997 var isBind = bindingType !== BIND_NONE;
45998
45999 switch (expr.type) {
46000 case "Identifier":
46001 if (this.strict && this.reservedWordsStrictBind.test(expr.name))
46002 { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
46003 if (isBind) {
46004 if (bindingType === BIND_LEXICAL && expr.name === "let")
46005 { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
46006 if (checkClashes) {
46007 if (has(checkClashes, expr.name))
46008 { this.raiseRecoverable(expr.start, "Argument name clash"); }
46009 checkClashes[expr.name] = true;
46010 }
46011 if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }
46012 }
46013 break
46014
46015 case "ChainExpression":
46016 this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
46017 break
46018
46019 case "MemberExpression":
46020 if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); }
46021 break
46022
46023 case "ParenthesizedExpression":
46024 if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); }
46025 return this.checkLValSimple(expr.expression, bindingType, checkClashes)
46026
46027 default:
46028 this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
46029 }
46030 };
46031
46032 pp$2.checkLValPattern = function(expr, bindingType, checkClashes) {
46033 if ( bindingType === void 0 ) bindingType = BIND_NONE;
46034
46035 switch (expr.type) {
46036 case "ObjectPattern":
46037 for (var i = 0, list = expr.properties; i < list.length; i += 1) {
46038 var prop = list[i];
46039
46040 this.checkLValInnerPattern(prop, bindingType, checkClashes);
46041 }
46042 break
46043
46044 case "ArrayPattern":
46045 for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
46046 var elem = list$1[i$1];
46047
46048 if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); }
46049 }
46050 break
46051
46052 default:
46053 this.checkLValSimple(expr, bindingType, checkClashes);
46054 }
46055 };
46056
46057 pp$2.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
46058 if ( bindingType === void 0 ) bindingType = BIND_NONE;
46059
46060 switch (expr.type) {
46061 case "Property":
46062 // AssignmentProperty has type === "Property"
46063 this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
46064 break
46065
46066 case "AssignmentPattern":
46067 this.checkLValPattern(expr.left, bindingType, checkClashes);
46068 break
46069
46070 case "RestElement":
46071 this.checkLValPattern(expr.argument, bindingType, checkClashes);
46072 break
46073
46074 default:
46075 this.checkLValPattern(expr, bindingType, checkClashes);
46076 }
46077 };
46078
46079 // A recursive descent parser operates by defining functions for all
46080
46081 var pp$3 = Parser.prototype;
46082
46083 // Check if property name clashes with already added.
46084 // Object/class getters and setters are not allowed to clash —
46085 // either with each other or with an init property — and in
46086 // strict mode, init properties are also not allowed to be repeated.
46087
46088 pp$3.checkPropClash = function(prop, propHash, refDestructuringErrors) {
46089 if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
46090 { return }
46091 if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
46092 { return }
46093 var key = prop.key;
46094 var name;
46095 switch (key.type) {
46096 case "Identifier": name = key.name; break
46097 case "Literal": name = String(key.value); break
46098 default: return
46099 }
46100 var kind = prop.kind;
46101 if (this.options.ecmaVersion >= 6) {
46102 if (name === "__proto__" && kind === "init") {
46103 if (propHash.proto) {
46104 if (refDestructuringErrors) {
46105 if (refDestructuringErrors.doubleProto < 0)
46106 { refDestructuringErrors.doubleProto = key.start; }
46107 // Backwards-compat kludge. Can be removed in version 6.0
46108 } else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); }
46109 }
46110 propHash.proto = true;
46111 }
46112 return
46113 }
46114 name = "$" + name;
46115 var other = propHash[name];
46116 if (other) {
46117 var redefinition;
46118 if (kind === "init") {
46119 redefinition = this.strict && other.init || other.get || other.set;
46120 } else {
46121 redefinition = other.init || other[kind];
46122 }
46123 if (redefinition)
46124 { this.raiseRecoverable(key.start, "Redefinition of property"); }
46125 } else {
46126 other = propHash[name] = {
46127 init: false,
46128 get: false,
46129 set: false
46130 };
46131 }
46132 other[kind] = true;
46133 };
46134
46135 // ### Expression parsing
46136
46137 // These nest, from the most general expression type at the top to
46138 // 'atomic', nondivisible expression types at the bottom. Most of
46139 // the functions will simply let the function(s) below them parse,
46140 // and, *if* the syntactic construct they handle is present, wrap
46141 // the AST node that the inner parser gave them in another node.
46142
46143 // Parse a full expression. The optional arguments are used to
46144 // forbid the `in` operator (in for loops initalization expressions)
46145 // and provide reference for storing '=' operator inside shorthand
46146 // property assignment in contexts where both object expression
46147 // and object pattern might appear (so it's possible to raise
46148 // delayed syntax error at correct position).
46149
46150 pp$3.parseExpression = function(forInit, refDestructuringErrors) {
46151 var startPos = this.start, startLoc = this.startLoc;
46152 var expr = this.parseMaybeAssign(forInit, refDestructuringErrors);
46153 if (this.type === types.comma) {
46154 var node = this.startNodeAt(startPos, startLoc);
46155 node.expressions = [expr];
46156 while (this.eat(types.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); }
46157 return this.finishNode(node, "SequenceExpression")
46158 }
46159 return expr
46160 };
46161
46162 // Parse an assignment expression. This includes applications of
46163 // operators like `+=`.
46164
46165 pp$3.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {
46166 if (this.isContextual("yield")) {
46167 if (this.inGenerator) { return this.parseYield(forInit) }
46168 // The tokenizer will assume an expression is allowed after
46169 // `yield`, but this isn't that kind of yield
46170 else { this.exprAllowed = false; }
46171 }
46172
46173 var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1;
46174 if (refDestructuringErrors) {
46175 oldParenAssign = refDestructuringErrors.parenthesizedAssign;
46176 oldTrailingComma = refDestructuringErrors.trailingComma;
46177 refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
46178 } else {
46179 refDestructuringErrors = new DestructuringErrors;
46180 ownDestructuringErrors = true;
46181 }
46182
46183 var startPos = this.start, startLoc = this.startLoc;
46184 if (this.type === types.parenL || this.type === types.name) {
46185 this.potentialArrowAt = this.start;
46186 this.potentialArrowInForAwait = forInit === "await";
46187 }
46188 var left = this.parseMaybeConditional(forInit, refDestructuringErrors);
46189 if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
46190 if (this.type.isAssign) {
46191 var node = this.startNodeAt(startPos, startLoc);
46192 node.operator = this.value;
46193 if (this.type === types.eq)
46194 { left = this.toAssignable(left, false, refDestructuringErrors); }
46195 if (!ownDestructuringErrors) {
46196 refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
46197 }
46198 if (refDestructuringErrors.shorthandAssign >= left.start)
46199 { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly
46200 if (this.type === types.eq)
46201 { this.checkLValPattern(left); }
46202 else
46203 { this.checkLValSimple(left); }
46204 node.left = left;
46205 this.next();
46206 node.right = this.parseMaybeAssign(forInit);
46207 return this.finishNode(node, "AssignmentExpression")
46208 } else {
46209 if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
46210 }
46211 if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
46212 if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
46213 return left
46214 };
46215
46216 // Parse a ternary conditional (`?:`) operator.
46217
46218 pp$3.parseMaybeConditional = function(forInit, refDestructuringErrors) {
46219 var startPos = this.start, startLoc = this.startLoc;
46220 var expr = this.parseExprOps(forInit, refDestructuringErrors);
46221 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
46222 if (this.eat(types.question)) {
46223 var node = this.startNodeAt(startPos, startLoc);
46224 node.test = expr;
46225 node.consequent = this.parseMaybeAssign();
46226 this.expect(types.colon);
46227 node.alternate = this.parseMaybeAssign(forInit);
46228 return this.finishNode(node, "ConditionalExpression")
46229 }
46230 return expr
46231 };
46232
46233 // Start the precedence parser.
46234
46235 pp$3.parseExprOps = function(forInit, refDestructuringErrors) {
46236 var startPos = this.start, startLoc = this.startLoc;
46237 var expr = this.parseMaybeUnary(refDestructuringErrors, false);
46238 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
46239 return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit)
46240 };
46241
46242 // Parse binary operators with the operator precedence parsing
46243 // algorithm. `left` is the left-hand side of the operator.
46244 // `minPrec` provides context that allows the function to stop and
46245 // defer further parser to one of its callers when it encounters an
46246 // operator that has a lower precedence than the set it is parsing.
46247
46248 pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {
46249 var prec = this.type.binop;
46250 if (prec != null && (!forInit || this.type !== types._in)) {
46251 if (prec > minPrec) {
46252 var logical = this.type === types.logicalOR || this.type === types.logicalAND;
46253 var coalesce = this.type === types.coalesce;
46254 if (coalesce) {
46255 // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
46256 // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
46257 prec = types.logicalAND.binop;
46258 }
46259 var op = this.value;
46260 this.next();
46261 var startPos = this.start, startLoc = this.startLoc;
46262 var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, forInit);
46263 var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
46264 if ((logical && this.type === types.coalesce) || (coalesce && (this.type === types.logicalOR || this.type === types.logicalAND))) {
46265 this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
46266 }
46267 return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit)
46268 }
46269 }
46270 return left
46271 };
46272
46273 pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) {
46274 var node = this.startNodeAt(startPos, startLoc);
46275 node.left = left;
46276 node.operator = op;
46277 node.right = right;
46278 return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
46279 };
46280
46281 // Parse unary operators, both prefix and postfix.
46282
46283 pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec) {
46284 var startPos = this.start, startLoc = this.startLoc, expr;
46285 if (this.isContextual("await") && this.canAwait) {
46286 expr = this.parseAwait();
46287 sawUnary = true;
46288 } else if (this.type.prefix) {
46289 var node = this.startNode(), update = this.type === types.incDec;
46290 node.operator = this.value;
46291 node.prefix = true;
46292 this.next();
46293 node.argument = this.parseMaybeUnary(null, true, update);
46294 this.checkExpressionErrors(refDestructuringErrors, true);
46295 if (update) { this.checkLValSimple(node.argument); }
46296 else if (this.strict && node.operator === "delete" &&
46297 node.argument.type === "Identifier")
46298 { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
46299 else if (node.operator === "delete" && isPrivateFieldAccess(node.argument))
46300 { this.raiseRecoverable(node.start, "Private fields can not be deleted"); }
46301 else { sawUnary = true; }
46302 expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
46303 } else {
46304 expr = this.parseExprSubscripts(refDestructuringErrors);
46305 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
46306 while (this.type.postfix && !this.canInsertSemicolon()) {
46307 var node$1 = this.startNodeAt(startPos, startLoc);
46308 node$1.operator = this.value;
46309 node$1.prefix = false;
46310 node$1.argument = expr;
46311 this.checkLValSimple(expr);
46312 this.next();
46313 expr = this.finishNode(node$1, "UpdateExpression");
46314 }
46315 }
46316
46317 if (!incDec && this.eat(types.starstar)) {
46318 if (sawUnary)
46319 { this.unexpected(this.lastTokStart); }
46320 else
46321 { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) }
46322 } else {
46323 return expr
46324 }
46325 };
46326
46327 function isPrivateFieldAccess(node) {
46328 return (
46329 node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" ||
46330 node.type === "ChainExpression" && isPrivateFieldAccess(node.expression)
46331 )
46332 }
46333
46334 // Parse call, dot, and `[]`-subscript expressions.
46335
46336 pp$3.parseExprSubscripts = function(refDestructuringErrors) {
46337 var startPos = this.start, startLoc = this.startLoc;
46338 var expr = this.parseExprAtom(refDestructuringErrors);
46339 if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")
46340 { return expr }
46341 var result = this.parseSubscripts(expr, startPos, startLoc);
46342 if (refDestructuringErrors && result.type === "MemberExpression") {
46343 if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
46344 if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
46345 if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; }
46346 }
46347 return result
46348 };
46349
46350 pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) {
46351 var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
46352 this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&
46353 this.potentialArrowAt === base.start;
46354 var optionalChained = false;
46355
46356 while (true) {
46357 var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained);
46358
46359 if (element.optional) { optionalChained = true; }
46360 if (element === base || element.type === "ArrowFunctionExpression") {
46361 if (optionalChained) {
46362 var chainNode = this.startNodeAt(startPos, startLoc);
46363 chainNode.expression = element;
46364 element = this.finishNode(chainNode, "ChainExpression");
46365 }
46366 return element
46367 }
46368
46369 base = element;
46370 }
46371 };
46372
46373 pp$3.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained) {
46374 var optionalSupported = this.options.ecmaVersion >= 11;
46375 var optional = optionalSupported && this.eat(types.questionDot);
46376 if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }
46377
46378 var computed = this.eat(types.bracketL);
46379 if (computed || (optional && this.type !== types.parenL && this.type !== types.backQuote) || this.eat(types.dot)) {
46380 var node = this.startNodeAt(startPos, startLoc);
46381 node.object = base;
46382 if (computed) {
46383 node.property = this.parseExpression();
46384 this.expect(types.bracketR);
46385 } else if (this.type === types.privateId && base.type !== "Super") {
46386 node.property = this.parsePrivateIdent();
46387 } else {
46388 node.property = this.parseIdent(this.options.allowReserved !== "never");
46389 }
46390 node.computed = !!computed;
46391 if (optionalSupported) {
46392 node.optional = optional;
46393 }
46394 base = this.finishNode(node, "MemberExpression");
46395 } else if (!noCalls && this.eat(types.parenL)) {
46396 var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
46397 this.yieldPos = 0;
46398 this.awaitPos = 0;
46399 this.awaitIdentPos = 0;
46400 var exprList = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
46401 if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types.arrow)) {
46402 this.checkPatternErrors(refDestructuringErrors, false);
46403 this.checkYieldAwaitInDefaultParams();
46404 if (this.awaitIdentPos > 0)
46405 { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
46406 this.yieldPos = oldYieldPos;
46407 this.awaitPos = oldAwaitPos;
46408 this.awaitIdentPos = oldAwaitIdentPos;
46409 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true)
46410 }
46411 this.checkExpressionErrors(refDestructuringErrors, true);
46412 this.yieldPos = oldYieldPos || this.yieldPos;
46413 this.awaitPos = oldAwaitPos || this.awaitPos;
46414 this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
46415 var node$1 = this.startNodeAt(startPos, startLoc);
46416 node$1.callee = base;
46417 node$1.arguments = exprList;
46418 if (optionalSupported) {
46419 node$1.optional = optional;
46420 }
46421 base = this.finishNode(node$1, "CallExpression");
46422 } else if (this.type === types.backQuote) {
46423 if (optional || optionalChained) {
46424 this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
46425 }
46426 var node$2 = this.startNodeAt(startPos, startLoc);
46427 node$2.tag = base;
46428 node$2.quasi = this.parseTemplate({isTagged: true});
46429 base = this.finishNode(node$2, "TaggedTemplateExpression");
46430 }
46431 return base
46432 };
46433
46434 // Parse an atomic expression — either a single token that is an
46435 // expression, an expression started by a keyword like `function` or
46436 // `new`, or an expression wrapped in punctuation like `()`, `[]`,
46437 // or `{}`.
46438
46439 pp$3.parseExprAtom = function(refDestructuringErrors) {
46440 // If a division operator appears in an expression position, the
46441 // tokenizer got confused, and we force it to read a regexp instead.
46442 if (this.type === types.slash) { this.readRegexp(); }
46443
46444 var node, canBeArrow = this.potentialArrowAt === this.start;
46445 switch (this.type) {
46446 case types._super:
46447 if (!this.allowSuper)
46448 { this.raise(this.start, "'super' keyword outside a method"); }
46449 node = this.startNode();
46450 this.next();
46451 if (this.type === types.parenL && !this.allowDirectSuper)
46452 { this.raise(node.start, "super() call outside constructor of a subclass"); }
46453 // The `super` keyword can appear at below:
46454 // SuperProperty:
46455 // super [ Expression ]
46456 // super . IdentifierName
46457 // SuperCall:
46458 // super ( Arguments )
46459 if (this.type !== types.dot && this.type !== types.bracketL && this.type !== types.parenL)
46460 { this.unexpected(); }
46461 return this.finishNode(node, "Super")
46462
46463 case types._this:
46464 node = this.startNode();
46465 this.next();
46466 return this.finishNode(node, "ThisExpression")
46467
46468 case types.name:
46469 var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
46470 var id = this.parseIdent(false);
46471 if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types._function))
46472 { return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true) }
46473 if (canBeArrow && !this.canInsertSemicolon()) {
46474 if (this.eat(types.arrow))
46475 { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) }
46476 if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types.name && !containsEsc &&
46477 (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {
46478 id = this.parseIdent(false);
46479 if (this.canInsertSemicolon() || !this.eat(types.arrow))
46480 { this.unexpected(); }
46481 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true)
46482 }
46483 }
46484 return id
46485
46486 case types.regexp:
46487 var value = this.value;
46488 node = this.parseLiteral(value.value);
46489 node.regex = {pattern: value.pattern, flags: value.flags};
46490 return node
46491
46492 case types.num: case types.string:
46493 return this.parseLiteral(this.value)
46494
46495 case types._null: case types._true: case types._false:
46496 node = this.startNode();
46497 node.value = this.type === types._null ? null : this.type === types._true;
46498 node.raw = this.type.keyword;
46499 this.next();
46500 return this.finishNode(node, "Literal")
46501
46502 case types.parenL:
46503 var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow);
46504 if (refDestructuringErrors) {
46505 if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
46506 { refDestructuringErrors.parenthesizedAssign = start; }
46507 if (refDestructuringErrors.parenthesizedBind < 0)
46508 { refDestructuringErrors.parenthesizedBind = start; }
46509 }
46510 return expr
46511
46512 case types.bracketL:
46513 node = this.startNode();
46514 this.next();
46515 node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors);
46516 return this.finishNode(node, "ArrayExpression")
46517
46518 case types.braceL:
46519 return this.parseObj(false, refDestructuringErrors)
46520
46521 case types._function:
46522 node = this.startNode();
46523 this.next();
46524 return this.parseFunction(node, 0)
46525
46526 case types._class:
46527 return this.parseClass(this.startNode(), false)
46528
46529 case types._new:
46530 return this.parseNew()
46531
46532 case types.backQuote:
46533 return this.parseTemplate()
46534
46535 case types._import:
46536 if (this.options.ecmaVersion >= 11) {
46537 return this.parseExprImport()
46538 } else {
46539 return this.unexpected()
46540 }
46541
46542 default:
46543 this.unexpected();
46544 }
46545 };
46546
46547 pp$3.parseExprImport = function() {
46548 var node = this.startNode();
46549
46550 // Consume `import` as an identifier for `import.meta`.
46551 // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.
46552 if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); }
46553 var meta = this.parseIdent(true);
46554
46555 switch (this.type) {
46556 case types.parenL:
46557 return this.parseDynamicImport(node)
46558 case types.dot:
46559 node.meta = meta;
46560 return this.parseImportMeta(node)
46561 default:
46562 this.unexpected();
46563 }
46564 };
46565
46566 pp$3.parseDynamicImport = function(node) {
46567 this.next(); // skip `(`
46568
46569 // Parse node.source.
46570 node.source = this.parseMaybeAssign();
46571
46572 // Verify ending.
46573 if (!this.eat(types.parenR)) {
46574 var errorPos = this.start;
46575 if (this.eat(types.comma) && this.eat(types.parenR)) {
46576 this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
46577 } else {
46578 this.unexpected(errorPos);
46579 }
46580 }
46581
46582 return this.finishNode(node, "ImportExpression")
46583 };
46584
46585 pp$3.parseImportMeta = function(node) {
46586 this.next(); // skip `.`
46587
46588 var containsEsc = this.containsEsc;
46589 node.property = this.parseIdent(true);
46590
46591 if (node.property.name !== "meta")
46592 { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); }
46593 if (containsEsc)
46594 { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); }
46595 if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere)
46596 { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); }
46597
46598 return this.finishNode(node, "MetaProperty")
46599 };
46600
46601 pp$3.parseLiteral = function(value) {
46602 var node = this.startNode();
46603 node.value = value;
46604 node.raw = this.input.slice(this.start, this.end);
46605 if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); }
46606 this.next();
46607 return this.finishNode(node, "Literal")
46608 };
46609
46610 pp$3.parseParenExpression = function() {
46611 this.expect(types.parenL);
46612 var val = this.parseExpression();
46613 this.expect(types.parenR);
46614 return val
46615 };
46616
46617 pp$3.parseParenAndDistinguishExpression = function(canBeArrow) {
46618 var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
46619 if (this.options.ecmaVersion >= 6) {
46620 this.next();
46621
46622 var innerStartPos = this.start, innerStartLoc = this.startLoc;
46623 var exprList = [], first = true, lastIsComma = false;
46624 var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
46625 this.yieldPos = 0;
46626 this.awaitPos = 0;
46627 // Do not save awaitIdentPos to allow checking awaits nested in parameters
46628 while (this.type !== types.parenR) {
46629 first ? first = false : this.expect(types.comma);
46630 if (allowTrailingComma && this.afterTrailingComma(types.parenR, true)) {
46631 lastIsComma = true;
46632 break
46633 } else if (this.type === types.ellipsis) {
46634 spreadStart = this.start;
46635 exprList.push(this.parseParenItem(this.parseRestBinding()));
46636 if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
46637 break
46638 } else {
46639 exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
46640 }
46641 }
46642 var innerEndPos = this.start, innerEndLoc = this.startLoc;
46643 this.expect(types.parenR);
46644
46645 if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) {
46646 this.checkPatternErrors(refDestructuringErrors, false);
46647 this.checkYieldAwaitInDefaultParams();
46648 this.yieldPos = oldYieldPos;
46649 this.awaitPos = oldAwaitPos;
46650 return this.parseParenArrowList(startPos, startLoc, exprList)
46651 }
46652
46653 if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
46654 if (spreadStart) { this.unexpected(spreadStart); }
46655 this.checkExpressionErrors(refDestructuringErrors, true);
46656 this.yieldPos = oldYieldPos || this.yieldPos;
46657 this.awaitPos = oldAwaitPos || this.awaitPos;
46658
46659 if (exprList.length > 1) {
46660 val = this.startNodeAt(innerStartPos, innerStartLoc);
46661 val.expressions = exprList;
46662 this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
46663 } else {
46664 val = exprList[0];
46665 }
46666 } else {
46667 val = this.parseParenExpression();
46668 }
46669
46670 if (this.options.preserveParens) {
46671 var par = this.startNodeAt(startPos, startLoc);
46672 par.expression = val;
46673 return this.finishNode(par, "ParenthesizedExpression")
46674 } else {
46675 return val
46676 }
46677 };
46678
46679 pp$3.parseParenItem = function(item) {
46680 return item
46681 };
46682
46683 pp$3.parseParenArrowList = function(startPos, startLoc, exprList) {
46684 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList)
46685 };
46686
46687 // New's precedence is slightly tricky. It must allow its argument to
46688 // be a `[]` or dot subscript expression, but not a call — at least,
46689 // not without wrapping it in parentheses. Thus, it uses the noCalls
46690 // argument to parseSubscripts to prevent it from consuming the
46691 // argument list.
46692
46693 var empty$1 = [];
46694
46695 pp$3.parseNew = function() {
46696 if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); }
46697 var node = this.startNode();
46698 var meta = this.parseIdent(true);
46699 if (this.options.ecmaVersion >= 6 && this.eat(types.dot)) {
46700 node.meta = meta;
46701 var containsEsc = this.containsEsc;
46702 node.property = this.parseIdent(true);
46703 if (node.property.name !== "target")
46704 { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); }
46705 if (containsEsc)
46706 { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); }
46707 if (!this.inNonArrowFunction)
46708 { this.raiseRecoverable(node.start, "'new.target' can only be used in functions"); }
46709 return this.finishNode(node, "MetaProperty")
46710 }
46711 var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types._import;
46712 node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
46713 if (isImport && node.callee.type === "ImportExpression") {
46714 this.raise(startPos, "Cannot use new with import()");
46715 }
46716 if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false); }
46717 else { node.arguments = empty$1; }
46718 return this.finishNode(node, "NewExpression")
46719 };
46720
46721 // Parse template expression.
46722
46723 pp$3.parseTemplateElement = function(ref) {
46724 var isTagged = ref.isTagged;
46725
46726 var elem = this.startNode();
46727 if (this.type === types.invalidTemplate) {
46728 if (!isTagged) {
46729 this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
46730 }
46731 elem.value = {
46732 raw: this.value,
46733 cooked: null
46734 };
46735 } else {
46736 elem.value = {
46737 raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
46738 cooked: this.value
46739 };
46740 }
46741 this.next();
46742 elem.tail = this.type === types.backQuote;
46743 return this.finishNode(elem, "TemplateElement")
46744 };
46745
46746 pp$3.parseTemplate = function(ref) {
46747 if ( ref === void 0 ) ref = {};
46748 var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
46749
46750 var node = this.startNode();
46751 this.next();
46752 node.expressions = [];
46753 var curElt = this.parseTemplateElement({isTagged: isTagged});
46754 node.quasis = [curElt];
46755 while (!curElt.tail) {
46756 if (this.type === types.eof) { this.raise(this.pos, "Unterminated template literal"); }
46757 this.expect(types.dollarBraceL);
46758 node.expressions.push(this.parseExpression());
46759 this.expect(types.braceR);
46760 node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
46761 }
46762 this.next();
46763 return this.finishNode(node, "TemplateLiteral")
46764 };
46765
46766 pp$3.isAsyncProp = function(prop) {
46767 return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
46768 (this.type === types.name || this.type === types.num || this.type === types.string || this.type === types.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types.star)) &&
46769 !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
46770 };
46771
46772 // Parse an object literal or binding pattern.
46773
46774 pp$3.parseObj = function(isPattern, refDestructuringErrors) {
46775 var node = this.startNode(), first = true, propHash = {};
46776 node.properties = [];
46777 this.next();
46778 while (!this.eat(types.braceR)) {
46779 if (!first) {
46780 this.expect(types.comma);
46781 if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types.braceR)) { break }
46782 } else { first = false; }
46783
46784 var prop = this.parseProperty(isPattern, refDestructuringErrors);
46785 if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
46786 node.properties.push(prop);
46787 }
46788 return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
46789 };
46790
46791 pp$3.parseProperty = function(isPattern, refDestructuringErrors) {
46792 var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
46793 if (this.options.ecmaVersion >= 9 && this.eat(types.ellipsis)) {
46794 if (isPattern) {
46795 prop.argument = this.parseIdent(false);
46796 if (this.type === types.comma) {
46797 this.raise(this.start, "Comma is not permitted after the rest element");
46798 }
46799 return this.finishNode(prop, "RestElement")
46800 }
46801 // To disallow parenthesized identifier via `this.toAssignable()`.
46802 if (this.type === types.parenL && refDestructuringErrors) {
46803 if (refDestructuringErrors.parenthesizedAssign < 0) {
46804 refDestructuringErrors.parenthesizedAssign = this.start;
46805 }
46806 if (refDestructuringErrors.parenthesizedBind < 0) {
46807 refDestructuringErrors.parenthesizedBind = this.start;
46808 }
46809 }
46810 // Parse argument.
46811 prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
46812 // To disallow trailing comma via `this.toAssignable()`.
46813 if (this.type === types.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
46814 refDestructuringErrors.trailingComma = this.start;
46815 }
46816 // Finish
46817 return this.finishNode(prop, "SpreadElement")
46818 }
46819 if (this.options.ecmaVersion >= 6) {
46820 prop.method = false;
46821 prop.shorthand = false;
46822 if (isPattern || refDestructuringErrors) {
46823 startPos = this.start;
46824 startLoc = this.startLoc;
46825 }
46826 if (!isPattern)
46827 { isGenerator = this.eat(types.star); }
46828 }
46829 var containsEsc = this.containsEsc;
46830 this.parsePropertyName(prop);
46831 if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
46832 isAsync = true;
46833 isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star);
46834 this.parsePropertyName(prop, refDestructuringErrors);
46835 } else {
46836 isAsync = false;
46837 }
46838 this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
46839 return this.finishNode(prop, "Property")
46840 };
46841
46842 pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
46843 if ((isGenerator || isAsync) && this.type === types.colon)
46844 { this.unexpected(); }
46845
46846 if (this.eat(types.colon)) {
46847 prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
46848 prop.kind = "init";
46849 } else if (this.options.ecmaVersion >= 6 && this.type === types.parenL) {
46850 if (isPattern) { this.unexpected(); }
46851 prop.kind = "init";
46852 prop.method = true;
46853 prop.value = this.parseMethod(isGenerator, isAsync);
46854 } else if (!isPattern && !containsEsc &&
46855 this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
46856 (prop.key.name === "get" || prop.key.name === "set") &&
46857 (this.type !== types.comma && this.type !== types.braceR && this.type !== types.eq)) {
46858 if (isGenerator || isAsync) { this.unexpected(); }
46859 prop.kind = prop.key.name;
46860 this.parsePropertyName(prop);
46861 prop.value = this.parseMethod(false);
46862 var paramCount = prop.kind === "get" ? 0 : 1;
46863 if (prop.value.params.length !== paramCount) {
46864 var start = prop.value.start;
46865 if (prop.kind === "get")
46866 { this.raiseRecoverable(start, "getter should have no params"); }
46867 else
46868 { this.raiseRecoverable(start, "setter should have exactly one param"); }
46869 } else {
46870 if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
46871 { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
46872 }
46873 } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
46874 if (isGenerator || isAsync) { this.unexpected(); }
46875 this.checkUnreserved(prop.key);
46876 if (prop.key.name === "await" && !this.awaitIdentPos)
46877 { this.awaitIdentPos = startPos; }
46878 prop.kind = "init";
46879 if (isPattern) {
46880 prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
46881 } else if (this.type === types.eq && refDestructuringErrors) {
46882 if (refDestructuringErrors.shorthandAssign < 0)
46883 { refDestructuringErrors.shorthandAssign = this.start; }
46884 prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
46885 } else {
46886 prop.value = this.copyNode(prop.key);
46887 }
46888 prop.shorthand = true;
46889 } else { this.unexpected(); }
46890 };
46891
46892 pp$3.parsePropertyName = function(prop) {
46893 if (this.options.ecmaVersion >= 6) {
46894 if (this.eat(types.bracketL)) {
46895 prop.computed = true;
46896 prop.key = this.parseMaybeAssign();
46897 this.expect(types.bracketR);
46898 return prop.key
46899 } else {
46900 prop.computed = false;
46901 }
46902 }
46903 return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
46904 };
46905
46906 // Initialize empty function node.
46907
46908 pp$3.initFunction = function(node) {
46909 node.id = null;
46910 if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }
46911 if (this.options.ecmaVersion >= 8) { node.async = false; }
46912 };
46913
46914 // Parse object or class method.
46915
46916 pp$3.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
46917 var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
46918
46919 this.initFunction(node);
46920 if (this.options.ecmaVersion >= 6)
46921 { node.generator = isGenerator; }
46922 if (this.options.ecmaVersion >= 8)
46923 { node.async = !!isAsync; }
46924
46925 this.yieldPos = 0;
46926 this.awaitPos = 0;
46927 this.awaitIdentPos = 0;
46928 this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
46929
46930 this.expect(types.parenL);
46931 node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
46932 this.checkYieldAwaitInDefaultParams();
46933 this.parseFunctionBody(node, false, true);
46934
46935 this.yieldPos = oldYieldPos;
46936 this.awaitPos = oldAwaitPos;
46937 this.awaitIdentPos = oldAwaitIdentPos;
46938 return this.finishNode(node, "FunctionExpression")
46939 };
46940
46941 // Parse arrow function expression with given parameters.
46942
46943 pp$3.parseArrowExpression = function(node, params, isAsync) {
46944 var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
46945
46946 this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
46947 this.initFunction(node);
46948 if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }
46949
46950 this.yieldPos = 0;
46951 this.awaitPos = 0;
46952 this.awaitIdentPos = 0;
46953
46954 node.params = this.toAssignableList(params, true);
46955 this.parseFunctionBody(node, true, false);
46956
46957 this.yieldPos = oldYieldPos;
46958 this.awaitPos = oldAwaitPos;
46959 this.awaitIdentPos = oldAwaitIdentPos;
46960 return this.finishNode(node, "ArrowFunctionExpression")
46961 };
46962
46963 // Parse function body and check parameters.
46964
46965 pp$3.parseFunctionBody = function(node, isArrowFunction, isMethod) {
46966 var isExpression = isArrowFunction && this.type !== types.braceL;
46967 var oldStrict = this.strict, useStrict = false;
46968
46969 if (isExpression) {
46970 node.body = this.parseMaybeAssign();
46971 node.expression = true;
46972 this.checkParams(node, false);
46973 } else {
46974 var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
46975 if (!oldStrict || nonSimple) {
46976 useStrict = this.strictDirective(this.end);
46977 // If this is a strict mode function, verify that argument names
46978 // are not repeated, and it does not try to bind the words `eval`
46979 // or `arguments`.
46980 if (useStrict && nonSimple)
46981 { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
46982 }
46983 // Start a new scope with regard to labels and the `inFunction`
46984 // flag (restore them to their old value afterwards).
46985 var oldLabels = this.labels;
46986 this.labels = [];
46987 if (useStrict) { this.strict = true; }
46988
46989 // Add the params to varDeclaredNames to ensure that an error is thrown
46990 // if a let/const declaration in the function clashes with one of the params.
46991 this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
46992 // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
46993 if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); }
46994 node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
46995 node.expression = false;
46996 this.adaptDirectivePrologue(node.body.body);
46997 this.labels = oldLabels;
46998 }
46999 this.exitScope();
47000 };
47001
47002 pp$3.isSimpleParamList = function(params) {
47003 for (var i = 0, list = params; i < list.length; i += 1)
47004 {
47005 var param = list[i];
47006
47007 if (param.type !== "Identifier") { return false
47008 } }
47009 return true
47010 };
47011
47012 // Checks function params for various disallowed patterns such as using "eval"
47013 // or "arguments" and duplicate parameters.
47014
47015 pp$3.checkParams = function(node, allowDuplicates) {
47016 var nameHash = Object.create(null);
47017 for (var i = 0, list = node.params; i < list.length; i += 1)
47018 {
47019 var param = list[i];
47020
47021 this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);
47022 }
47023 };
47024
47025 // Parses a comma-separated list of expressions, and returns them as
47026 // an array. `close` is the token type that ends the list, and
47027 // `allowEmpty` can be turned on to allow subsequent commas with
47028 // nothing in between them to be parsed as `null` (which is needed
47029 // for array literals).
47030
47031 pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
47032 var elts = [], first = true;
47033 while (!this.eat(close)) {
47034 if (!first) {
47035 this.expect(types.comma);
47036 if (allowTrailingComma && this.afterTrailingComma(close)) { break }
47037 } else { first = false; }
47038
47039 var elt = (void 0);
47040 if (allowEmpty && this.type === types.comma)
47041 { elt = null; }
47042 else if (this.type === types.ellipsis) {
47043 elt = this.parseSpread(refDestructuringErrors);
47044 if (refDestructuringErrors && this.type === types.comma && refDestructuringErrors.trailingComma < 0)
47045 { refDestructuringErrors.trailingComma = this.start; }
47046 } else {
47047 elt = this.parseMaybeAssign(false, refDestructuringErrors);
47048 }
47049 elts.push(elt);
47050 }
47051 return elts
47052 };
47053
47054 pp$3.checkUnreserved = function(ref) {
47055 var start = ref.start;
47056 var end = ref.end;
47057 var name = ref.name;
47058
47059 if (this.inGenerator && name === "yield")
47060 { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }
47061 if (this.inAsync && name === "await")
47062 { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }
47063 if (this.currentThisScope().inClassFieldInit && name === "arguments")
47064 { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); }
47065 if (this.keywords.test(name))
47066 { this.raise(start, ("Unexpected keyword '" + name + "'")); }
47067 if (this.options.ecmaVersion < 6 &&
47068 this.input.slice(start, end).indexOf("\\") !== -1) { return }
47069 var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
47070 if (re.test(name)) {
47071 if (!this.inAsync && name === "await")
47072 { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }
47073 this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
47074 }
47075 };
47076
47077 // Parse the next token as an identifier. If `liberal` is true (used
47078 // when parsing properties), it will also convert keywords into
47079 // identifiers.
47080
47081 pp$3.parseIdent = function(liberal, isBinding) {
47082 var node = this.startNode();
47083 if (this.type === types.name) {
47084 node.name = this.value;
47085 } else if (this.type.keyword) {
47086 node.name = this.type.keyword;
47087
47088 // To fix https://github.com/acornjs/acorn/issues/575
47089 // `class` and `function` keywords push new context into this.context.
47090 // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
47091 // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
47092 if ((node.name === "class" || node.name === "function") &&
47093 (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
47094 this.context.pop();
47095 }
47096 } else {
47097 this.unexpected();
47098 }
47099 this.next(!!liberal);
47100 this.finishNode(node, "Identifier");
47101 if (!liberal) {
47102 this.checkUnreserved(node);
47103 if (node.name === "await" && !this.awaitIdentPos)
47104 { this.awaitIdentPos = node.start; }
47105 }
47106 return node
47107 };
47108
47109 pp$3.parsePrivateIdent = function() {
47110 var node = this.startNode();
47111 if (this.type === types.privateId) {
47112 node.name = this.value;
47113 } else {
47114 this.unexpected();
47115 }
47116 this.next();
47117 this.finishNode(node, "PrivateIdentifier");
47118
47119 // For validating existence
47120 if (this.privateNameStack.length === 0) {
47121 this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class"));
47122 } else {
47123 this.privateNameStack[this.privateNameStack.length - 1].used.push(node);
47124 }
47125
47126 return node
47127 };
47128
47129 // Parses yield expression inside generator.
47130
47131 pp$3.parseYield = function(forInit) {
47132 if (!this.yieldPos) { this.yieldPos = this.start; }
47133
47134 var node = this.startNode();
47135 this.next();
47136 if (this.type === types.semi || this.canInsertSemicolon() || (this.type !== types.star && !this.type.startsExpr)) {
47137 node.delegate = false;
47138 node.argument = null;
47139 } else {
47140 node.delegate = this.eat(types.star);
47141 node.argument = this.parseMaybeAssign(forInit);
47142 }
47143 return this.finishNode(node, "YieldExpression")
47144 };
47145
47146 pp$3.parseAwait = function() {
47147 if (!this.awaitPos) { this.awaitPos = this.start; }
47148
47149 var node = this.startNode();
47150 this.next();
47151 node.argument = this.parseMaybeUnary(null, true);
47152 return this.finishNode(node, "AwaitExpression")
47153 };
47154
47155 var pp$4 = Parser.prototype;
47156
47157 // This function is used to raise exceptions on parse errors. It
47158 // takes an offset integer (into the current `input`) to indicate
47159 // the location of the error, attaches the position to the end
47160 // of the error message, and then raises a `SyntaxError` with that
47161 // message.
47162
47163 pp$4.raise = function(pos, message) {
47164 var loc = getLineInfo(this.input, pos);
47165 message += " (" + loc.line + ":" + loc.column + ")";
47166 var err = new SyntaxError(message);
47167 err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
47168 throw err
47169 };
47170
47171 pp$4.raiseRecoverable = pp$4.raise;
47172
47173 pp$4.curPosition = function() {
47174 if (this.options.locations) {
47175 return new Position(this.curLine, this.pos - this.lineStart)
47176 }
47177 };
47178
47179 var pp$5 = Parser.prototype;
47180
47181 var Scope = function Scope(flags) {
47182 this.flags = flags;
47183 // A list of var-declared names in the current lexical scope
47184 this.var = [];
47185 // A list of lexically-declared names in the current lexical scope
47186 this.lexical = [];
47187 // A list of lexically-declared FunctionDeclaration names in the current lexical scope
47188 this.functions = [];
47189 // A switch to disallow the identifier reference 'arguments'
47190 this.inClassFieldInit = false;
47191 };
47192
47193 // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
47194
47195 pp$5.enterScope = function(flags) {
47196 this.scopeStack.push(new Scope(flags));
47197 };
47198
47199 pp$5.exitScope = function() {
47200 this.scopeStack.pop();
47201 };
47202
47203 // The spec says:
47204 // > At the top level of a function, or script, function declarations are
47205 // > treated like var declarations rather than like lexical declarations.
47206 pp$5.treatFunctionsAsVarInScope = function(scope) {
47207 return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)
47208 };
47209
47210 pp$5.declareName = function(name, bindingType, pos) {
47211 var redeclared = false;
47212 if (bindingType === BIND_LEXICAL) {
47213 var scope = this.currentScope();
47214 redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
47215 scope.lexical.push(name);
47216 if (this.inModule && (scope.flags & SCOPE_TOP))
47217 { delete this.undefinedExports[name]; }
47218 } else if (bindingType === BIND_SIMPLE_CATCH) {
47219 var scope$1 = this.currentScope();
47220 scope$1.lexical.push(name);
47221 } else if (bindingType === BIND_FUNCTION) {
47222 var scope$2 = this.currentScope();
47223 if (this.treatFunctionsAsVar)
47224 { redeclared = scope$2.lexical.indexOf(name) > -1; }
47225 else
47226 { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }
47227 scope$2.functions.push(name);
47228 } else {
47229 for (var i = this.scopeStack.length - 1; i >= 0; --i) {
47230 var scope$3 = this.scopeStack[i];
47231 if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||
47232 !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
47233 redeclared = true;
47234 break
47235 }
47236 scope$3.var.push(name);
47237 if (this.inModule && (scope$3.flags & SCOPE_TOP))
47238 { delete this.undefinedExports[name]; }
47239 if (scope$3.flags & SCOPE_VAR) { break }
47240 }
47241 }
47242 if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
47243 };
47244
47245 pp$5.checkLocalExport = function(id) {
47246 // scope.functions must be empty as Module code is always strict.
47247 if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
47248 this.scopeStack[0].var.indexOf(id.name) === -1) {
47249 this.undefinedExports[id.name] = id;
47250 }
47251 };
47252
47253 pp$5.currentScope = function() {
47254 return this.scopeStack[this.scopeStack.length - 1]
47255 };
47256
47257 pp$5.currentVarScope = function() {
47258 for (var i = this.scopeStack.length - 1;; i--) {
47259 var scope = this.scopeStack[i];
47260 if (scope.flags & SCOPE_VAR) { return scope }
47261 }
47262 };
47263
47264 // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
47265 pp$5.currentThisScope = function() {
47266 for (var i = this.scopeStack.length - 1;; i--) {
47267 var scope = this.scopeStack[i];
47268 if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }
47269 }
47270 };
47271
47272 var Node = function Node(parser, pos, loc) {
47273 this.type = "";
47274 this.start = pos;
47275 this.end = 0;
47276 if (parser.options.locations)
47277 { this.loc = new SourceLocation(parser, loc); }
47278 if (parser.options.directSourceFile)
47279 { this.sourceFile = parser.options.directSourceFile; }
47280 if (parser.options.ranges)
47281 { this.range = [pos, 0]; }
47282 };
47283
47284 // Start an AST node, attaching a start offset.
47285
47286 var pp$6 = Parser.prototype;
47287
47288 pp$6.startNode = function() {
47289 return new Node(this, this.start, this.startLoc)
47290 };
47291
47292 pp$6.startNodeAt = function(pos, loc) {
47293 return new Node(this, pos, loc)
47294 };
47295
47296 // Finish an AST node, adding `type` and `end` properties.
47297
47298 function finishNodeAt(node, type, pos, loc) {
47299 node.type = type;
47300 node.end = pos;
47301 if (this.options.locations)
47302 { node.loc.end = loc; }
47303 if (this.options.ranges)
47304 { node.range[1] = pos; }
47305 return node
47306 }
47307
47308 pp$6.finishNode = function(node, type) {
47309 return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
47310 };
47311
47312 // Finish node at given position
47313
47314 pp$6.finishNodeAt = function(node, type, pos, loc) {
47315 return finishNodeAt.call(this, node, type, pos, loc)
47316 };
47317
47318 pp$6.copyNode = function(node) {
47319 var newNode = new Node(this, node.start, this.startLoc);
47320 for (var prop in node) { newNode[prop] = node[prop]; }
47321 return newNode
47322 };
47323
47324 // The algorithm used to determine whether a regexp can appear at a
47325
47326 var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
47327 this.token = token;
47328 this.isExpr = !!isExpr;
47329 this.preserveSpace = !!preserveSpace;
47330 this.override = override;
47331 this.generator = !!generator;
47332 };
47333
47334 var types$1 = {
47335 b_stat: new TokContext("{", false),
47336 b_expr: new TokContext("{", true),
47337 b_tmpl: new TokContext("${", false),
47338 p_stat: new TokContext("(", false),
47339 p_expr: new TokContext("(", true),
47340 q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
47341 f_stat: new TokContext("function", false),
47342 f_expr: new TokContext("function", true),
47343 f_expr_gen: new TokContext("function", true, false, null, true),
47344 f_gen: new TokContext("function", false, false, null, true)
47345 };
47346
47347 var pp$7 = Parser.prototype;
47348
47349 pp$7.initialContext = function() {
47350 return [types$1.b_stat]
47351 };
47352
47353 pp$7.braceIsBlock = function(prevType) {
47354 var parent = this.curContext();
47355 if (parent === types$1.f_expr || parent === types$1.f_stat)
47356 { return true }
47357 if (prevType === types.colon && (parent === types$1.b_stat || parent === types$1.b_expr))
47358 { return !parent.isExpr }
47359
47360 // The check for `tt.name && exprAllowed` detects whether we are
47361 // after a `yield` or `of` construct. See the `updateContext` for
47362 // `tt.name`.
47363 if (prevType === types._return || prevType === types.name && this.exprAllowed)
47364 { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
47365 if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow)
47366 { return true }
47367 if (prevType === types.braceL)
47368 { return parent === types$1.b_stat }
47369 if (prevType === types._var || prevType === types._const || prevType === types.name)
47370 { return false }
47371 return !this.exprAllowed
47372 };
47373
47374 pp$7.inGeneratorContext = function() {
47375 for (var i = this.context.length - 1; i >= 1; i--) {
47376 var context = this.context[i];
47377 if (context.token === "function")
47378 { return context.generator }
47379 }
47380 return false
47381 };
47382
47383 pp$7.updateContext = function(prevType) {
47384 var update, type = this.type;
47385 if (type.keyword && prevType === types.dot)
47386 { this.exprAllowed = false; }
47387 else if (update = type.updateContext)
47388 { update.call(this, prevType); }
47389 else
47390 { this.exprAllowed = type.beforeExpr; }
47391 };
47392
47393 // Token-specific context update code
47394
47395 types.parenR.updateContext = types.braceR.updateContext = function() {
47396 if (this.context.length === 1) {
47397 this.exprAllowed = true;
47398 return
47399 }
47400 var out = this.context.pop();
47401 if (out === types$1.b_stat && this.curContext().token === "function") {
47402 out = this.context.pop();
47403 }
47404 this.exprAllowed = !out.isExpr;
47405 };
47406
47407 types.braceL.updateContext = function(prevType) {
47408 this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr);
47409 this.exprAllowed = true;
47410 };
47411
47412 types.dollarBraceL.updateContext = function() {
47413 this.context.push(types$1.b_tmpl);
47414 this.exprAllowed = true;
47415 };
47416
47417 types.parenL.updateContext = function(prevType) {
47418 var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while;
47419 this.context.push(statementParens ? types$1.p_stat : types$1.p_expr);
47420 this.exprAllowed = true;
47421 };
47422
47423 types.incDec.updateContext = function() {
47424 // tokExprAllowed stays unchanged
47425 };
47426
47427 types._function.updateContext = types._class.updateContext = function(prevType) {
47428 if (prevType.beforeExpr && prevType !== types._else &&
47429 !(prevType === types.semi && this.curContext() !== types$1.p_stat) &&
47430 !(prevType === types._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
47431 !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat))
47432 { this.context.push(types$1.f_expr); }
47433 else
47434 { this.context.push(types$1.f_stat); }
47435 this.exprAllowed = false;
47436 };
47437
47438 types.backQuote.updateContext = function() {
47439 if (this.curContext() === types$1.q_tmpl)
47440 { this.context.pop(); }
47441 else
47442 { this.context.push(types$1.q_tmpl); }
47443 this.exprAllowed = false;
47444 };
47445
47446 types.star.updateContext = function(prevType) {
47447 if (prevType === types._function) {
47448 var index = this.context.length - 1;
47449 if (this.context[index] === types$1.f_expr)
47450 { this.context[index] = types$1.f_expr_gen; }
47451 else
47452 { this.context[index] = types$1.f_gen; }
47453 }
47454 this.exprAllowed = true;
47455 };
47456
47457 types.name.updateContext = function(prevType) {
47458 var allowed = false;
47459 if (this.options.ecmaVersion >= 6 && prevType !== types.dot) {
47460 if (this.value === "of" && !this.exprAllowed ||
47461 this.value === "yield" && this.inGeneratorContext())
47462 { allowed = true; }
47463 }
47464 this.exprAllowed = allowed;
47465 };
47466
47467 // This file contains Unicode properties extracted from the ECMAScript
47468 // specification. The lists are extracted like so:
47469 // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)
47470
47471 // #table-binary-unicode-properties
47472 var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";
47473 var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
47474 var ecma11BinaryProperties = ecma10BinaryProperties;
47475 var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
47476 var unicodeBinaryProperties = {
47477 9: ecma9BinaryProperties,
47478 10: ecma10BinaryProperties,
47479 11: ecma11BinaryProperties,
47480 12: ecma12BinaryProperties
47481 };
47482
47483 // #table-unicode-general-category-values
47484 var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";
47485
47486 // #table-unicode-script-values
47487 var ecma9ScriptValues = "Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";
47488 var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
47489 var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
47490 var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
47491 var unicodeScriptValues = {
47492 9: ecma9ScriptValues,
47493 10: ecma10ScriptValues,
47494 11: ecma11ScriptValues,
47495 12: ecma12ScriptValues
47496 };
47497
47498 var data = {};
47499 function buildUnicodeData(ecmaVersion) {
47500 var d = data[ecmaVersion] = {
47501 binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
47502 nonBinary: {
47503 General_Category: wordsRegexp(unicodeGeneralCategoryValues),
47504 Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
47505 }
47506 };
47507 d.nonBinary.Script_Extensions = d.nonBinary.Script;
47508
47509 d.nonBinary.gc = d.nonBinary.General_Category;
47510 d.nonBinary.sc = d.nonBinary.Script;
47511 d.nonBinary.scx = d.nonBinary.Script_Extensions;
47512 }
47513 buildUnicodeData(9);
47514 buildUnicodeData(10);
47515 buildUnicodeData(11);
47516 buildUnicodeData(12);
47517
47518 var pp$8 = Parser.prototype;
47519
47520 var RegExpValidationState = function RegExpValidationState(parser) {
47521 this.parser = parser;
47522 this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "");
47523 this.unicodeProperties = data[parser.options.ecmaVersion >= 12 ? 12 : parser.options.ecmaVersion];
47524 this.source = "";
47525 this.flags = "";
47526 this.start = 0;
47527 this.switchU = false;
47528 this.switchN = false;
47529 this.pos = 0;
47530 this.lastIntValue = 0;
47531 this.lastStringValue = "";
47532 this.lastAssertionIsQuantifiable = false;
47533 this.numCapturingParens = 0;
47534 this.maxBackReference = 0;
47535 this.groupNames = [];
47536 this.backReferenceNames = [];
47537 };
47538
47539 RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {
47540 var unicode = flags.indexOf("u") !== -1;
47541 this.start = start | 0;
47542 this.source = pattern + "";
47543 this.flags = flags;
47544 this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
47545 this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
47546 };
47547
47548 RegExpValidationState.prototype.raise = function raise (message) {
47549 this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));
47550 };
47551
47552 // If u flag is given, this returns the code point at the index (it combines a surrogate pair).
47553 // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).
47554 RegExpValidationState.prototype.at = function at (i, forceU) {
47555 if ( forceU === void 0 ) forceU = false;
47556
47557 var s = this.source;
47558 var l = s.length;
47559 if (i >= l) {
47560 return -1
47561 }
47562 var c = s.charCodeAt(i);
47563 if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
47564 return c
47565 }
47566 var next = s.charCodeAt(i + 1);
47567 return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c
47568 };
47569
47570 RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {
47571 if ( forceU === void 0 ) forceU = false;
47572
47573 var s = this.source;
47574 var l = s.length;
47575 if (i >= l) {
47576 return l
47577 }
47578 var c = s.charCodeAt(i), next;
47579 if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||
47580 (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {
47581 return i + 1
47582 }
47583 return i + 2
47584 };
47585
47586 RegExpValidationState.prototype.current = function current (forceU) {
47587 if ( forceU === void 0 ) forceU = false;
47588
47589 return this.at(this.pos, forceU)
47590 };
47591
47592 RegExpValidationState.prototype.lookahead = function lookahead (forceU) {
47593 if ( forceU === void 0 ) forceU = false;
47594
47595 return this.at(this.nextIndex(this.pos, forceU), forceU)
47596 };
47597
47598 RegExpValidationState.prototype.advance = function advance (forceU) {
47599 if ( forceU === void 0 ) forceU = false;
47600
47601 this.pos = this.nextIndex(this.pos, forceU);
47602 };
47603
47604 RegExpValidationState.prototype.eat = function eat (ch, forceU) {
47605 if ( forceU === void 0 ) forceU = false;
47606
47607 if (this.current(forceU) === ch) {
47608 this.advance(forceU);
47609 return true
47610 }
47611 return false
47612 };
47613
47614 function codePointToString(ch) {
47615 if (ch <= 0xFFFF) { return String.fromCharCode(ch) }
47616 ch -= 0x10000;
47617 return String.fromCharCode((ch >> 10) + 0xD800, (ch & 0x03FF) + 0xDC00)
47618 }
47619
47620 /**
47621 * Validate the flags part of a given RegExpLiteral.
47622 *
47623 * @param {RegExpValidationState} state The state to validate RegExp.
47624 * @returns {void}
47625 */
47626 pp$8.validateRegExpFlags = function(state) {
47627 var validFlags = state.validFlags;
47628 var flags = state.flags;
47629
47630 for (var i = 0; i < flags.length; i++) {
47631 var flag = flags.charAt(i);
47632 if (validFlags.indexOf(flag) === -1) {
47633 this.raise(state.start, "Invalid regular expression flag");
47634 }
47635 if (flags.indexOf(flag, i + 1) > -1) {
47636 this.raise(state.start, "Duplicate regular expression flag");
47637 }
47638 }
47639 };
47640
47641 /**
47642 * Validate the pattern part of a given RegExpLiteral.
47643 *
47644 * @param {RegExpValidationState} state The state to validate RegExp.
47645 * @returns {void}
47646 */
47647 pp$8.validateRegExpPattern = function(state) {
47648 this.regexp_pattern(state);
47649
47650 // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
47651 // parsing contains a |GroupName|, reparse with the goal symbol
47652 // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
47653 // exception if _P_ did not conform to the grammar, if any elements of _P_
47654 // were not matched by the parse, or if any Early Error conditions exist.
47655 if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
47656 state.switchN = true;
47657 this.regexp_pattern(state);
47658 }
47659 };
47660
47661 // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern
47662 pp$8.regexp_pattern = function(state) {
47663 state.pos = 0;
47664 state.lastIntValue = 0;
47665 state.lastStringValue = "";
47666 state.lastAssertionIsQuantifiable = false;
47667 state.numCapturingParens = 0;
47668 state.maxBackReference = 0;
47669 state.groupNames.length = 0;
47670 state.backReferenceNames.length = 0;
47671
47672 this.regexp_disjunction(state);
47673
47674 if (state.pos !== state.source.length) {
47675 // Make the same messages as V8.
47676 if (state.eat(0x29 /* ) */)) {
47677 state.raise("Unmatched ')'");
47678 }
47679 if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {
47680 state.raise("Lone quantifier brackets");
47681 }
47682 }
47683 if (state.maxBackReference > state.numCapturingParens) {
47684 state.raise("Invalid escape");
47685 }
47686 for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
47687 var name = list[i];
47688
47689 if (state.groupNames.indexOf(name) === -1) {
47690 state.raise("Invalid named capture referenced");
47691 }
47692 }
47693 };
47694
47695 // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction
47696 pp$8.regexp_disjunction = function(state) {
47697 this.regexp_alternative(state);
47698 while (state.eat(0x7C /* | */)) {
47699 this.regexp_alternative(state);
47700 }
47701
47702 // Make the same message as V8.
47703 if (this.regexp_eatQuantifier(state, true)) {
47704 state.raise("Nothing to repeat");
47705 }
47706 if (state.eat(0x7B /* { */)) {
47707 state.raise("Lone quantifier brackets");
47708 }
47709 };
47710
47711 // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative
47712 pp$8.regexp_alternative = function(state) {
47713 while (state.pos < state.source.length && this.regexp_eatTerm(state))
47714 { }
47715 };
47716
47717 // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
47718 pp$8.regexp_eatTerm = function(state) {
47719 if (this.regexp_eatAssertion(state)) {
47720 // Handle `QuantifiableAssertion Quantifier` alternative.
47721 // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
47722 // is a QuantifiableAssertion.
47723 if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
47724 // Make the same message as V8.
47725 if (state.switchU) {
47726 state.raise("Invalid quantifier");
47727 }
47728 }
47729 return true
47730 }
47731
47732 if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
47733 this.regexp_eatQuantifier(state);
47734 return true
47735 }
47736
47737 return false
47738 };
47739
47740 // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion
47741 pp$8.regexp_eatAssertion = function(state) {
47742 var start = state.pos;
47743 state.lastAssertionIsQuantifiable = false;
47744
47745 // ^, $
47746 if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {
47747 return true
47748 }
47749
47750 // \b \B
47751 if (state.eat(0x5C /* \ */)) {
47752 if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {
47753 return true
47754 }
47755 state.pos = start;
47756 }
47757
47758 // Lookahead / Lookbehind
47759 if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {
47760 var lookbehind = false;
47761 if (this.options.ecmaVersion >= 9) {
47762 lookbehind = state.eat(0x3C /* < */);
47763 }
47764 if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {
47765 this.regexp_disjunction(state);
47766 if (!state.eat(0x29 /* ) */)) {
47767 state.raise("Unterminated group");
47768 }
47769 state.lastAssertionIsQuantifiable = !lookbehind;
47770 return true
47771 }
47772 }
47773
47774 state.pos = start;
47775 return false
47776 };
47777
47778 // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier
47779 pp$8.regexp_eatQuantifier = function(state, noError) {
47780 if ( noError === void 0 ) noError = false;
47781
47782 if (this.regexp_eatQuantifierPrefix(state, noError)) {
47783 state.eat(0x3F /* ? */);
47784 return true
47785 }
47786 return false
47787 };
47788
47789 // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
47790 pp$8.regexp_eatQuantifierPrefix = function(state, noError) {
47791 return (
47792 state.eat(0x2A /* * */) ||
47793 state.eat(0x2B /* + */) ||
47794 state.eat(0x3F /* ? */) ||
47795 this.regexp_eatBracedQuantifier(state, noError)
47796 )
47797 };
47798 pp$8.regexp_eatBracedQuantifier = function(state, noError) {
47799 var start = state.pos;
47800 if (state.eat(0x7B /* { */)) {
47801 var min = 0, max = -1;
47802 if (this.regexp_eatDecimalDigits(state)) {
47803 min = state.lastIntValue;
47804 if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {
47805 max = state.lastIntValue;
47806 }
47807 if (state.eat(0x7D /* } */)) {
47808 // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
47809 if (max !== -1 && max < min && !noError) {
47810 state.raise("numbers out of order in {} quantifier");
47811 }
47812 return true
47813 }
47814 }
47815 if (state.switchU && !noError) {
47816 state.raise("Incomplete quantifier");
47817 }
47818 state.pos = start;
47819 }
47820 return false
47821 };
47822
47823 // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
47824 pp$8.regexp_eatAtom = function(state) {
47825 return (
47826 this.regexp_eatPatternCharacters(state) ||
47827 state.eat(0x2E /* . */) ||
47828 this.regexp_eatReverseSolidusAtomEscape(state) ||
47829 this.regexp_eatCharacterClass(state) ||
47830 this.regexp_eatUncapturingGroup(state) ||
47831 this.regexp_eatCapturingGroup(state)
47832 )
47833 };
47834 pp$8.regexp_eatReverseSolidusAtomEscape = function(state) {
47835 var start = state.pos;
47836 if (state.eat(0x5C /* \ */)) {
47837 if (this.regexp_eatAtomEscape(state)) {
47838 return true
47839 }
47840 state.pos = start;
47841 }
47842 return false
47843 };
47844 pp$8.regexp_eatUncapturingGroup = function(state) {
47845 var start = state.pos;
47846 if (state.eat(0x28 /* ( */)) {
47847 if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {
47848 this.regexp_disjunction(state);
47849 if (state.eat(0x29 /* ) */)) {
47850 return true
47851 }
47852 state.raise("Unterminated group");
47853 }
47854 state.pos = start;
47855 }
47856 return false
47857 };
47858 pp$8.regexp_eatCapturingGroup = function(state) {
47859 if (state.eat(0x28 /* ( */)) {
47860 if (this.options.ecmaVersion >= 9) {
47861 this.regexp_groupSpecifier(state);
47862 } else if (state.current() === 0x3F /* ? */) {
47863 state.raise("Invalid group");
47864 }
47865 this.regexp_disjunction(state);
47866 if (state.eat(0x29 /* ) */)) {
47867 state.numCapturingParens += 1;
47868 return true
47869 }
47870 state.raise("Unterminated group");
47871 }
47872 return false
47873 };
47874
47875 // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom
47876 pp$8.regexp_eatExtendedAtom = function(state) {
47877 return (
47878 state.eat(0x2E /* . */) ||
47879 this.regexp_eatReverseSolidusAtomEscape(state) ||
47880 this.regexp_eatCharacterClass(state) ||
47881 this.regexp_eatUncapturingGroup(state) ||
47882 this.regexp_eatCapturingGroup(state) ||
47883 this.regexp_eatInvalidBracedQuantifier(state) ||
47884 this.regexp_eatExtendedPatternCharacter(state)
47885 )
47886 };
47887
47888 // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
47889 pp$8.regexp_eatInvalidBracedQuantifier = function(state) {
47890 if (this.regexp_eatBracedQuantifier(state, true)) {
47891 state.raise("Nothing to repeat");
47892 }
47893 return false
47894 };
47895
47896 // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter
47897 pp$8.regexp_eatSyntaxCharacter = function(state) {
47898 var ch = state.current();
47899 if (isSyntaxCharacter(ch)) {
47900 state.lastIntValue = ch;
47901 state.advance();
47902 return true
47903 }
47904 return false
47905 };
47906 function isSyntaxCharacter(ch) {
47907 return (
47908 ch === 0x24 /* $ */ ||
47909 ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||
47910 ch === 0x2E /* . */ ||
47911 ch === 0x3F /* ? */ ||
47912 ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||
47913 ch >= 0x7B /* { */ && ch <= 0x7D /* } */
47914 )
47915 }
47916
47917 // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter
47918 // But eat eager.
47919 pp$8.regexp_eatPatternCharacters = function(state) {
47920 var start = state.pos;
47921 var ch = 0;
47922 while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
47923 state.advance();
47924 }
47925 return state.pos !== start
47926 };
47927
47928 // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter
47929 pp$8.regexp_eatExtendedPatternCharacter = function(state) {
47930 var ch = state.current();
47931 if (
47932 ch !== -1 &&
47933 ch !== 0x24 /* $ */ &&
47934 !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&
47935 ch !== 0x2E /* . */ &&
47936 ch !== 0x3F /* ? */ &&
47937 ch !== 0x5B /* [ */ &&
47938 ch !== 0x5E /* ^ */ &&
47939 ch !== 0x7C /* | */
47940 ) {
47941 state.advance();
47942 return true
47943 }
47944 return false
47945 };
47946
47947 // GroupSpecifier ::
47948 // [empty]
47949 // `?` GroupName
47950 pp$8.regexp_groupSpecifier = function(state) {
47951 if (state.eat(0x3F /* ? */)) {
47952 if (this.regexp_eatGroupName(state)) {
47953 if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
47954 state.raise("Duplicate capture group name");
47955 }
47956 state.groupNames.push(state.lastStringValue);
47957 return
47958 }
47959 state.raise("Invalid group");
47960 }
47961 };
47962
47963 // GroupName ::
47964 // `<` RegExpIdentifierName `>`
47965 // Note: this updates `state.lastStringValue` property with the eaten name.
47966 pp$8.regexp_eatGroupName = function(state) {
47967 state.lastStringValue = "";
47968 if (state.eat(0x3C /* < */)) {
47969 if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {
47970 return true
47971 }
47972 state.raise("Invalid capture group name");
47973 }
47974 return false
47975 };
47976
47977 // RegExpIdentifierName ::
47978 // RegExpIdentifierStart
47979 // RegExpIdentifierName RegExpIdentifierPart
47980 // Note: this updates `state.lastStringValue` property with the eaten name.
47981 pp$8.regexp_eatRegExpIdentifierName = function(state) {
47982 state.lastStringValue = "";
47983 if (this.regexp_eatRegExpIdentifierStart(state)) {
47984 state.lastStringValue += codePointToString(state.lastIntValue);
47985 while (this.regexp_eatRegExpIdentifierPart(state)) {
47986 state.lastStringValue += codePointToString(state.lastIntValue);
47987 }
47988 return true
47989 }
47990 return false
47991 };
47992
47993 // RegExpIdentifierStart ::
47994 // UnicodeIDStart
47995 // `$`
47996 // `_`
47997 // `\` RegExpUnicodeEscapeSequence[+U]
47998 pp$8.regexp_eatRegExpIdentifierStart = function(state) {
47999 var start = state.pos;
48000 var forceU = this.options.ecmaVersion >= 11;
48001 var ch = state.current(forceU);
48002 state.advance(forceU);
48003
48004 if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
48005 ch = state.lastIntValue;
48006 }
48007 if (isRegExpIdentifierStart(ch)) {
48008 state.lastIntValue = ch;
48009 return true
48010 }
48011
48012 state.pos = start;
48013 return false
48014 };
48015 function isRegExpIdentifierStart(ch) {
48016 return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */
48017 }
48018
48019 // RegExpIdentifierPart ::
48020 // UnicodeIDContinue
48021 // `$`
48022 // `_`
48023 // `\` RegExpUnicodeEscapeSequence[+U]
48024 // <ZWNJ>
48025 // <ZWJ>
48026 pp$8.regexp_eatRegExpIdentifierPart = function(state) {
48027 var start = state.pos;
48028 var forceU = this.options.ecmaVersion >= 11;
48029 var ch = state.current(forceU);
48030 state.advance(forceU);
48031
48032 if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
48033 ch = state.lastIntValue;
48034 }
48035 if (isRegExpIdentifierPart(ch)) {
48036 state.lastIntValue = ch;
48037 return true
48038 }
48039
48040 state.pos = start;
48041 return false
48042 };
48043 function isRegExpIdentifierPart(ch) {
48044 return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */
48045 }
48046
48047 // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
48048 pp$8.regexp_eatAtomEscape = function(state) {
48049 if (
48050 this.regexp_eatBackReference(state) ||
48051 this.regexp_eatCharacterClassEscape(state) ||
48052 this.regexp_eatCharacterEscape(state) ||
48053 (state.switchN && this.regexp_eatKGroupName(state))
48054 ) {
48055 return true
48056 }
48057 if (state.switchU) {
48058 // Make the same message as V8.
48059 if (state.current() === 0x63 /* c */) {
48060 state.raise("Invalid unicode escape");
48061 }
48062 state.raise("Invalid escape");
48063 }
48064 return false
48065 };
48066 pp$8.regexp_eatBackReference = function(state) {
48067 var start = state.pos;
48068 if (this.regexp_eatDecimalEscape(state)) {
48069 var n = state.lastIntValue;
48070 if (state.switchU) {
48071 // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
48072 if (n > state.maxBackReference) {
48073 state.maxBackReference = n;
48074 }
48075 return true
48076 }
48077 if (n <= state.numCapturingParens) {
48078 return true
48079 }
48080 state.pos = start;
48081 }
48082 return false
48083 };
48084 pp$8.regexp_eatKGroupName = function(state) {
48085 if (state.eat(0x6B /* k */)) {
48086 if (this.regexp_eatGroupName(state)) {
48087 state.backReferenceNames.push(state.lastStringValue);
48088 return true
48089 }
48090 state.raise("Invalid named reference");
48091 }
48092 return false
48093 };
48094
48095 // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
48096 pp$8.regexp_eatCharacterEscape = function(state) {
48097 return (
48098 this.regexp_eatControlEscape(state) ||
48099 this.regexp_eatCControlLetter(state) ||
48100 this.regexp_eatZero(state) ||
48101 this.regexp_eatHexEscapeSequence(state) ||
48102 this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||
48103 (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
48104 this.regexp_eatIdentityEscape(state)
48105 )
48106 };
48107 pp$8.regexp_eatCControlLetter = function(state) {
48108 var start = state.pos;
48109 if (state.eat(0x63 /* c */)) {
48110 if (this.regexp_eatControlLetter(state)) {
48111 return true
48112 }
48113 state.pos = start;
48114 }
48115 return false
48116 };
48117 pp$8.regexp_eatZero = function(state) {
48118 if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {
48119 state.lastIntValue = 0;
48120 state.advance();
48121 return true
48122 }
48123 return false
48124 };
48125
48126 // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape
48127 pp$8.regexp_eatControlEscape = function(state) {
48128 var ch = state.current();
48129 if (ch === 0x74 /* t */) {
48130 state.lastIntValue = 0x09; /* \t */
48131 state.advance();
48132 return true
48133 }
48134 if (ch === 0x6E /* n */) {
48135 state.lastIntValue = 0x0A; /* \n */
48136 state.advance();
48137 return true
48138 }
48139 if (ch === 0x76 /* v */) {
48140 state.lastIntValue = 0x0B; /* \v */
48141 state.advance();
48142 return true
48143 }
48144 if (ch === 0x66 /* f */) {
48145 state.lastIntValue = 0x0C; /* \f */
48146 state.advance();
48147 return true
48148 }
48149 if (ch === 0x72 /* r */) {
48150 state.lastIntValue = 0x0D; /* \r */
48151 state.advance();
48152 return true
48153 }
48154 return false
48155 };
48156
48157 // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter
48158 pp$8.regexp_eatControlLetter = function(state) {
48159 var ch = state.current();
48160 if (isControlLetter(ch)) {
48161 state.lastIntValue = ch % 0x20;
48162 state.advance();
48163 return true
48164 }
48165 return false
48166 };
48167 function isControlLetter(ch) {
48168 return (
48169 (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||
48170 (ch >= 0x61 /* a */ && ch <= 0x7A /* z */)
48171 )
48172 }
48173
48174 // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
48175 pp$8.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
48176 if ( forceU === void 0 ) forceU = false;
48177
48178 var start = state.pos;
48179 var switchU = forceU || state.switchU;
48180
48181 if (state.eat(0x75 /* u */)) {
48182 if (this.regexp_eatFixedHexDigits(state, 4)) {
48183 var lead = state.lastIntValue;
48184 if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {
48185 var leadSurrogateEnd = state.pos;
48186 if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
48187 var trail = state.lastIntValue;
48188 if (trail >= 0xDC00 && trail <= 0xDFFF) {
48189 state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
48190 return true
48191 }
48192 }
48193 state.pos = leadSurrogateEnd;
48194 state.lastIntValue = lead;
48195 }
48196 return true
48197 }
48198 if (
48199 switchU &&
48200 state.eat(0x7B /* { */) &&
48201 this.regexp_eatHexDigits(state) &&
48202 state.eat(0x7D /* } */) &&
48203 isValidUnicode(state.lastIntValue)
48204 ) {
48205 return true
48206 }
48207 if (switchU) {
48208 state.raise("Invalid unicode escape");
48209 }
48210 state.pos = start;
48211 }
48212
48213 return false
48214 };
48215 function isValidUnicode(ch) {
48216 return ch >= 0 && ch <= 0x10FFFF
48217 }
48218
48219 // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
48220 pp$8.regexp_eatIdentityEscape = function(state) {
48221 if (state.switchU) {
48222 if (this.regexp_eatSyntaxCharacter(state)) {
48223 return true
48224 }
48225 if (state.eat(0x2F /* / */)) {
48226 state.lastIntValue = 0x2F; /* / */
48227 return true
48228 }
48229 return false
48230 }
48231
48232 var ch = state.current();
48233 if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {
48234 state.lastIntValue = ch;
48235 state.advance();
48236 return true
48237 }
48238
48239 return false
48240 };
48241
48242 // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape
48243 pp$8.regexp_eatDecimalEscape = function(state) {
48244 state.lastIntValue = 0;
48245 var ch = state.current();
48246 if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {
48247 do {
48248 state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
48249 state.advance();
48250 } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)
48251 return true
48252 }
48253 return false
48254 };
48255
48256 // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape
48257 pp$8.regexp_eatCharacterClassEscape = function(state) {
48258 var ch = state.current();
48259
48260 if (isCharacterClassEscape(ch)) {
48261 state.lastIntValue = -1;
48262 state.advance();
48263 return true
48264 }
48265
48266 if (
48267 state.switchU &&
48268 this.options.ecmaVersion >= 9 &&
48269 (ch === 0x50 /* P */ || ch === 0x70 /* p */)
48270 ) {
48271 state.lastIntValue = -1;
48272 state.advance();
48273 if (
48274 state.eat(0x7B /* { */) &&
48275 this.regexp_eatUnicodePropertyValueExpression(state) &&
48276 state.eat(0x7D /* } */)
48277 ) {
48278 return true
48279 }
48280 state.raise("Invalid property name");
48281 }
48282
48283 return false
48284 };
48285 function isCharacterClassEscape(ch) {
48286 return (
48287 ch === 0x64 /* d */ ||
48288 ch === 0x44 /* D */ ||
48289 ch === 0x73 /* s */ ||
48290 ch === 0x53 /* S */ ||
48291 ch === 0x77 /* w */ ||
48292 ch === 0x57 /* W */
48293 )
48294 }
48295
48296 // UnicodePropertyValueExpression ::
48297 // UnicodePropertyName `=` UnicodePropertyValue
48298 // LoneUnicodePropertyNameOrValue
48299 pp$8.regexp_eatUnicodePropertyValueExpression = function(state) {
48300 var start = state.pos;
48301
48302 // UnicodePropertyName `=` UnicodePropertyValue
48303 if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
48304 var name = state.lastStringValue;
48305 if (this.regexp_eatUnicodePropertyValue(state)) {
48306 var value = state.lastStringValue;
48307 this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
48308 return true
48309 }
48310 }
48311 state.pos = start;
48312
48313 // LoneUnicodePropertyNameOrValue
48314 if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
48315 var nameOrValue = state.lastStringValue;
48316 this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
48317 return true
48318 }
48319 return false
48320 };
48321 pp$8.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
48322 if (!has(state.unicodeProperties.nonBinary, name))
48323 { state.raise("Invalid property name"); }
48324 if (!state.unicodeProperties.nonBinary[name].test(value))
48325 { state.raise("Invalid property value"); }
48326 };
48327 pp$8.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
48328 if (!state.unicodeProperties.binary.test(nameOrValue))
48329 { state.raise("Invalid property name"); }
48330 };
48331
48332 // UnicodePropertyName ::
48333 // UnicodePropertyNameCharacters
48334 pp$8.regexp_eatUnicodePropertyName = function(state) {
48335 var ch = 0;
48336 state.lastStringValue = "";
48337 while (isUnicodePropertyNameCharacter(ch = state.current())) {
48338 state.lastStringValue += codePointToString(ch);
48339 state.advance();
48340 }
48341 return state.lastStringValue !== ""
48342 };
48343 function isUnicodePropertyNameCharacter(ch) {
48344 return isControlLetter(ch) || ch === 0x5F /* _ */
48345 }
48346
48347 // UnicodePropertyValue ::
48348 // UnicodePropertyValueCharacters
48349 pp$8.regexp_eatUnicodePropertyValue = function(state) {
48350 var ch = 0;
48351 state.lastStringValue = "";
48352 while (isUnicodePropertyValueCharacter(ch = state.current())) {
48353 state.lastStringValue += codePointToString(ch);
48354 state.advance();
48355 }
48356 return state.lastStringValue !== ""
48357 };
48358 function isUnicodePropertyValueCharacter(ch) {
48359 return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)
48360 }
48361
48362 // LoneUnicodePropertyNameOrValue ::
48363 // UnicodePropertyValueCharacters
48364 pp$8.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
48365 return this.regexp_eatUnicodePropertyValue(state)
48366 };
48367
48368 // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
48369 pp$8.regexp_eatCharacterClass = function(state) {
48370 if (state.eat(0x5B /* [ */)) {
48371 state.eat(0x5E /* ^ */);
48372 this.regexp_classRanges(state);
48373 if (state.eat(0x5D /* ] */)) {
48374 return true
48375 }
48376 // Unreachable since it threw "unterminated regular expression" error before.
48377 state.raise("Unterminated character class");
48378 }
48379 return false
48380 };
48381
48382 // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
48383 // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
48384 // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
48385 pp$8.regexp_classRanges = function(state) {
48386 while (this.regexp_eatClassAtom(state)) {
48387 var left = state.lastIntValue;
48388 if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {
48389 var right = state.lastIntValue;
48390 if (state.switchU && (left === -1 || right === -1)) {
48391 state.raise("Invalid character class");
48392 }
48393 if (left !== -1 && right !== -1 && left > right) {
48394 state.raise("Range out of order in character class");
48395 }
48396 }
48397 }
48398 };
48399
48400 // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom
48401 // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash
48402 pp$8.regexp_eatClassAtom = function(state) {
48403 var start = state.pos;
48404
48405 if (state.eat(0x5C /* \ */)) {
48406 if (this.regexp_eatClassEscape(state)) {
48407 return true
48408 }
48409 if (state.switchU) {
48410 // Make the same message as V8.
48411 var ch$1 = state.current();
48412 if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {
48413 state.raise("Invalid class escape");
48414 }
48415 state.raise("Invalid escape");
48416 }
48417 state.pos = start;
48418 }
48419
48420 var ch = state.current();
48421 if (ch !== 0x5D /* ] */) {
48422 state.lastIntValue = ch;
48423 state.advance();
48424 return true
48425 }
48426
48427 return false
48428 };
48429
48430 // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape
48431 pp$8.regexp_eatClassEscape = function(state) {
48432 var start = state.pos;
48433
48434 if (state.eat(0x62 /* b */)) {
48435 state.lastIntValue = 0x08; /* <BS> */
48436 return true
48437 }
48438
48439 if (state.switchU && state.eat(0x2D /* - */)) {
48440 state.lastIntValue = 0x2D; /* - */
48441 return true
48442 }
48443
48444 if (!state.switchU && state.eat(0x63 /* c */)) {
48445 if (this.regexp_eatClassControlLetter(state)) {
48446 return true
48447 }
48448 state.pos = start;
48449 }
48450
48451 return (
48452 this.regexp_eatCharacterClassEscape(state) ||
48453 this.regexp_eatCharacterEscape(state)
48454 )
48455 };
48456
48457 // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter
48458 pp$8.regexp_eatClassControlLetter = function(state) {
48459 var ch = state.current();
48460 if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {
48461 state.lastIntValue = ch % 0x20;
48462 state.advance();
48463 return true
48464 }
48465 return false
48466 };
48467
48468 // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
48469 pp$8.regexp_eatHexEscapeSequence = function(state) {
48470 var start = state.pos;
48471 if (state.eat(0x78 /* x */)) {
48472 if (this.regexp_eatFixedHexDigits(state, 2)) {
48473 return true
48474 }
48475 if (state.switchU) {
48476 state.raise("Invalid escape");
48477 }
48478 state.pos = start;
48479 }
48480 return false
48481 };
48482
48483 // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits
48484 pp$8.regexp_eatDecimalDigits = function(state) {
48485 var start = state.pos;
48486 var ch = 0;
48487 state.lastIntValue = 0;
48488 while (isDecimalDigit(ch = state.current())) {
48489 state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
48490 state.advance();
48491 }
48492 return state.pos !== start
48493 };
48494 function isDecimalDigit(ch) {
48495 return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */
48496 }
48497
48498 // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits
48499 pp$8.regexp_eatHexDigits = function(state) {
48500 var start = state.pos;
48501 var ch = 0;
48502 state.lastIntValue = 0;
48503 while (isHexDigit(ch = state.current())) {
48504 state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
48505 state.advance();
48506 }
48507 return state.pos !== start
48508 };
48509 function isHexDigit(ch) {
48510 return (
48511 (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||
48512 (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||
48513 (ch >= 0x61 /* a */ && ch <= 0x66 /* f */)
48514 )
48515 }
48516 function hexToInt(ch) {
48517 if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {
48518 return 10 + (ch - 0x41 /* A */)
48519 }
48520 if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {
48521 return 10 + (ch - 0x61 /* a */)
48522 }
48523 return ch - 0x30 /* 0 */
48524 }
48525
48526 // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence
48527 // Allows only 0-377(octal) i.e. 0-255(decimal).
48528 pp$8.regexp_eatLegacyOctalEscapeSequence = function(state) {
48529 if (this.regexp_eatOctalDigit(state)) {
48530 var n1 = state.lastIntValue;
48531 if (this.regexp_eatOctalDigit(state)) {
48532 var n2 = state.lastIntValue;
48533 if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
48534 state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
48535 } else {
48536 state.lastIntValue = n1 * 8 + n2;
48537 }
48538 } else {
48539 state.lastIntValue = n1;
48540 }
48541 return true
48542 }
48543 return false
48544 };
48545
48546 // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit
48547 pp$8.regexp_eatOctalDigit = function(state) {
48548 var ch = state.current();
48549 if (isOctalDigit(ch)) {
48550 state.lastIntValue = ch - 0x30; /* 0 */
48551 state.advance();
48552 return true
48553 }
48554 state.lastIntValue = 0;
48555 return false
48556 };
48557 function isOctalDigit(ch) {
48558 return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */
48559 }
48560
48561 // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits
48562 // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit
48563 // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
48564 pp$8.regexp_eatFixedHexDigits = function(state, length) {
48565 var start = state.pos;
48566 state.lastIntValue = 0;
48567 for (var i = 0; i < length; ++i) {
48568 var ch = state.current();
48569 if (!isHexDigit(ch)) {
48570 state.pos = start;
48571 return false
48572 }
48573 state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
48574 state.advance();
48575 }
48576 return true
48577 };
48578
48579 // Object type used to represent tokens. Note that normally, tokens
48580 // simply exist as properties on the parser object. This is only
48581 // used for the onToken callback and the external tokenizer.
48582
48583 var Token = function Token(p) {
48584 this.type = p.type;
48585 this.value = p.value;
48586 this.start = p.start;
48587 this.end = p.end;
48588 if (p.options.locations)
48589 { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
48590 if (p.options.ranges)
48591 { this.range = [p.start, p.end]; }
48592 };
48593
48594 // ## Tokenizer
48595
48596 var pp$9 = Parser.prototype;
48597
48598 // Move to the next token
48599
48600 pp$9.next = function(ignoreEscapeSequenceInKeyword) {
48601 if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)
48602 { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); }
48603 if (this.options.onToken)
48604 { this.options.onToken(new Token(this)); }
48605
48606 this.lastTokEnd = this.end;
48607 this.lastTokStart = this.start;
48608 this.lastTokEndLoc = this.endLoc;
48609 this.lastTokStartLoc = this.startLoc;
48610 this.nextToken();
48611 };
48612
48613 pp$9.getToken = function() {
48614 this.next();
48615 return new Token(this)
48616 };
48617
48618 // If we're in an ES6 environment, make parsers iterable
48619 if (typeof Symbol !== "undefined")
48620 { pp$9[Symbol.iterator] = function() {
48621 var this$1$1 = this;
48622
48623 return {
48624 next: function () {
48625 var token = this$1$1.getToken();
48626 return {
48627 done: token.type === types.eof,
48628 value: token
48629 }
48630 }
48631 }
48632 }; }
48633
48634 // Toggle strict mode. Re-reads the next number or string to please
48635 // pedantic tests (`"use strict"; 010;` should fail).
48636
48637 pp$9.curContext = function() {
48638 return this.context[this.context.length - 1]
48639 };
48640
48641 // Read a single token, updating the parser object's token-related
48642 // properties.
48643
48644 pp$9.nextToken = function() {
48645 var curContext = this.curContext();
48646 if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
48647
48648 this.start = this.pos;
48649 if (this.options.locations) { this.startLoc = this.curPosition(); }
48650 if (this.pos >= this.input.length) { return this.finishToken(types.eof) }
48651
48652 if (curContext.override) { return curContext.override(this) }
48653 else { this.readToken(this.fullCharCodeAtPos()); }
48654 };
48655
48656 pp$9.readToken = function(code) {
48657 // Identifier or keyword. '\uXXXX' sequences are allowed in
48658 // identifiers, so '\' also dispatches to that.
48659 if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
48660 { return this.readWord() }
48661
48662 return this.getTokenFromCode(code)
48663 };
48664
48665 pp$9.fullCharCodeAtPos = function() {
48666 var code = this.input.charCodeAt(this.pos);
48667 if (code <= 0xd7ff || code >= 0xdc00) { return code }
48668 var next = this.input.charCodeAt(this.pos + 1);
48669 return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00
48670 };
48671
48672 pp$9.skipBlockComment = function() {
48673 var startLoc = this.options.onComment && this.curPosition();
48674 var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
48675 if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
48676 this.pos = end + 2;
48677 if (this.options.locations) {
48678 lineBreakG.lastIndex = start;
48679 var match;
48680 while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {
48681 ++this.curLine;
48682 this.lineStart = match.index + match[0].length;
48683 }
48684 }
48685 if (this.options.onComment)
48686 { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
48687 startLoc, this.curPosition()); }
48688 };
48689
48690 pp$9.skipLineComment = function(startSkip) {
48691 var start = this.pos;
48692 var startLoc = this.options.onComment && this.curPosition();
48693 var ch = this.input.charCodeAt(this.pos += startSkip);
48694 while (this.pos < this.input.length && !isNewLine(ch)) {
48695 ch = this.input.charCodeAt(++this.pos);
48696 }
48697 if (this.options.onComment)
48698 { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
48699 startLoc, this.curPosition()); }
48700 };
48701
48702 // Called at the start of the parse and after every token. Skips
48703 // whitespace and comments, and.
48704
48705 pp$9.skipSpace = function() {
48706 loop: while (this.pos < this.input.length) {
48707 var ch = this.input.charCodeAt(this.pos);
48708 switch (ch) {
48709 case 32: case 160: // ' '
48710 ++this.pos;
48711 break
48712 case 13:
48713 if (this.input.charCodeAt(this.pos + 1) === 10) {
48714 ++this.pos;
48715 }
48716 case 10: case 8232: case 8233:
48717 ++this.pos;
48718 if (this.options.locations) {
48719 ++this.curLine;
48720 this.lineStart = this.pos;
48721 }
48722 break
48723 case 47: // '/'
48724 switch (this.input.charCodeAt(this.pos + 1)) {
48725 case 42: // '*'
48726 this.skipBlockComment();
48727 break
48728 case 47:
48729 this.skipLineComment(2);
48730 break
48731 default:
48732 break loop
48733 }
48734 break
48735 default:
48736 if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
48737 ++this.pos;
48738 } else {
48739 break loop
48740 }
48741 }
48742 }
48743 };
48744
48745 // Called at the end of every token. Sets `end`, `val`, and
48746 // maintains `context` and `exprAllowed`, and skips the space after
48747 // the token, so that the next one's `start` will point at the
48748 // right position.
48749
48750 pp$9.finishToken = function(type, val) {
48751 this.end = this.pos;
48752 if (this.options.locations) { this.endLoc = this.curPosition(); }
48753 var prevType = this.type;
48754 this.type = type;
48755 this.value = val;
48756
48757 this.updateContext(prevType);
48758 };
48759
48760 // ### Token reading
48761
48762 // This is the function that is called to fetch the next token. It
48763 // is somewhat obscure, because it works in character codes rather
48764 // than characters, and because operator parsing has been inlined
48765 // into it.
48766 //
48767 // All in the name of speed.
48768 //
48769 pp$9.readToken_dot = function() {
48770 var next = this.input.charCodeAt(this.pos + 1);
48771 if (next >= 48 && next <= 57) { return this.readNumber(true) }
48772 var next2 = this.input.charCodeAt(this.pos + 2);
48773 if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
48774 this.pos += 3;
48775 return this.finishToken(types.ellipsis)
48776 } else {
48777 ++this.pos;
48778 return this.finishToken(types.dot)
48779 }
48780 };
48781
48782 pp$9.readToken_slash = function() { // '/'
48783 var next = this.input.charCodeAt(this.pos + 1);
48784 if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
48785 if (next === 61) { return this.finishOp(types.assign, 2) }
48786 return this.finishOp(types.slash, 1)
48787 };
48788
48789 pp$9.readToken_mult_modulo_exp = function(code) { // '%*'
48790 var next = this.input.charCodeAt(this.pos + 1);
48791 var size = 1;
48792 var tokentype = code === 42 ? types.star : types.modulo;
48793
48794 // exponentiation operator ** and **=
48795 if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
48796 ++size;
48797 tokentype = types.starstar;
48798 next = this.input.charCodeAt(this.pos + 2);
48799 }
48800
48801 if (next === 61) { return this.finishOp(types.assign, size + 1) }
48802 return this.finishOp(tokentype, size)
48803 };
48804
48805 pp$9.readToken_pipe_amp = function(code) { // '|&'
48806 var next = this.input.charCodeAt(this.pos + 1);
48807 if (next === code) {
48808 if (this.options.ecmaVersion >= 12) {
48809 var next2 = this.input.charCodeAt(this.pos + 2);
48810 if (next2 === 61) { return this.finishOp(types.assign, 3) }
48811 }
48812 return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2)
48813 }
48814 if (next === 61) { return this.finishOp(types.assign, 2) }
48815 return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1)
48816 };
48817
48818 pp$9.readToken_caret = function() { // '^'
48819 var next = this.input.charCodeAt(this.pos + 1);
48820 if (next === 61) { return this.finishOp(types.assign, 2) }
48821 return this.finishOp(types.bitwiseXOR, 1)
48822 };
48823
48824 pp$9.readToken_plus_min = function(code) { // '+-'
48825 var next = this.input.charCodeAt(this.pos + 1);
48826 if (next === code) {
48827 if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&
48828 (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
48829 // A `-->` line comment
48830 this.skipLineComment(3);
48831 this.skipSpace();
48832 return this.nextToken()
48833 }
48834 return this.finishOp(types.incDec, 2)
48835 }
48836 if (next === 61) { return this.finishOp(types.assign, 2) }
48837 return this.finishOp(types.plusMin, 1)
48838 };
48839
48840 pp$9.readToken_lt_gt = function(code) { // '<>'
48841 var next = this.input.charCodeAt(this.pos + 1);
48842 var size = 1;
48843 if (next === code) {
48844 size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
48845 if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types.assign, size + 1) }
48846 return this.finishOp(types.bitShift, size)
48847 }
48848 if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&
48849 this.input.charCodeAt(this.pos + 3) === 45) {
48850 // `<!--`, an XML-style comment that should be interpreted as a line comment
48851 this.skipLineComment(4);
48852 this.skipSpace();
48853 return this.nextToken()
48854 }
48855 if (next === 61) { size = 2; }
48856 return this.finishOp(types.relational, size)
48857 };
48858
48859 pp$9.readToken_eq_excl = function(code) { // '=!'
48860 var next = this.input.charCodeAt(this.pos + 1);
48861 if (next === 61) { return this.finishOp(types.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
48862 if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
48863 this.pos += 2;
48864 return this.finishToken(types.arrow)
48865 }
48866 return this.finishOp(code === 61 ? types.eq : types.prefix, 1)
48867 };
48868
48869 pp$9.readToken_question = function() { // '?'
48870 var ecmaVersion = this.options.ecmaVersion;
48871 if (ecmaVersion >= 11) {
48872 var next = this.input.charCodeAt(this.pos + 1);
48873 if (next === 46) {
48874 var next2 = this.input.charCodeAt(this.pos + 2);
48875 if (next2 < 48 || next2 > 57) { return this.finishOp(types.questionDot, 2) }
48876 }
48877 if (next === 63) {
48878 if (ecmaVersion >= 12) {
48879 var next2$1 = this.input.charCodeAt(this.pos + 2);
48880 if (next2$1 === 61) { return this.finishOp(types.assign, 3) }
48881 }
48882 return this.finishOp(types.coalesce, 2)
48883 }
48884 }
48885 return this.finishOp(types.question, 1)
48886 };
48887
48888 pp$9.readToken_numberSign = function() { // '#'
48889 var ecmaVersion = this.options.ecmaVersion;
48890 var code = 35; // '#'
48891 if (ecmaVersion >= 13) {
48892 ++this.pos;
48893 code = this.fullCharCodeAtPos();
48894 if (isIdentifierStart(code, true) || code === 92 /* '\' */) {
48895 return this.finishToken(types.privateId, this.readWord1())
48896 }
48897 }
48898
48899 this.raise(this.pos, "Unexpected character '" + codePointToString$1(code) + "'");
48900 };
48901
48902 pp$9.getTokenFromCode = function(code) {
48903 switch (code) {
48904 // The interpretation of a dot depends on whether it is followed
48905 // by a digit or another two dots.
48906 case 46: // '.'
48907 return this.readToken_dot()
48908
48909 // Punctuation tokens.
48910 case 40: ++this.pos; return this.finishToken(types.parenL)
48911 case 41: ++this.pos; return this.finishToken(types.parenR)
48912 case 59: ++this.pos; return this.finishToken(types.semi)
48913 case 44: ++this.pos; return this.finishToken(types.comma)
48914 case 91: ++this.pos; return this.finishToken(types.bracketL)
48915 case 93: ++this.pos; return this.finishToken(types.bracketR)
48916 case 123: ++this.pos; return this.finishToken(types.braceL)
48917 case 125: ++this.pos; return this.finishToken(types.braceR)
48918 case 58: ++this.pos; return this.finishToken(types.colon)
48919
48920 case 96: // '`'
48921 if (this.options.ecmaVersion < 6) { break }
48922 ++this.pos;
48923 return this.finishToken(types.backQuote)
48924
48925 case 48: // '0'
48926 var next = this.input.charCodeAt(this.pos + 1);
48927 if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
48928 if (this.options.ecmaVersion >= 6) {
48929 if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
48930 if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
48931 }
48932
48933 // Anything else beginning with a digit is an integer, octal
48934 // number, or float.
48935 case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
48936 return this.readNumber(false)
48937
48938 // Quotes produce strings.
48939 case 34: case 39: // '"', "'"
48940 return this.readString(code)
48941
48942 // Operators are parsed inline in tiny state machines. '=' (61) is
48943 // often referred to. `finishOp` simply skips the amount of
48944 // characters it is given as second argument, and returns a token
48945 // of the type given by its first argument.
48946
48947 case 47: // '/'
48948 return this.readToken_slash()
48949
48950 case 37: case 42: // '%*'
48951 return this.readToken_mult_modulo_exp(code)
48952
48953 case 124: case 38: // '|&'
48954 return this.readToken_pipe_amp(code)
48955
48956 case 94: // '^'
48957 return this.readToken_caret()
48958
48959 case 43: case 45: // '+-'
48960 return this.readToken_plus_min(code)
48961
48962 case 60: case 62: // '<>'
48963 return this.readToken_lt_gt(code)
48964
48965 case 61: case 33: // '=!'
48966 return this.readToken_eq_excl(code)
48967
48968 case 63: // '?'
48969 return this.readToken_question()
48970
48971 case 126: // '~'
48972 return this.finishOp(types.prefix, 1)
48973
48974 case 35: // '#'
48975 return this.readToken_numberSign()
48976 }
48977
48978 this.raise(this.pos, "Unexpected character '" + codePointToString$1(code) + "'");
48979 };
48980
48981 pp$9.finishOp = function(type, size) {
48982 var str = this.input.slice(this.pos, this.pos + size);
48983 this.pos += size;
48984 return this.finishToken(type, str)
48985 };
48986
48987 pp$9.readRegexp = function() {
48988 var escaped, inClass, start = this.pos;
48989 for (;;) {
48990 if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }
48991 var ch = this.input.charAt(this.pos);
48992 if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }
48993 if (!escaped) {
48994 if (ch === "[") { inClass = true; }
48995 else if (ch === "]" && inClass) { inClass = false; }
48996 else if (ch === "/" && !inClass) { break }
48997 escaped = ch === "\\";
48998 } else { escaped = false; }
48999 ++this.pos;
49000 }
49001 var pattern = this.input.slice(start, this.pos);
49002 ++this.pos;
49003 var flagsStart = this.pos;
49004 var flags = this.readWord1();
49005 if (this.containsEsc) { this.unexpected(flagsStart); }
49006
49007 // Validate pattern
49008 var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
49009 state.reset(start, pattern, flags);
49010 this.validateRegExpFlags(state);
49011 this.validateRegExpPattern(state);
49012
49013 // Create Literal#value property value.
49014 var value = null;
49015 try {
49016 value = new RegExp(pattern, flags);
49017 } catch (e) {
49018 // ESTree requires null if it failed to instantiate RegExp object.
49019 // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral
49020 }
49021
49022 return this.finishToken(types.regexp, {pattern: pattern, flags: flags, value: value})
49023 };
49024
49025 // Read an integer in the given radix. Return null if zero digits
49026 // were read, the integer value otherwise. When `len` is given, this
49027 // will return `null` unless the integer has exactly `len` digits.
49028
49029 pp$9.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
49030 // `len` is used for character escape sequences. In that case, disallow separators.
49031 var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined;
49032
49033 // `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b)
49034 // and isn't fraction part nor exponent part. In that case, if the first digit
49035 // is zero then disallow separators.
49036 var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
49037
49038 var start = this.pos, total = 0, lastCode = 0;
49039 for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {
49040 var code = this.input.charCodeAt(this.pos), val = (void 0);
49041
49042 if (allowSeparators && code === 95) {
49043 if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); }
49044 if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); }
49045 if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); }
49046 lastCode = code;
49047 continue
49048 }
49049
49050 if (code >= 97) { val = code - 97 + 10; } // a
49051 else if (code >= 65) { val = code - 65 + 10; } // A
49052 else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
49053 else { val = Infinity; }
49054 if (val >= radix) { break }
49055 lastCode = code;
49056 total = total * radix + val;
49057 }
49058
49059 if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); }
49060 if (this.pos === start || len != null && this.pos - start !== len) { return null }
49061
49062 return total
49063 };
49064
49065 function stringToNumber(str, isLegacyOctalNumericLiteral) {
49066 if (isLegacyOctalNumericLiteral) {
49067 return parseInt(str, 8)
49068 }
49069
49070 // `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value.
49071 return parseFloat(str.replace(/_/g, ""))
49072 }
49073
49074 function stringToBigInt(str) {
49075 if (typeof BigInt !== "function") {
49076 return null
49077 }
49078
49079 // `BigInt(value)` throws syntax error if the string contains numeric separators.
49080 return BigInt(str.replace(/_/g, ""))
49081 }
49082
49083 pp$9.readRadixNumber = function(radix) {
49084 var start = this.pos;
49085 this.pos += 2; // 0x
49086 var val = this.readInt(radix);
49087 if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
49088 if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
49089 val = stringToBigInt(this.input.slice(start, this.pos));
49090 ++this.pos;
49091 } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
49092 return this.finishToken(types.num, val)
49093 };
49094
49095 // Read an integer, octal integer, or floating-point number.
49096
49097 pp$9.readNumber = function(startsWithDot) {
49098 var start = this.pos;
49099 if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); }
49100 var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
49101 if (octal && this.strict) { this.raise(start, "Invalid number"); }
49102 var next = this.input.charCodeAt(this.pos);
49103 if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
49104 var val$1 = stringToBigInt(this.input.slice(start, this.pos));
49105 ++this.pos;
49106 if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
49107 return this.finishToken(types.num, val$1)
49108 }
49109 if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }
49110 if (next === 46 && !octal) { // '.'
49111 ++this.pos;
49112 this.readInt(10);
49113 next = this.input.charCodeAt(this.pos);
49114 }
49115 if ((next === 69 || next === 101) && !octal) { // 'eE'
49116 next = this.input.charCodeAt(++this.pos);
49117 if (next === 43 || next === 45) { ++this.pos; } // '+-'
49118 if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
49119 }
49120 if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
49121
49122 var val = stringToNumber(this.input.slice(start, this.pos), octal);
49123 return this.finishToken(types.num, val)
49124 };
49125
49126 // Read a string value, interpreting backslash-escapes.
49127
49128 pp$9.readCodePoint = function() {
49129 var ch = this.input.charCodeAt(this.pos), code;
49130
49131 if (ch === 123) { // '{'
49132 if (this.options.ecmaVersion < 6) { this.unexpected(); }
49133 var codePos = ++this.pos;
49134 code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
49135 ++this.pos;
49136 if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
49137 } else {
49138 code = this.readHexChar(4);
49139 }
49140 return code
49141 };
49142
49143 function codePointToString$1(code) {
49144 // UTF-16 Decoding
49145 if (code <= 0xFFFF) { return String.fromCharCode(code) }
49146 code -= 0x10000;
49147 return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
49148 }
49149
49150 pp$9.readString = function(quote) {
49151 var out = "", chunkStart = ++this.pos;
49152 for (;;) {
49153 if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }
49154 var ch = this.input.charCodeAt(this.pos);
49155 if (ch === quote) { break }
49156 if (ch === 92) { // '\'
49157 out += this.input.slice(chunkStart, this.pos);
49158 out += this.readEscapedChar(false);
49159 chunkStart = this.pos;
49160 } else {
49161 if (isNewLine(ch, this.options.ecmaVersion >= 10)) { this.raise(this.start, "Unterminated string constant"); }
49162 ++this.pos;
49163 }
49164 }
49165 out += this.input.slice(chunkStart, this.pos++);
49166 return this.finishToken(types.string, out)
49167 };
49168
49169 // Reads template string tokens.
49170
49171 var INVALID_TEMPLATE_ESCAPE_ERROR = {};
49172
49173 pp$9.tryReadTemplateToken = function() {
49174 this.inTemplateElement = true;
49175 try {
49176 this.readTmplToken();
49177 } catch (err) {
49178 if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
49179 this.readInvalidTemplateToken();
49180 } else {
49181 throw err
49182 }
49183 }
49184
49185 this.inTemplateElement = false;
49186 };
49187
49188 pp$9.invalidStringToken = function(position, message) {
49189 if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
49190 throw INVALID_TEMPLATE_ESCAPE_ERROR
49191 } else {
49192 this.raise(position, message);
49193 }
49194 };
49195
49196 pp$9.readTmplToken = function() {
49197 var out = "", chunkStart = this.pos;
49198 for (;;) {
49199 if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }
49200 var ch = this.input.charCodeAt(this.pos);
49201 if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'
49202 if (this.pos === this.start && (this.type === types.template || this.type === types.invalidTemplate)) {
49203 if (ch === 36) {
49204 this.pos += 2;
49205 return this.finishToken(types.dollarBraceL)
49206 } else {
49207 ++this.pos;
49208 return this.finishToken(types.backQuote)
49209 }
49210 }
49211 out += this.input.slice(chunkStart, this.pos);
49212 return this.finishToken(types.template, out)
49213 }
49214 if (ch === 92) { // '\'
49215 out += this.input.slice(chunkStart, this.pos);
49216 out += this.readEscapedChar(true);
49217 chunkStart = this.pos;
49218 } else if (isNewLine(ch)) {
49219 out += this.input.slice(chunkStart, this.pos);
49220 ++this.pos;
49221 switch (ch) {
49222 case 13:
49223 if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }
49224 case 10:
49225 out += "\n";
49226 break
49227 default:
49228 out += String.fromCharCode(ch);
49229 break
49230 }
49231 if (this.options.locations) {
49232 ++this.curLine;
49233 this.lineStart = this.pos;
49234 }
49235 chunkStart = this.pos;
49236 } else {
49237 ++this.pos;
49238 }
49239 }
49240 };
49241
49242 // Reads a template token to search for the end, without validating any escape sequences
49243 pp$9.readInvalidTemplateToken = function() {
49244 for (; this.pos < this.input.length; this.pos++) {
49245 switch (this.input[this.pos]) {
49246 case "\\":
49247 ++this.pos;
49248 break
49249
49250 case "$":
49251 if (this.input[this.pos + 1] !== "{") {
49252 break
49253 }
49254 // falls through
49255
49256 case "`":
49257 return this.finishToken(types.invalidTemplate, this.input.slice(this.start, this.pos))
49258
49259 // no default
49260 }
49261 }
49262 this.raise(this.start, "Unterminated template");
49263 };
49264
49265 // Used to read escaped characters
49266
49267 pp$9.readEscapedChar = function(inTemplate) {
49268 var ch = this.input.charCodeAt(++this.pos);
49269 ++this.pos;
49270 switch (ch) {
49271 case 110: return "\n" // 'n' -> '\n'
49272 case 114: return "\r" // 'r' -> '\r'
49273 case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
49274 case 117: return codePointToString$1(this.readCodePoint()) // 'u'
49275 case 116: return "\t" // 't' -> '\t'
49276 case 98: return "\b" // 'b' -> '\b'
49277 case 118: return "\u000b" // 'v' -> '\u000b'
49278 case 102: return "\f" // 'f' -> '\f'
49279 case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
49280 case 10: // ' \n'
49281 if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
49282 return ""
49283 case 56:
49284 case 57:
49285 if (this.strict) {
49286 this.invalidStringToken(
49287 this.pos - 1,
49288 "Invalid escape sequence"
49289 );
49290 }
49291 if (inTemplate) {
49292 var codePos = this.pos - 1;
49293
49294 this.invalidStringToken(
49295 codePos,
49296 "Invalid escape sequence in template string"
49297 );
49298
49299 return null
49300 }
49301 default:
49302 if (ch >= 48 && ch <= 55) {
49303 var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
49304 var octal = parseInt(octalStr, 8);
49305 if (octal > 255) {
49306 octalStr = octalStr.slice(0, -1);
49307 octal = parseInt(octalStr, 8);
49308 }
49309 this.pos += octalStr.length - 1;
49310 ch = this.input.charCodeAt(this.pos);
49311 if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
49312 this.invalidStringToken(
49313 this.pos - 1 - octalStr.length,
49314 inTemplate
49315 ? "Octal literal in template string"
49316 : "Octal literal in strict mode"
49317 );
49318 }
49319 return String.fromCharCode(octal)
49320 }
49321 if (isNewLine(ch)) {
49322 // Unicode new line characters after \ get removed from output in both
49323 // template literals and strings
49324 return ""
49325 }
49326 return String.fromCharCode(ch)
49327 }
49328 };
49329
49330 // Used to read character escape sequences ('\x', '\u', '\U').
49331
49332 pp$9.readHexChar = function(len) {
49333 var codePos = this.pos;
49334 var n = this.readInt(16, len);
49335 if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
49336 return n
49337 };
49338
49339 // Read an identifier, and return it as a string. Sets `this.containsEsc`
49340 // to whether the word contained a '\u' escape.
49341 //
49342 // Incrementally adds only escaped chars, adding other chunks as-is
49343 // as a micro-optimization.
49344
49345 pp$9.readWord1 = function() {
49346 this.containsEsc = false;
49347 var word = "", first = true, chunkStart = this.pos;
49348 var astral = this.options.ecmaVersion >= 6;
49349 while (this.pos < this.input.length) {
49350 var ch = this.fullCharCodeAtPos();
49351 if (isIdentifierChar(ch, astral)) {
49352 this.pos += ch <= 0xffff ? 1 : 2;
49353 } else if (ch === 92) { // "\"
49354 this.containsEsc = true;
49355 word += this.input.slice(chunkStart, this.pos);
49356 var escStart = this.pos;
49357 if (this.input.charCodeAt(++this.pos) !== 117) // "u"
49358 { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }
49359 ++this.pos;
49360 var esc = this.readCodePoint();
49361 if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
49362 { this.invalidStringToken(escStart, "Invalid Unicode escape"); }
49363 word += codePointToString$1(esc);
49364 chunkStart = this.pos;
49365 } else {
49366 break
49367 }
49368 first = false;
49369 }
49370 return word + this.input.slice(chunkStart, this.pos)
49371 };
49372
49373 // Read an identifier or keyword token. Will check for reserved
49374 // words when necessary.
49375
49376 pp$9.readWord = function() {
49377 var word = this.readWord1();
49378 var type = types.name;
49379 if (this.keywords.test(word)) {
49380 type = keywords$1[word];
49381 }
49382 return this.finishToken(type, word)
49383 };
49384
49385 // Acorn is a tiny, fast JavaScript parser written in JavaScript.
49386
49387 var version = "8.4.1";
49388
49389 Parser.acorn = {
49390 Parser: Parser,
49391 version: version,
49392 defaultOptions: defaultOptions,
49393 Position: Position,
49394 SourceLocation: SourceLocation,
49395 getLineInfo: getLineInfo,
49396 Node: Node,
49397 TokenType: TokenType,
49398 tokTypes: types,
49399 keywordTypes: keywords$1,
49400 TokContext: TokContext,
49401 tokContexts: types$1,
49402 isIdentifierChar: isIdentifierChar,
49403 isIdentifierStart: isIdentifierStart,
49404 Token: Token,
49405 isNewLine: isNewLine,
49406 lineBreak: lineBreak,
49407 lineBreakG: lineBreakG,
49408 nonASCIIwhitespace: nonASCIIwhitespace
49409 };
49410
49411 // The main exported interface (under `self.acorn` when in the
49412 // browser) is a `parse` function that takes a code string and
49413 // returns an abstract syntax tree as specified by [Mozilla parser
49414 // API][api].
49415 //
49416 // [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
49417
49418 function parse(input, options) {
49419 return Parser.parse(input, options)
49420 }
49421
49422 // This function tries to parse a single expression at a given
49423 // offset in a string. Useful for parsing mixed-language formats
49424 // that embed JavaScript expressions.
49425
49426 function parseExpressionAt(input, pos, options) {
49427 return Parser.parseExpressionAt(input, pos, options)
49428 }
49429
49430 // Acorn is organized as a tokenizer and a recursive-descent parser.
49431 // The `tokenizer` export provides an interface to the tokenizer.
49432
49433 function tokenizer(input, options) {
49434 return Parser.tokenizer(input, options)
49435 }
49436
49437 exports.Node = Node;
49438 exports.Parser = Parser;
49439 exports.Position = Position;
49440 exports.SourceLocation = SourceLocation;
49441 exports.TokContext = TokContext;
49442 exports.Token = Token;
49443 exports.TokenType = TokenType;
49444 exports.defaultOptions = defaultOptions;
49445 exports.getLineInfo = getLineInfo;
49446 exports.isIdentifierChar = isIdentifierChar;
49447 exports.isIdentifierStart = isIdentifierStart;
49448 exports.isNewLine = isNewLine;
49449 exports.keywordTypes = keywords$1;
49450 exports.lineBreak = lineBreak;
49451 exports.lineBreakG = lineBreakG;
49452 exports.nonASCIIwhitespace = nonASCIIwhitespace;
49453 exports.parse = parse;
49454 exports.parseExpressionAt = parseExpressionAt;
49455 exports.tokContexts = types$1;
49456 exports.tokTypes = types;
49457 exports.tokenizer = tokenizer;
49458 exports.version = version;
49459
49460 Object.defineProperty(exports, '__esModule', { value: true });
49461
49462})));
49463}(acorn, acorn.exports));
49464
49465const getPrototype = Object.getPrototypeOf || (o => o.__proto__);
49466
49467const getAcorn = Parser => {
49468 if (Parser.acorn) return Parser.acorn
49469
49470 const acorn$1 = acorn.exports;
49471
49472 if (acorn$1.version.indexOf("6.") != 0 && acorn$1.version.indexOf("6.0.") == 0 && acorn$1.version.indexOf("7.") != 0) {
49473 throw new Error(`acorn-private-class-elements requires acorn@^6.1.0 or acorn@7.0.0, not ${acorn$1.version}`)
49474 }
49475
49476 // Make sure `Parser` comes from the same acorn as we `require`d,
49477 // otherwise the comparisons fail.
49478 for (let cur = Parser; cur && cur !== acorn$1.Parser; cur = getPrototype(cur)) {
49479 if (cur !== acorn$1.Parser) {
49480 throw new Error("acorn-private-class-elements does not support mixing different acorn copies")
49481 }
49482 }
49483 return acorn$1
49484};
49485
49486var acornPrivateClassElements = function(Parser) {
49487 // Only load this plugin once.
49488 if (Parser.prototype.parsePrivateName) {
49489 return Parser
49490 }
49491
49492 const acorn = getAcorn(Parser);
49493
49494 Parser = class extends Parser {
49495 _branch() {
49496 this.__branch = this.__branch || new Parser({ecmaVersion: this.options.ecmaVersion}, this.input);
49497 this.__branch.end = this.end;
49498 this.__branch.pos = this.pos;
49499 this.__branch.type = this.type;
49500 this.__branch.value = this.value;
49501 this.__branch.containsEsc = this.containsEsc;
49502 return this.__branch
49503 }
49504
49505 parsePrivateClassElementName(element) {
49506 element.computed = false;
49507 element.key = this.parsePrivateName();
49508 if (element.key.name == "constructor") this.raise(element.key.start, "Classes may not have a private element named constructor");
49509 const accept = {get: "set", set: "get"}[element.kind];
49510 const privateBoundNames = this._privateBoundNames;
49511 if (Object.prototype.hasOwnProperty.call(privateBoundNames, element.key.name) && privateBoundNames[element.key.name] !== accept) {
49512 this.raise(element.start, "Duplicate private element");
49513 }
49514 privateBoundNames[element.key.name] = element.kind || true;
49515 delete this._unresolvedPrivateNames[element.key.name];
49516 return element.key
49517 }
49518
49519 parsePrivateName() {
49520 const node = this.startNode();
49521 node.name = this.value;
49522 this.next();
49523 this.finishNode(node, "PrivateIdentifier");
49524 if (this.options.allowReserved == "never") this.checkUnreserved(node);
49525 return node
49526 }
49527
49528 // Parse # token
49529 getTokenFromCode(code) {
49530 if (code === 35) {
49531 ++this.pos;
49532 const word = this.readWord1();
49533 return this.finishToken(this.privateIdentifierToken, word)
49534 }
49535 return super.getTokenFromCode(code)
49536 }
49537
49538 // Manage stacks and check for undeclared private names
49539 parseClass(node, isStatement) {
49540 const oldOuterPrivateBoundNames = this._outerPrivateBoundNames;
49541 this._outerPrivateBoundNames = this._privateBoundNames;
49542 this._privateBoundNames = Object.create(this._privateBoundNames || null);
49543 const oldOuterUnresolvedPrivateNames = this._outerUnresolvedPrivateNames;
49544 this._outerUnresolvedPrivateNames = this._unresolvedPrivateNames;
49545 this._unresolvedPrivateNames = Object.create(null);
49546
49547 const _return = super.parseClass(node, isStatement);
49548
49549 const unresolvedPrivateNames = this._unresolvedPrivateNames;
49550 this._privateBoundNames = this._outerPrivateBoundNames;
49551 this._outerPrivateBoundNames = oldOuterPrivateBoundNames;
49552 this._unresolvedPrivateNames = this._outerUnresolvedPrivateNames;
49553 this._outerUnresolvedPrivateNames = oldOuterUnresolvedPrivateNames;
49554 if (!this._unresolvedPrivateNames) {
49555 const names = Object.keys(unresolvedPrivateNames);
49556 if (names.length) {
49557 names.sort((n1, n2) => unresolvedPrivateNames[n1] - unresolvedPrivateNames[n2]);
49558 this.raise(unresolvedPrivateNames[names[0]], "Usage of undeclared private name");
49559 }
49560 } else Object.assign(this._unresolvedPrivateNames, unresolvedPrivateNames);
49561 return _return
49562 }
49563
49564 // Class heritage is evaluated with outer private environment
49565 parseClassSuper(node) {
49566 const privateBoundNames = this._privateBoundNames;
49567 this._privateBoundNames = this._outerPrivateBoundNames;
49568 const unresolvedPrivateNames = this._unresolvedPrivateNames;
49569 this._unresolvedPrivateNames = this._outerUnresolvedPrivateNames;
49570 const _return = super.parseClassSuper(node);
49571 this._privateBoundNames = privateBoundNames;
49572 this._unresolvedPrivateNames = unresolvedPrivateNames;
49573 return _return
49574 }
49575
49576 // Parse private element access
49577 parseSubscript(base, startPos, startLoc, _noCalls, _maybeAsyncArrow, _optionalChained) {
49578 const optionalSupported = this.options.ecmaVersion >= 11 && acorn.tokTypes.questionDot;
49579 const branch = this._branch();
49580 if (!(
49581 (branch.eat(acorn.tokTypes.dot) || (optionalSupported && branch.eat(acorn.tokTypes.questionDot))) &&
49582 branch.type == this.privateIdentifierToken
49583 )) {
49584 return super.parseSubscript.apply(this, arguments)
49585 }
49586 let optional = false;
49587 if (!this.eat(acorn.tokTypes.dot)) {
49588 this.expect(acorn.tokTypes.questionDot);
49589 optional = true;
49590 }
49591 let node = this.startNodeAt(startPos, startLoc);
49592 node.object = base;
49593 node.computed = false;
49594 if (optionalSupported) {
49595 node.optional = optional;
49596 }
49597 if (this.type == this.privateIdentifierToken) {
49598 if (base.type == "Super") {
49599 this.raise(this.start, "Cannot access private element on super");
49600 }
49601 node.property = this.parsePrivateName();
49602 if (!this._privateBoundNames || !this._privateBoundNames[node.property.name]) {
49603 if (!this._unresolvedPrivateNames) {
49604 this.raise(node.property.start, "Usage of undeclared private name");
49605 }
49606 this._unresolvedPrivateNames[node.property.name] = node.property.start;
49607 }
49608 } else {
49609 node.property = this.parseIdent(true);
49610 }
49611 return this.finishNode(node, "MemberExpression")
49612 }
49613
49614 // Prohibit delete of private class elements
49615 parseMaybeUnary(refDestructuringErrors, sawUnary) {
49616 const _return = super.parseMaybeUnary(refDestructuringErrors, sawUnary);
49617 if (_return.operator == "delete") {
49618 if (_return.argument.type == "MemberExpression" && _return.argument.property.type == "PrivateIdentifier") {
49619 this.raise(_return.start, "Private elements may not be deleted");
49620 }
49621 }
49622 return _return
49623 }
49624 };
49625 Parser.prototype.privateIdentifierToken = new acorn.TokenType("privateIdentifier");
49626 return Parser
49627};
49628
49629const privateClassElements$1 = acornPrivateClassElements;
49630
49631var acornClassFields = function(Parser) {
49632 const acorn$1 = Parser.acorn || acorn.exports;
49633 const tt = acorn$1.tokTypes;
49634
49635 Parser = privateClassElements$1(Parser);
49636 return class extends Parser {
49637 _maybeParseFieldValue(field) {
49638 if (this.eat(tt.eq)) {
49639 const oldInFieldValue = this._inFieldValue;
49640 this._inFieldValue = true;
49641 if (this.type === tt.name && this.value === "await" && (this.inAsync || this.options.allowAwaitOutsideFunction)) {
49642 field.value = this.parseAwait();
49643 } else field.value = this.parseExpression();
49644 this._inFieldValue = oldInFieldValue;
49645 } else field.value = null;
49646 }
49647
49648 // Parse fields
49649 parseClassElement(_constructorAllowsSuper) {
49650 if (this.options.ecmaVersion >= 8 && (this.type == tt.name || this.type.keyword || this.type == this.privateIdentifierToken || this.type == tt.bracketL || this.type == tt.string || this.type == tt.num)) {
49651 const branch = this._branch();
49652 if (branch.type == tt.bracketL) {
49653 let count = 0;
49654 do {
49655 if (branch.eat(tt.bracketL)) ++count;
49656 else if (branch.eat(tt.bracketR)) --count;
49657 else branch.next();
49658 } while (count > 0)
49659 } else branch.next(true);
49660 let isField = branch.type == tt.eq || branch.type == tt.semi;
49661 if (!isField && branch.canInsertSemicolon()) {
49662 isField = branch.type != tt.parenL;
49663 }
49664 if (isField) {
49665 const node = this.startNode();
49666 if (this.type == this.privateIdentifierToken) {
49667 this.parsePrivateClassElementName(node);
49668 } else {
49669 this.parsePropertyName(node);
49670 }
49671 if ((node.key.type === "Identifier" && node.key.name === "constructor") ||
49672 (node.key.type === "Literal" && node.key.value === "constructor")) {
49673 this.raise(node.key.start, "Classes may not have a field called constructor");
49674 }
49675 this.enterScope(64 | 2 | 1); // See acorn's scopeflags.js
49676 this._maybeParseFieldValue(node);
49677 this.exitScope();
49678 this.finishNode(node, "PropertyDefinition");
49679 this.semicolon();
49680 return node
49681 }
49682 }
49683
49684 return super.parseClassElement.apply(this, arguments)
49685 }
49686
49687 // Prohibit arguments in class field initializers
49688 parseIdent(liberal, isBinding) {
49689 const ident = super.parseIdent(liberal, isBinding);
49690 if (this._inFieldValue && ident.name == "arguments") this.raise(ident.start, "A class field initializer may not contain arguments");
49691 return ident
49692 }
49693 }
49694};
49695
49696function withoutAcornBigInt(acorn, Parser) {
49697 return class extends Parser {
49698 readInt(radix, len) {
49699 // Hack: len is only != null for unicode escape sequences,
49700 // where numeric separators are not allowed
49701 if (len != null) return super.readInt(radix, len)
49702
49703 let start = this.pos, total = 0, acceptUnderscore = false;
49704 for (;;) {
49705 let code = this.input.charCodeAt(this.pos), val;
49706 if (code >= 97) val = code - 97 + 10; // a
49707 else if (code == 95) {
49708 if (!acceptUnderscore) this.raise(this.pos, "Invalid numeric separator");
49709 ++this.pos;
49710 acceptUnderscore = false;
49711 continue
49712 } else if (code >= 65) val = code - 65 + 10; // A
49713 else if (code >= 48 && code <= 57) val = code - 48; // 0-9
49714 else val = Infinity;
49715 if (val >= radix) break
49716 ++this.pos;
49717 total = total * radix + val;
49718 acceptUnderscore = true;
49719 }
49720 if (this.pos === start) return null
49721 if (!acceptUnderscore) this.raise(this.pos - 1, "Invalid numeric separator");
49722
49723 return total
49724 }
49725
49726 readNumber(startsWithDot) {
49727 const token = super.readNumber(startsWithDot);
49728 let octal = this.end - this.start >= 2 && this.input.charCodeAt(this.start) === 48;
49729 const stripped = this.getNumberInput(this.start, this.end);
49730 if (stripped.length < this.end - this.start) {
49731 if (octal) this.raise(this.start, "Invalid number");
49732 this.value = parseFloat(stripped);
49733 }
49734 return token
49735 }
49736
49737 // This is used by acorn-bigint
49738 getNumberInput(start, end) {
49739 return this.input.slice(start, end).replace(/_/g, "")
49740 }
49741 }
49742}
49743
49744function withAcornBigInt(acorn, Parser) {
49745 return class extends Parser {
49746 readInt(radix, len) {
49747 // Hack: len is only != null for unicode escape sequences,
49748 // where numeric separators are not allowed
49749 if (len != null) return super.readInt(radix, len)
49750
49751 let start = this.pos, total = 0, acceptUnderscore = false;
49752 for (;;) {
49753 let code = this.input.charCodeAt(this.pos), val;
49754 if (code >= 97) val = code - 97 + 10; // a
49755 else if (code == 95) {
49756 if (!acceptUnderscore) this.raise(this.pos, "Invalid numeric separator");
49757 ++this.pos;
49758 acceptUnderscore = false;
49759 continue
49760 } else if (code >= 65) val = code - 65 + 10; // A
49761 else if (code >= 48 && code <= 57) val = code - 48; // 0-9
49762 else val = Infinity;
49763 if (val >= radix) break
49764 ++this.pos;
49765 total = total * radix + val;
49766 acceptUnderscore = true;
49767 }
49768 if (this.pos === start) return null
49769 if (!acceptUnderscore) this.raise(this.pos - 1, "Invalid numeric separator");
49770
49771 return total
49772 }
49773
49774 readNumber(startsWithDot) {
49775 let start = this.pos;
49776 if (!startsWithDot && this.readInt(10) === null) this.raise(start, "Invalid number");
49777 let octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
49778 let octalLike = false;
49779 if (octal && this.strict) this.raise(start, "Invalid number");
49780 let next = this.input.charCodeAt(this.pos);
49781 if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
49782 let str = this.getNumberInput(start, this.pos);
49783 // eslint-disable-next-line node/no-unsupported-features/es-builtins
49784 let val = typeof BigInt !== "undefined" ? BigInt(str) : null;
49785 ++this.pos;
49786 if (acorn.isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number");
49787 return this.finishToken(acorn.tokTypes.num, val)
49788 }
49789 if (octal && /[89]/.test(this.input.slice(start, this.pos))) {
49790 octal = false;
49791 octalLike = true;
49792 }
49793 if (next === 46 && !octal) { // '.'
49794 ++this.pos;
49795 this.readInt(10);
49796 next = this.input.charCodeAt(this.pos);
49797 }
49798 if ((next === 69 || next === 101) && !octal) { // 'eE'
49799 next = this.input.charCodeAt(++this.pos);
49800 if (next === 43 || next === 45) ++this.pos; // '+-'
49801 if (this.readInt(10) === null) this.raise(start, "Invalid number");
49802 }
49803 if (acorn.isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number");
49804 let str = this.getNumberInput(start, this.pos);
49805 if ((octal || octalLike) && str.length < this.pos - start) {
49806 this.raise(start, "Invalid number");
49807 }
49808
49809 let val = octal ? parseInt(str, 8) : parseFloat(str);
49810 return this.finishToken(acorn.tokTypes.num, val)
49811 }
49812
49813 parseLiteral(value) {
49814 const ret = super.parseLiteral(value);
49815 if (ret.bigint) ret.bigint = ret.bigint.replace(/_/g, "");
49816 return ret
49817 }
49818
49819 readRadixNumber(radix) {
49820 let start = this.pos;
49821 this.pos += 2; // 0x
49822 let val = this.readInt(radix);
49823 if (val == null) { this.raise(this.start + 2, `Expected number in radix ${radix}`); }
49824 if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
49825 let str = this.getNumberInput(start, this.pos);
49826 // eslint-disable-next-line node/no-unsupported-features/es-builtins
49827 val = typeof BigInt !== "undefined" ? BigInt(str) : null;
49828 ++this.pos;
49829 } else if (acorn.isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
49830 return this.finishToken(acorn.tokTypes.num, val)
49831 }
49832
49833 // This is used by acorn-bigint, which theoretically could be used with acorn@6.2 || acorn@7
49834 getNumberInput(start, end) {
49835 return this.input.slice(start, end).replace(/_/g, "")
49836 }
49837 }
49838}
49839
49840// eslint-disable-next-line node/no-unsupported-features/es-syntax
49841function numericSeparator(Parser) {
49842 const acorn = Parser.acorn || require("acorn");
49843 const withAcornBigIntSupport = (acorn.version.startsWith("6.") && !(acorn.version.startsWith("6.0.") || acorn.version.startsWith("6.1."))) || acorn.version.startsWith("7.");
49844
49845 return withAcornBigIntSupport ? withAcornBigInt(acorn, Parser) : withoutAcornBigInt(acorn, Parser)
49846}
49847
49848const privateClassElements = acornPrivateClassElements;
49849
49850var acornStaticClassFeatures = function(Parser) {
49851 const ExtendedParser = privateClassElements(Parser);
49852
49853 const acorn$1 = Parser.acorn || acorn.exports;
49854 const tt = acorn$1.tokTypes;
49855
49856 return class extends ExtendedParser {
49857 _maybeParseFieldValue(field) {
49858 if (this.eat(tt.eq)) {
49859 const oldInFieldValue = this._inStaticFieldScope;
49860 this._inStaticFieldScope = this.currentThisScope();
49861 field.value = this.parseExpression();
49862 this._inStaticFieldScope = oldInFieldValue;
49863 } else field.value = null;
49864 }
49865
49866 // Parse fields
49867 parseClassElement(_constructorAllowsSuper) {
49868 if (this.options.ecmaVersion < 8 || !this.isContextual("static")) {
49869 return super.parseClassElement.apply(this, arguments)
49870 }
49871
49872 const branch = this._branch();
49873 branch.next();
49874 if ([tt.name, tt.bracketL, tt.string, tt.num, this.privateIdentifierToken].indexOf(branch.type) == -1 && !branch.type.keyword) {
49875 return super.parseClassElement.apply(this, arguments)
49876 }
49877 if (branch.type == tt.bracketL) {
49878 let count = 0;
49879 do {
49880 if (branch.eat(tt.bracketL)) ++count;
49881 else if (branch.eat(tt.bracketR)) --count;
49882 else branch.next();
49883 } while (count > 0)
49884 } else branch.next();
49885 if (branch.type != tt.eq && !branch.canInsertSemicolon() && branch.type != tt.semi) {
49886 return super.parseClassElement.apply(this, arguments)
49887 }
49888
49889 const node = this.startNode();
49890 node.static = this.eatContextual("static");
49891 if (this.type == this.privateIdentifierToken) {
49892 this.parsePrivateClassElementName(node);
49893 } else {
49894 this.parsePropertyName(node);
49895 }
49896 if ((node.key.type === "Identifier" && node.key.name === "constructor") ||
49897 (node.key.type === "Literal" && !node.computed && node.key.value === "constructor")) {
49898 this.raise(node.key.start, "Classes may not have a field called constructor");
49899 }
49900 if ((node.key.name || node.key.value) === "prototype" && !node.computed) {
49901 this.raise(node.key.start, "Classes may not have a static property named prototype");
49902 }
49903
49904 this.enterScope(64 | 2 | 1); // See acorn's scopeflags.js
49905 this._maybeParseFieldValue(node);
49906 this.exitScope();
49907 this.finishNode(node, "PropertyDefinition");
49908 this.semicolon();
49909 return node
49910 }
49911
49912 // Parse private static methods
49913 parsePropertyName(prop) {
49914 if (prop.static && this.type == this.privateIdentifierToken) {
49915 this.parsePrivateClassElementName(prop);
49916 } else {
49917 super.parsePropertyName(prop);
49918 }
49919 }
49920
49921 // Prohibit arguments in class field initializers
49922 parseIdent(liberal, isBinding) {
49923 const ident = super.parseIdent(liberal, isBinding);
49924 if (this._inStaticFieldScope && this.currentThisScope() === this._inStaticFieldScope && ident.name == "arguments") {
49925 this.raise(ident.start, "A static class field initializer may not contain arguments");
49926 }
49927 return ident
49928 }
49929 }
49930};
49931
49932var ansiRegex$1 = ({onlyFirst = false} = {}) => {
49933 const pattern = [
49934 '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)',
49935 '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'
49936 ].join('|');
49937
49938 return new RegExp(pattern, onlyFirst ? undefined : 'g');
49939};
49940
49941const ansiRegex = ansiRegex$1;
49942
49943var stripAnsi = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string;
49944
49945function prepareError(err) {
49946 // only copy the information we need and avoid serializing unnecessary
49947 // properties, since some errors may attach full objects (e.g. PostCSS)
49948 return {
49949 message: stripAnsi(err.message),
49950 stack: stripAnsi(cleanStack(err.stack || '')),
49951 id: err.id,
49952 frame: stripAnsi(err.frame || ''),
49953 plugin: err.plugin,
49954 pluginCode: err.pluginCode,
49955 loc: err.loc
49956 };
49957}
49958function buildErrorMessage(err, args = [], includeStack = true) {
49959 if (err.plugin)
49960 args.push(` Plugin: ${source.magenta(err.plugin)}`);
49961 if (err.id)
49962 args.push(` File: ${source.cyan(err.id)}`);
49963 if (err.frame)
49964 args.push(source.yellow(pad$1(err.frame)));
49965 if (includeStack && err.stack)
49966 args.push(pad$1(cleanStack(err.stack)));
49967 return args.join('\n');
49968}
49969function cleanStack(stack) {
49970 return stack
49971 .split(/\n/g)
49972 .filter((l) => /^\s*at/.test(l))
49973 .join('\n');
49974}
49975function errorMiddleware(server, allowNext = false) {
49976 // note the 4 args must be kept for connect to treat this as error middleware
49977 // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
49978 return function viteErrorMiddleware(err, _req, res, next) {
49979 const msg = buildErrorMessage(err, [
49980 source.red(`Internal server error: ${err.message}`)
49981 ]);
49982 server.config.logger.error(msg, {
49983 clear: true,
49984 timestamp: true
49985 });
49986 server.ws.send({
49987 type: 'error',
49988 err: prepareError(err)
49989 });
49990 if (allowNext) {
49991 next();
49992 }
49993 else {
49994 if (err instanceof AccessRestrictedError) {
49995 res.statusCode = 403;
49996 res.write(renderErrorHTML(err.message));
49997 res.end();
49998 }
49999 res.statusCode = 500;
50000 res.end();
50001 }
50002 };
50003}
50004class AccessRestrictedError extends Error {
50005 constructor(msg) {
50006 super(msg);
50007 }
50008}
50009function renderErrorHTML(msg) {
50010 // to have syntax highlighting and autocompletion in IDE
50011 const html = String.raw;
50012 return html `
50013 <body>
50014 <h1>403 Restricted</h1>
50015 <p>${msg.replace(/\n/g, '<br/>')}</p>
50016 <style>
50017 body {
50018 padding: 1em 2em;
50019 }
50020 </style>
50021 </body>
50022 `;
50023}
50024
50025/**
50026 * This file is refactored into TypeScript based on
50027 * https://github.com/preactjs/wmr/blob/main/packages/wmr/src/lib/rollup-plugin-container.js
50028 */
50029let parser = Parser.extend(acornClassFields, acornStaticClassFeatures, numericSeparator);
50030async function createPluginContainer({ plugins, logger, root, build: { rollupOptions } }, watcher) {
50031 const isDebug = process.env.DEBUG;
50032 const seenResolves = {};
50033 const debugResolve = createDebugger('vite:resolve');
50034 const debugPluginResolve = createDebugger('vite:plugin-resolve', {
50035 onlyWhenFocused: 'vite:plugin'
50036 });
50037 const debugPluginTransform = createDebugger('vite:plugin-transform', {
50038 onlyWhenFocused: 'vite:plugin'
50039 });
50040 // ---------------------------------------------------------------------------
50041 const MODULES = new Map();
50042 const watchFiles = new Set();
50043 // get rollup version
50044 const rollupPkgPath = path$A.resolve(require.resolve('rollup'), '../../package.json');
50045 const minimalContext = {
50046 meta: {
50047 rollupVersion: JSON.parse(fs__default.readFileSync(rollupPkgPath, 'utf-8'))
50048 .version,
50049 watchMode: true
50050 }
50051 };
50052 function warnIncompatibleMethod(method, plugin) {
50053 logger.warn(source.cyan(`[plugin:${plugin}] `) +
50054 source.yellow(`context method ${source.bold(`${method}()`)} is not supported in serve mode. This plugin is likely not vite-compatible.`));
50055 }
50056 // we should create a new context for each async hook pipeline so that the
50057 // active plugin in that pipeline can be tracked in a concurrency-safe manner.
50058 // using a class to make creating new contexts more efficient
50059 class Context {
50060 constructor(initialPlugin) {
50061 this.meta = minimalContext.meta;
50062 this.ssr = false;
50063 this._activeId = null;
50064 this._activeCode = null;
50065 this._activePlugin = initialPlugin || null;
50066 }
50067 parse(code, opts = {}) {
50068 return parser.parse(code, {
50069 sourceType: 'module',
50070 ecmaVersion: 2020,
50071 locations: true,
50072 ...opts
50073 });
50074 }
50075 async resolve(id, importer, options) {
50076 let skips;
50077 if ((options === null || options === void 0 ? void 0 : options.skipSelf) && this._activePlugin) {
50078 skips = new Set(this._resolveSkips);
50079 skips.add(this._activePlugin);
50080 }
50081 let out = await container.resolveId(id, importer, skips, this.ssr);
50082 if (typeof out === 'string')
50083 out = { id: out };
50084 return out;
50085 }
50086 getModuleInfo(id) {
50087 let mod = MODULES.get(id);
50088 if (mod)
50089 return mod.info;
50090 mod = {
50091 /** @type {import('rollup').ModuleInfo} */
50092 // @ts-ignore-next
50093 info: {}
50094 };
50095 MODULES.set(id, mod);
50096 return mod.info;
50097 }
50098 getModuleIds() {
50099 return MODULES.keys();
50100 }
50101 addWatchFile(id) {
50102 watchFiles.add(id);
50103 if (watcher)
50104 ensureWatchedFile(watcher, id, root);
50105 }
50106 getWatchFiles() {
50107 return [...watchFiles];
50108 }
50109 emitFile(assetOrFile) {
50110 warnIncompatibleMethod(`emitFile`, this._activePlugin.name);
50111 return '';
50112 }
50113 setAssetSource() {
50114 warnIncompatibleMethod(`setAssetSource`, this._activePlugin.name);
50115 }
50116 getFileName() {
50117 warnIncompatibleMethod(`getFileName`, this._activePlugin.name);
50118 return '';
50119 }
50120 warn(e, position) {
50121 const err = formatError(e, position, this);
50122 const msg = buildErrorMessage(err, [source.yellow(`warning: ${err.message}`)], false);
50123 logger.warn(msg, {
50124 clear: true,
50125 timestamp: true
50126 });
50127 }
50128 error(e, position) {
50129 // error thrown here is caught by the transform middleware and passed on
50130 // the the error middleware.
50131 throw formatError(e, position, this);
50132 }
50133 }
50134 function formatError(e, position, ctx) {
50135 const err = (typeof e === 'string' ? new Error(e) : e);
50136 if (ctx._activePlugin)
50137 err.plugin = ctx._activePlugin.name;
50138 if (ctx._activeId && !err.id)
50139 err.id = ctx._activeId;
50140 if (ctx._activeCode) {
50141 err.pluginCode = ctx._activeCode;
50142 const pos = position != null
50143 ? position
50144 : err.pos != null
50145 ? err.pos
50146 : // some rollup plugins, e.g. json, sets position instead of pos
50147 err.position;
50148 if (pos != null) {
50149 err.loc = err.loc || {
50150 file: err.id,
50151 ...numberToPos(ctx._activeCode, pos)
50152 };
50153 err.frame = err.frame || generateCodeFrame(ctx._activeCode, pos);
50154 }
50155 else if (err.loc) {
50156 // css preprocessors may report errors in an included file
50157 if (!err.frame) {
50158 let code = ctx._activeCode;
50159 if (err.loc.file) {
50160 err.id = normalizePath$4(err.loc.file);
50161 try {
50162 code = fs__default.readFileSync(err.loc.file, 'utf-8');
50163 }
50164 catch { }
50165 }
50166 err.frame = generateCodeFrame(code, err.loc);
50167 }
50168 }
50169 else if (err.line && err.column) {
50170 err.loc = {
50171 file: err.id,
50172 line: err.line,
50173 column: err.column
50174 };
50175 err.frame = err.frame || generateCodeFrame(ctx._activeCode, err.loc);
50176 }
50177 }
50178 return err;
50179 }
50180 class TransformContext extends Context {
50181 constructor(filename, code, inMap) {
50182 super();
50183 this.originalSourcemap = null;
50184 this.sourcemapChain = [];
50185 this.combinedMap = null;
50186 this.filename = filename;
50187 this.originalCode = code;
50188 if (inMap) {
50189 this.sourcemapChain.push(inMap);
50190 }
50191 }
50192 _getCombinedSourcemap(createIfNull = false) {
50193 let combinedMap = this.combinedMap;
50194 for (let m of this.sourcemapChain) {
50195 if (typeof m === 'string')
50196 m = JSON.parse(m);
50197 if (!('version' in m)) {
50198 // empty, nullified source map
50199 combinedMap = this.combinedMap = null;
50200 this.sourcemapChain.length = 0;
50201 break;
50202 }
50203 if (!combinedMap) {
50204 combinedMap = m;
50205 }
50206 else {
50207 combinedMap = combineSourcemaps(this.filename, [
50208 {
50209 ...m,
50210 sourcesContent: combinedMap.sourcesContent
50211 },
50212 combinedMap
50213 ]);
50214 }
50215 }
50216 if (!combinedMap) {
50217 return createIfNull
50218 ? new MagicString(this.originalCode).generateMap({
50219 includeContent: true,
50220 hires: true,
50221 source: this.filename
50222 })
50223 : null;
50224 }
50225 if (combinedMap !== this.combinedMap) {
50226 this.combinedMap = combinedMap;
50227 this.sourcemapChain.length = 0;
50228 }
50229 return this.combinedMap;
50230 }
50231 getCombinedSourcemap() {
50232 return this._getCombinedSourcemap(true);
50233 }
50234 }
50235 let closed = false;
50236 const container = {
50237 options: await (async () => {
50238 let options = rollupOptions;
50239 for (const plugin of plugins) {
50240 if (!plugin.options)
50241 continue;
50242 options =
50243 (await plugin.options.call(minimalContext, options)) || options;
50244 }
50245 if (options.acornInjectPlugins) {
50246 parser = Parser.extend(...[
50247 acornClassFields,
50248 acornStaticClassFeatures,
50249 numericSeparator
50250 ].concat(options.acornInjectPlugins));
50251 }
50252 return {
50253 acorn: acorn$1,
50254 acornInjectPlugins: [],
50255 ...options
50256 };
50257 })(),
50258 async buildStart() {
50259 await Promise.all(plugins.map((plugin) => {
50260 if (plugin.buildStart) {
50261 return plugin.buildStart.call(new Context(plugin), container.options);
50262 }
50263 }));
50264 },
50265 async resolveId(rawId, importer = path$A.join(root, 'index.html'), skips, ssr) {
50266 const ctx = new Context();
50267 ctx.ssr = !!ssr;
50268 ctx._resolveSkips = skips;
50269 const resolveStart = isDebug ? Date.now() : 0;
50270 let id = null;
50271 const partial = {};
50272 for (const plugin of plugins) {
50273 if (!plugin.resolveId)
50274 continue;
50275 if (skips === null || skips === void 0 ? void 0 : skips.has(plugin))
50276 continue;
50277 ctx._activePlugin = plugin;
50278 const pluginResolveStart = isDebug ? Date.now() : 0;
50279 const result = await plugin.resolveId.call(ctx, rawId, importer, {}, ssr);
50280 if (!result)
50281 continue;
50282 if (typeof result === 'string') {
50283 id = result;
50284 }
50285 else {
50286 id = result.id;
50287 Object.assign(partial, result);
50288 }
50289 isDebug &&
50290 debugPluginResolve(timeFrom(pluginResolveStart), plugin.name, prettifyUrl(id, root));
50291 // resolveId() is hookFirst - first non-null result is returned.
50292 break;
50293 }
50294 if (isDebug && rawId !== id && !rawId.startsWith(FS_PREFIX)) {
50295 const key = rawId + id;
50296 // avoid spamming
50297 if (!seenResolves[key]) {
50298 seenResolves[key] = true;
50299 debugResolve(`${timeFrom(resolveStart)} ${source.cyan(rawId)} -> ${source.dim(id)}`);
50300 }
50301 }
50302 if (id) {
50303 partial.id = isExternalUrl(id) ? id : normalizePath$4(id);
50304 return partial;
50305 }
50306 else {
50307 return null;
50308 }
50309 },
50310 async load(id, ssr) {
50311 const ctx = new Context();
50312 ctx.ssr = !!ssr;
50313 for (const plugin of plugins) {
50314 if (!plugin.load)
50315 continue;
50316 ctx._activePlugin = plugin;
50317 const result = await plugin.load.call(ctx, id, ssr);
50318 if (result != null) {
50319 return result;
50320 }
50321 }
50322 return null;
50323 },
50324 async transform(code, id, inMap, ssr) {
50325 const ctx = new TransformContext(id, code, inMap);
50326 ctx.ssr = !!ssr;
50327 for (const plugin of plugins) {
50328 if (!plugin.transform)
50329 continue;
50330 ctx._activePlugin = plugin;
50331 ctx._activeId = id;
50332 ctx._activeCode = code;
50333 const start = isDebug ? Date.now() : 0;
50334 let result;
50335 try {
50336 result = await plugin.transform.call(ctx, code, id, ssr);
50337 }
50338 catch (e) {
50339 ctx.error(e);
50340 }
50341 if (!result)
50342 continue;
50343 isDebug &&
50344 debugPluginTransform(timeFrom(start), plugin.name, prettifyUrl(id, root));
50345 if (typeof result === 'object') {
50346 code = result.code || '';
50347 if (result.map)
50348 ctx.sourcemapChain.push(result.map);
50349 }
50350 else {
50351 code = result;
50352 }
50353 }
50354 return {
50355 code,
50356 map: ctx._getCombinedSourcemap()
50357 };
50358 },
50359 watchChange(id, event = 'update') {
50360 const ctx = new Context();
50361 if (watchFiles.has(id)) {
50362 for (const plugin of plugins) {
50363 if (!plugin.watchChange)
50364 continue;
50365 ctx._activePlugin = plugin;
50366 plugin.watchChange.call(ctx, id, { event });
50367 }
50368 }
50369 },
50370 async close() {
50371 if (closed)
50372 return;
50373 const ctx = new Context();
50374 await Promise.all(plugins.map((p) => p.buildEnd && p.buildEnd.call(ctx)));
50375 await Promise.all(plugins.map((p) => p.closeBundle && p.closeBundle.call(ctx)));
50376 closed = true;
50377 }
50378 };
50379 return container;
50380}
50381
50382const debug$9 = createDebugger('vite:deps');
50383const htmlTypesRE = /\.(html|vue|svelte)$/;
50384// A simple regex to detect import sources. This is only used on
50385// <script lang="ts"> blocks in vue (setup only) or svelte files, since
50386// seemingly unused imports are dropped by esbuild when transpiling TS which
50387// prevents it from crawling further.
50388// We can't use es-module-lexer because it can't handle TS, and don't want to
50389// use Acorn because it's slow. Luckily this doesn't have to be bullet proof
50390// since even missed imports can be caught at runtime, and false positives will
50391// simply be ignored.
50392const importsRE = /(?:^|;|\*\/)\s*import(?!\s+type)(?:[\w*{}\n\r\t, ]+from\s*)?\s*("[^"]+"|'[^']+')\s*(?:$|;|\/\/|\/\*)/gm;
50393async function scanImports(config) {
50394 var _a, _b, _c, _d;
50395 const s = Date.now();
50396 let entries = [];
50397 const explicitEntryPatterns = (_a = config.optimizeDeps) === null || _a === void 0 ? void 0 : _a.entries;
50398 const buildInput = (_b = config.build.rollupOptions) === null || _b === void 0 ? void 0 : _b.input;
50399 if (explicitEntryPatterns) {
50400 entries = await globEntries(explicitEntryPatterns, config);
50401 }
50402 else if (buildInput) {
50403 const resolvePath = (p) => path__default.resolve(config.root, p);
50404 if (typeof buildInput === 'string') {
50405 entries = [resolvePath(buildInput)];
50406 }
50407 else if (Array.isArray(buildInput)) {
50408 entries = buildInput.map(resolvePath);
50409 }
50410 else if (isObject$3(buildInput)) {
50411 entries = Object.values(buildInput).map(resolvePath);
50412 }
50413 else {
50414 throw new Error('invalid rollupOptions.input value.');
50415 }
50416 }
50417 else {
50418 entries = await globEntries('**/*.html', config);
50419 }
50420 // Non-supported entry file types and virtual files should not be scanned for
50421 // dependencies.
50422 entries = entries.filter((entry) => (JS_TYPES_RE.test(entry) || htmlTypesRE.test(entry)) &&
50423 fs__default.existsSync(entry));
50424 if (!entries.length) {
50425 debug$9(`No entry HTML files detected`);
50426 return { deps: {}, missing: {} };
50427 }
50428 else {
50429 debug$9(`Crawling dependencies using entries:\n ${entries.join('\n ')}`);
50430 }
50431 const deps = {};
50432 const missing = {};
50433 const container = await createPluginContainer(config);
50434 const plugin = esbuildScanPlugin(config, container, deps, missing, entries);
50435 const { plugins = [], ...esbuildOptions } = (_d = (_c = config.optimizeDeps) === null || _c === void 0 ? void 0 : _c.esbuildOptions) !== null && _d !== void 0 ? _d : {};
50436 await Promise.all(entries.map((entry) => esbuild.build({
50437 absWorkingDir: process.cwd(),
50438 write: false,
50439 entryPoints: [entry],
50440 bundle: true,
50441 format: 'esm',
50442 logLevel: 'error',
50443 plugins: [...plugins, plugin],
50444 ...esbuildOptions
50445 })));
50446 debug$9(`Scan completed in ${Date.now() - s}ms:`, deps);
50447 return {
50448 deps,
50449 missing
50450 };
50451}
50452function globEntries(pattern, config) {
50453 return out$1(pattern, {
50454 cwd: config.root,
50455 ignore: [
50456 '**/node_modules/**',
50457 `**/${config.build.outDir}/**`,
50458 `**/__tests__/**`
50459 ],
50460 absolute: true
50461 });
50462}
50463const scriptModuleRE = /(<script\b[^>]*type\s*=\s*(?:"module"|'module')[^>]*>)(.*?)<\/script>/gims;
50464const scriptRE = /(<script\b(?:\s[^>]*>|>))(.*?)<\/script>/gims;
50465const commentRE = /<!--(.|[\r\n])*?-->/;
50466const srcRE = /\bsrc\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/im;
50467const langRE = /\blang\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/im;
50468function esbuildScanPlugin(config, container, depImports, missing, entries) {
50469 var _a, _b;
50470 const seen = new Map();
50471 const resolve = async (id, importer) => {
50472 const key = id + (importer && path__default.dirname(importer));
50473 if (seen.has(key)) {
50474 return seen.get(key);
50475 }
50476 const resolved = await container.resolveId(id, importer && normalizePath$4(importer));
50477 const res = resolved === null || resolved === void 0 ? void 0 : resolved.id;
50478 seen.set(key, res);
50479 return res;
50480 };
50481 const include = (_a = config.optimizeDeps) === null || _a === void 0 ? void 0 : _a.include;
50482 const exclude = (_b = config.optimizeDeps) === null || _b === void 0 ? void 0 : _b.exclude;
50483 const externalUnlessEntry = ({ path }) => ({
50484 path,
50485 external: !entries.includes(path)
50486 });
50487 return {
50488 name: 'vite:dep-scan',
50489 setup(build) {
50490 // external urls
50491 build.onResolve({ filter: externalRE }, ({ path }) => ({
50492 path,
50493 external: true
50494 }));
50495 // data urls
50496 build.onResolve({ filter: dataUrlRE }, ({ path }) => ({
50497 path,
50498 external: true
50499 }));
50500 // html types: extract script contents -----------------------------------
50501 build.onResolve({ filter: htmlTypesRE }, async ({ path, importer }) => {
50502 return {
50503 path: await resolve(path, importer),
50504 namespace: 'html'
50505 };
50506 });
50507 // extract scripts inside HTML-like files and treat it as a js module
50508 build.onLoad({ filter: htmlTypesRE, namespace: 'html' }, async ({ path }) => {
50509 let raw = fs__default.readFileSync(path, 'utf-8');
50510 // Avoid matching the content of the comment
50511 raw = raw.replace(commentRE, '<!---->');
50512 const isHtml = path.endsWith('.html');
50513 const regex = isHtml ? scriptModuleRE : scriptRE;
50514 regex.lastIndex = 0;
50515 let js = '';
50516 let loader = 'js';
50517 let match;
50518 while ((match = regex.exec(raw))) {
50519 const [, openTag, content] = match;
50520 const srcMatch = openTag.match(srcRE);
50521 const langMatch = openTag.match(langRE);
50522 const lang = langMatch && (langMatch[1] || langMatch[2] || langMatch[3]);
50523 if (lang === 'ts' || lang === 'tsx' || lang === 'jsx') {
50524 loader = lang;
50525 }
50526 if (srcMatch) {
50527 const src = srcMatch[1] || srcMatch[2] || srcMatch[3];
50528 js += `import ${JSON.stringify(src)}\n`;
50529 }
50530 else if (content.trim()) {
50531 js += content + '\n';
50532 }
50533 }
50534 if (loader.startsWith('ts') &&
50535 (path.endsWith('.svelte') ||
50536 (path.endsWith('.vue') && /<script\s+setup/.test(raw)))) {
50537 // when using TS + (Vue + <script setup>) or Svelte, imports may seem
50538 // unused to esbuild and dropped in the build output, which prevents
50539 // esbuild from crawling further.
50540 // the solution is to add `import 'x'` for every source to force
50541 // esbuild to keep crawling due to potential side effects.
50542 let m;
50543 const original = js;
50544 while ((m = importsRE.exec(original)) !== null) {
50545 // This is necessary to avoid infinite loops with zero-width matches
50546 if (m.index === importsRE.lastIndex) {
50547 importsRE.lastIndex++;
50548 }
50549 js += `\nimport ${m[1]}`;
50550 }
50551 }
50552 if (!js.includes(`export default`)) {
50553 js += `\nexport default {}`;
50554 }
50555 if (js.includes('import.meta.glob')) {
50556 return {
50557 // transformGlob already transforms to js
50558 loader: 'js',
50559 contents: await transformGlob(js, path, config.root, loader)
50560 };
50561 }
50562 return {
50563 loader,
50564 contents: js
50565 };
50566 });
50567 // bare imports: record and externalize ----------------------------------
50568 build.onResolve({
50569 // avoid matching windows volume
50570 filter: /^[\w@][^:]/
50571 }, async ({ path: id, importer }) => {
50572 if (exclude === null || exclude === void 0 ? void 0 : exclude.some((e) => e === id || id.startsWith(e + '/'))) {
50573 return externalUnlessEntry({ path: id });
50574 }
50575 if (depImports[id]) {
50576 return externalUnlessEntry({ path: id });
50577 }
50578 const resolved = await resolve(id, importer);
50579 if (resolved) {
50580 if (shouldExternalizeDep(resolved, id)) {
50581 return externalUnlessEntry({ path: id });
50582 }
50583 if (resolved.includes('node_modules') || (include === null || include === void 0 ? void 0 : include.includes(id))) {
50584 // dependency or forced included, externalize and stop crawling
50585 if (OPTIMIZABLE_ENTRY_RE.test(resolved)) {
50586 depImports[id] = resolved;
50587 }
50588 return externalUnlessEntry({ path: id });
50589 }
50590 else {
50591 // linked package, keep crawling
50592 return {
50593 path: path__default.resolve(resolved)
50594 };
50595 }
50596 }
50597 else {
50598 missing[id] = normalizePath$4(importer);
50599 }
50600 });
50601 // Externalized file types -----------------------------------------------
50602 // these are done on raw ids using esbuild's native regex filter so it
50603 // should be faster than doing it in the catch-all via js
50604 // they are done after the bare import resolve because a package name
50605 // may end with these extensions
50606 // css & json
50607 build.onResolve({
50608 filter: /\.(css|less|sass|scss|styl|stylus|pcss|postcss|json)$/
50609 }, externalUnlessEntry);
50610 // known asset types
50611 build.onResolve({
50612 filter: new RegExp(`\\.(${KNOWN_ASSET_TYPES.join('|')})$`)
50613 }, externalUnlessEntry);
50614 // known vite query types: ?worker, ?raw
50615 build.onResolve({ filter: SPECIAL_QUERY_RE }, ({ path }) => ({
50616 path,
50617 external: true
50618 }));
50619 // catch all -------------------------------------------------------------
50620 build.onResolve({
50621 filter: /.*/
50622 }, async ({ path: id, importer }) => {
50623 // use vite resolver to support urls and omitted extensions
50624 const resolved = await resolve(id, importer);
50625 if (resolved) {
50626 if (shouldExternalizeDep(resolved, id)) {
50627 return externalUnlessEntry({ path: id });
50628 }
50629 const namespace = htmlTypesRE.test(resolved) ? 'html' : undefined;
50630 return {
50631 path: path__default.resolve(cleanUrl(resolved)),
50632 namespace
50633 };
50634 }
50635 else {
50636 // resolve failed... probably unsupported type
50637 return externalUnlessEntry({ path: id });
50638 }
50639 });
50640 // for jsx/tsx, we need to access the content and check for
50641 // presence of import.meta.glob, since it results in import relationships
50642 // but isn't crawled by esbuild.
50643 build.onLoad({ filter: JS_TYPES_RE }, ({ path: id }) => {
50644 let ext = path__default.extname(id).slice(1);
50645 if (ext === 'mjs')
50646 ext = 'js';
50647 let contents = fs__default.readFileSync(id, 'utf-8');
50648 if (ext.endsWith('x') && config.esbuild && config.esbuild.jsxInject) {
50649 contents = config.esbuild.jsxInject + `\n` + contents;
50650 }
50651 if (contents.includes('import.meta.glob')) {
50652 return transformGlob(contents, id, config.root, ext).then((contents) => ({
50653 loader: ext,
50654 contents
50655 }));
50656 }
50657 return {
50658 loader: ext,
50659 contents
50660 };
50661 });
50662 }
50663 };
50664}
50665async function transformGlob(source, importer, root, loader) {
50666 // transform the content first since es-module-lexer can't handle non-js
50667 if (loader !== 'js') {
50668 source = (await esbuild.transform(source, { loader })).code;
50669 }
50670 await init;
50671 const imports = parse$e(source)[0];
50672 const s = new MagicString(source);
50673 for (let index = 0; index < imports.length; index++) {
50674 const { s: start, e: end, ss: expStart } = imports[index];
50675 const url = source.slice(start, end);
50676 if (url !== 'import.meta')
50677 continue;
50678 if (source.slice(end, end + 5) !== '.glob')
50679 continue;
50680 const { importsString, exp, endIndex } = await transformImportGlob(source, start, normalizePath$4(importer), index, root);
50681 s.prepend(importsString);
50682 s.overwrite(expStart, endIndex, exp);
50683 }
50684 return s.toString();
50685}
50686function shouldExternalizeDep(resolvedId, rawId) {
50687 // not a valid file path
50688 if (!path__default.isAbsolute(resolvedId)) {
50689 return true;
50690 }
50691 // virtual id
50692 if (resolvedId === rawId || resolvedId.includes('\0')) {
50693 return true;
50694 }
50695 // resolved is not a scannable type
50696 if (!JS_TYPES_RE.test(resolvedId) && !htmlTypesRE.test(resolvedId)) {
50697 return true;
50698 }
50699 return false;
50700}
50701
50702const importMetaUrlRE = /\bnew\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*\)/g;
50703/**
50704 * Convert `new URL('./foo.png', import.meta.url)` to its resolved built URL
50705 *
50706 * Supports tempalte string with dynamic segments:
50707 * ```
50708 * new URL(`./dir/${name}.png`, import.meta.url)
50709 * // transformed to
50710 * import.meta.globEager('./dir/**.png')[`./dir/${name}.png`].default
50711 * ```
50712 */
50713function assetImportMetaUrlPlugin(config) {
50714 return {
50715 name: 'asset-import-meta-url',
50716 async transform(code, id, ssr) {
50717 if (code.includes('new URL') && code.includes(`import.meta.url`)) {
50718 let s = null;
50719 let match;
50720 while ((match = importMetaUrlRE.exec(code))) {
50721 const { 0: exp, 1: rawUrl, index } = match;
50722 if (ssr) {
50723 this.error(`\`new URL(url, import.meta.url)\` is not supported in SSR.`, index);
50724 }
50725 if (!s)
50726 s = new MagicString(code);
50727 // potential dynamic template string
50728 if (rawUrl[0] === '`' && /\$\{/.test(rawUrl)) {
50729 const ast = this.parse(rawUrl);
50730 const templateLiteral = ast.body[0].expression;
50731 if (templateLiteral.expressions.length) {
50732 const pattern = buildGlobPattern(templateLiteral);
50733 // Note: native import.meta.url is not supported in the baseline
50734 // target so we use window.location here -
50735 s.overwrite(index, index + exp.length, `new URL(import.meta.globEagerDefault(${JSON.stringify(pattern)})[${rawUrl}], window.location)`);
50736 continue;
50737 }
50738 }
50739 const url = rawUrl.slice(1, -1);
50740 const file = path__default.resolve(path__default.dirname(id), url);
50741 const builtUrl = await fileToUrl(file, config, this);
50742 s.overwrite(index, index + exp.length, `new URL(${JSON.stringify(builtUrl)}, window.location)`);
50743 }
50744 if (s) {
50745 return {
50746 code: s.toString(),
50747 map: config.build.sourcemap ? s.generateMap({ hires: true }) : null
50748 };
50749 }
50750 }
50751 return null;
50752 }
50753 };
50754}
50755function buildGlobPattern(ast) {
50756 let pattern = '';
50757 let lastElementIndex = -1;
50758 for (const exp of ast.expressions) {
50759 for (let i = lastElementIndex + 1; i < ast.quasis.length; i++) {
50760 const el = ast.quasis[i];
50761 if (el.end < exp.start) {
50762 pattern += el.value.raw;
50763 lastElementIndex = i;
50764 }
50765 }
50766 pattern += '**';
50767 }
50768 for (let i = lastElementIndex + 1; i < ast.quasis.length; i++) {
50769 pattern += ast.quasis[i].value.raw;
50770 }
50771 return pattern;
50772}
50773
50774function resolveBuildOptions(raw) {
50775 const resolved = {
50776 target: 'modules',
50777 polyfillDynamicImport: false,
50778 outDir: 'dist',
50779 assetsDir: 'assets',
50780 assetsInlineLimit: 4096,
50781 cssCodeSplit: !(raw === null || raw === void 0 ? void 0 : raw.lib),
50782 sourcemap: false,
50783 rollupOptions: {},
50784 commonjsOptions: {
50785 include: [/node_modules/],
50786 extensions: ['.js', '.cjs'],
50787 ...raw === null || raw === void 0 ? void 0 : raw.commonjsOptions
50788 },
50789 dynamicImportVarsOptions: {
50790 warnOnError: true,
50791 exclude: [/node_modules/],
50792 ...raw === null || raw === void 0 ? void 0 : raw.dynamicImportVarsOptions
50793 },
50794 minify: (raw === null || raw === void 0 ? void 0 : raw.ssr) ? false : 'terser',
50795 terserOptions: {},
50796 cleanCssOptions: {},
50797 write: true,
50798 emptyOutDir: null,
50799 manifest: false,
50800 lib: false,
50801 ssr: false,
50802 ssrManifest: false,
50803 brotliSize: true,
50804 chunkSizeWarningLimit: 500,
50805 watch: null,
50806 ...raw
50807 };
50808 // handle special build targets
50809 if (resolved.target === 'modules') {
50810 // Support browserslist
50811 // "defaults and supports es6-module and supports es6-module-dynamic-import",
50812 resolved.target = [
50813 'es2019',
50814 'edge88',
50815 'firefox78',
50816 'chrome87',
50817 'safari13.1'
50818 ];
50819 }
50820 else if (resolved.target === 'esnext' && resolved.minify === 'terser') {
50821 // esnext + terser: limit to es2019 so it can be minified by terser
50822 resolved.target = 'es2019';
50823 }
50824 // normalize false string into actual false
50825 if (resolved.minify === 'false') {
50826 resolved.minify = false;
50827 }
50828 return resolved;
50829}
50830function resolveBuildPlugins(config) {
50831 const options = config.build;
50832 return {
50833 pre: [
50834 buildHtmlPlugin(config),
50835 commonjs(options.commonjsOptions),
50836 dataURIPlugin(),
50837 dynamicImportVariables(options.dynamicImportVarsOptions),
50838 assetImportMetaUrlPlugin(config),
50839 ...(options.rollupOptions.plugins
50840 ? options.rollupOptions.plugins.filter((p) => !!p)
50841 : [])
50842 ],
50843 post: [
50844 buildImportAnalysisPlugin(config),
50845 buildEsbuildPlugin(config),
50846 ...(options.minify && options.minify !== 'esbuild'
50847 ? [terserPlugin(options.terserOptions)]
50848 : []),
50849 ...(options.manifest ? [manifestPlugin(config)] : []),
50850 ...(options.ssrManifest ? [ssrManifestPlugin(config)] : []),
50851 buildReporterPlugin(config)
50852 ]
50853 };
50854}
50855/**
50856 * Track parallel build calls and only stop the esbuild service when all
50857 * builds are done. (#1098)
50858 */
50859let parallelCallCounts = 0;
50860// we use a separate counter to track since the call may error before the
50861// bundle is even pushed.
50862const parallelBuilds = [];
50863/**
50864 * Bundles the app for production.
50865 * Returns a Promise containing the build result.
50866 */
50867async function build(inlineConfig = {}) {
50868 parallelCallCounts++;
50869 try {
50870 return await doBuild(inlineConfig);
50871 }
50872 finally {
50873 parallelCallCounts--;
50874 if (parallelCallCounts <= 0) {
50875 await Promise.all(parallelBuilds.map((bundle) => bundle.close()));
50876 parallelBuilds.length = 0;
50877 }
50878 }
50879}
50880async function doBuild(inlineConfig = {}) {
50881 var _a, _b, _c, _d;
50882 const config = await resolveConfig(inlineConfig, 'build', 'production');
50883 const options = config.build;
50884 const ssr = !!options.ssr;
50885 const libOptions = options.lib;
50886 config.logger.info(source.cyan(`vite v${require('vite/package.json').version} ${source.green(`building ${ssr ? `SSR bundle ` : ``}for ${config.mode}...`)}`));
50887 const resolve = (p) => path__default.resolve(config.root, p);
50888 const input = libOptions
50889 ? resolve(libOptions.entry)
50890 : typeof options.ssr === 'string'
50891 ? resolve(options.ssr)
50892 : ((_a = options.rollupOptions) === null || _a === void 0 ? void 0 : _a.input) || resolve('index.html');
50893 if (ssr && typeof input === 'string' && input.endsWith('.html')) {
50894 throw new Error(`rollupOptions.input should not be an html file when building for SSR. ` +
50895 `Please specify a dedicated SSR entry.`);
50896 }
50897 const outDir = resolve(options.outDir);
50898 // inject ssr arg to plugin load/transform hooks
50899 const plugins = (ssr ? config.plugins.map((p) => injectSsrFlagToHooks(p)) : config.plugins);
50900 // inject ssrExternal if present
50901 const userExternal = (_b = options.rollupOptions) === null || _b === void 0 ? void 0 : _b.external;
50902 let external = userExternal;
50903 if (ssr) {
50904 // see if we have cached deps data available
50905 let knownImports;
50906 if (config.cacheDir) {
50907 const dataPath = path__default.join(config.cacheDir, '_metadata.json');
50908 try {
50909 const data = JSON.parse(fs__default.readFileSync(dataPath, 'utf-8'));
50910 knownImports = Object.keys(data.optimized);
50911 }
50912 catch (e) { }
50913 }
50914 if (!knownImports) {
50915 // no dev deps optimization data, do a fresh scan
50916 knownImports = Object.keys((await scanImports(config)).deps);
50917 }
50918 external = resolveExternal(resolveSSRExternal(config, knownImports), userExternal);
50919 }
50920 const rollup = require('rollup');
50921 const rollupOptions = {
50922 input,
50923 preserveEntrySignatures: ssr
50924 ? 'allow-extension'
50925 : libOptions
50926 ? 'strict'
50927 : false,
50928 ...options.rollupOptions,
50929 plugins,
50930 external,
50931 onwarn(warning, warn) {
50932 onRollupWarning(warning, warn, config);
50933 }
50934 };
50935 const outputBuildError = (e) => {
50936 config.logger.error(source.red(`${e.plugin ? `[${e.plugin}] ` : ''}${e.message}`));
50937 if (e.id) {
50938 const loc = e.loc ? `:${e.loc.line}:${e.loc.column}` : '';
50939 config.logger.error(`file: ${source.cyan(`${e.id}${loc}`)}`);
50940 }
50941 if (e.frame) {
50942 config.logger.error(source.yellow(e.frame));
50943 }
50944 };
50945 try {
50946 const pkgName = libOptions && getPkgName(config.root);
50947 const buildOutputOptions = (output = {}) => {
50948 return {
50949 dir: outDir,
50950 format: ssr ? 'cjs' : 'es',
50951 exports: ssr ? 'named' : 'auto',
50952 sourcemap: options.sourcemap,
50953 name: libOptions ? libOptions.name : undefined,
50954 entryFileNames: ssr
50955 ? `[name].js`
50956 : libOptions
50957 ? `${libOptions.fileName || pkgName}.${output.format || `es`}.js`
50958 : path__default.posix.join(options.assetsDir, `[name].[hash].js`),
50959 chunkFileNames: libOptions
50960 ? `[name].js`
50961 : path__default.posix.join(options.assetsDir, `[name].[hash].js`),
50962 assetFileNames: libOptions
50963 ? `[name].[ext]`
50964 : path__default.posix.join(options.assetsDir, `[name].[hash].[ext]`),
50965 // #764 add `Symbol.toStringTag` when build es module into cjs chunk
50966 // #1048 add `Symbol.toStringTag` for module default export
50967 namespaceToStringTag: true,
50968 inlineDynamicImports: ssr && typeof input === 'string',
50969 manualChunks: !ssr &&
50970 !libOptions &&
50971 (output === null || output === void 0 ? void 0 : output.format) !== 'umd' &&
50972 (output === null || output === void 0 ? void 0 : output.format) !== 'iife'
50973 ? createMoveToVendorChunkFn()
50974 : undefined,
50975 ...output
50976 };
50977 };
50978 // resolve lib mode outputs
50979 const outputs = resolveBuildOutputs((_c = options.rollupOptions) === null || _c === void 0 ? void 0 : _c.output, libOptions, config.logger);
50980 // watch file changes with rollup
50981 if (config.build.watch) {
50982 config.logger.info(source.cyanBright(`\nwatching for file changes...`));
50983 const output = [];
50984 if (Array.isArray(outputs)) {
50985 for (const resolvedOutput of outputs) {
50986 output.push(buildOutputOptions(resolvedOutput));
50987 }
50988 }
50989 else {
50990 output.push(buildOutputOptions(outputs));
50991 }
50992 const watcherOptions = config.build.watch;
50993 const watcher = rollup.watch({
50994 ...rollupOptions,
50995 output,
50996 watch: {
50997 ...watcherOptions,
50998 chokidar: {
50999 ignored: [
51000 '**/node_modules/**',
51001 '**/.git/**',
51002 ...(((_d = watcherOptions === null || watcherOptions === void 0 ? void 0 : watcherOptions.chokidar) === null || _d === void 0 ? void 0 : _d.ignored) || [])
51003 ],
51004 ignoreInitial: true,
51005 ignorePermissionErrors: true,
51006 ...watcherOptions.chokidar
51007 }
51008 }
51009 });
51010 watcher.on('event', (event) => {
51011 if (event.code === 'BUNDLE_START') {
51012 config.logger.info(source.cyanBright(`\nbuild started...`));
51013 if (options.write) {
51014 prepareOutDir(outDir, options.emptyOutDir, config);
51015 }
51016 }
51017 else if (event.code === 'BUNDLE_END') {
51018 event.result.close();
51019 config.logger.info(source.cyanBright(`built in ${event.duration}ms.`));
51020 }
51021 else if (event.code === 'ERROR') {
51022 outputBuildError(event.error);
51023 }
51024 });
51025 // stop watching
51026 watcher.close();
51027 return watcher;
51028 }
51029 // write or generate files with rollup
51030 const bundle = await rollup.rollup(rollupOptions);
51031 parallelBuilds.push(bundle);
51032 const generate = (output = {}) => {
51033 return bundle[options.write ? 'write' : 'generate'](buildOutputOptions(output));
51034 };
51035 if (options.write) {
51036 prepareOutDir(outDir, options.emptyOutDir, config);
51037 }
51038 if (Array.isArray(outputs)) {
51039 const res = [];
51040 for (const output of outputs) {
51041 res.push(await generate(output));
51042 }
51043 return res;
51044 }
51045 else {
51046 return await generate(outputs);
51047 }
51048 }
51049 catch (e) {
51050 outputBuildError(e);
51051 throw e;
51052 }
51053}
51054function prepareOutDir(outDir, emptyOutDir, config) {
51055 if (fs__default.existsSync(outDir)) {
51056 if (emptyOutDir == null &&
51057 !normalizePath$4(outDir).startsWith(config.root + '/')) {
51058 // warn if outDir is outside of root
51059 config.logger.warn(source.yellow(`\n${source.bold(`(!)`)} outDir ${source.white.dim(outDir)} is not inside project root and will not be emptied.\n` +
51060 `Use --emptyOutDir to override.\n`));
51061 }
51062 else if (emptyOutDir !== false) {
51063 emptyDir(outDir, ['.git']);
51064 }
51065 }
51066 if (config.publicDir && fs__default.existsSync(config.publicDir)) {
51067 copyDir(config.publicDir, outDir);
51068 }
51069}
51070function getPkgName(root) {
51071 const { name } = JSON.parse(lookupFile(root, ['package.json']) || `{}`);
51072 if (!name)
51073 throw new Error('no name found in package.json');
51074 return name.startsWith('@') ? name.split('/')[1] : name;
51075}
51076function createMoveToVendorChunkFn(config) {
51077 const cache = new Map();
51078 return (id, { getModuleInfo }) => {
51079 if (id.includes('node_modules') &&
51080 !isCSSRequest(id) &&
51081 staticImportedByEntry(id, getModuleInfo, cache)) {
51082 return 'vendor';
51083 }
51084 };
51085}
51086function staticImportedByEntry(id, getModuleInfo, cache, importStack = []) {
51087 if (cache.has(id)) {
51088 return cache.get(id);
51089 }
51090 if (importStack.includes(id)) {
51091 // circular deps!
51092 cache.set(id, false);
51093 return false;
51094 }
51095 const mod = getModuleInfo(id);
51096 if (!mod) {
51097 cache.set(id, false);
51098 return false;
51099 }
51100 if (mod.isEntry) {
51101 cache.set(id, true);
51102 return true;
51103 }
51104 const someImporterIs = mod.importers.some((importer) => staticImportedByEntry(importer, getModuleInfo, cache, importStack.concat(id)));
51105 cache.set(id, someImporterIs);
51106 return someImporterIs;
51107}
51108function resolveBuildOutputs(outputs, libOptions, logger) {
51109 if (libOptions) {
51110 const formats = libOptions.formats || ['es', 'umd'];
51111 if ((formats.includes('umd') || formats.includes('iife')) &&
51112 !libOptions.name) {
51113 throw new Error(`Option "build.lib.name" is required when output formats ` +
51114 `include "umd" or "iife".`);
51115 }
51116 if (!outputs) {
51117 return formats.map((format) => ({ format }));
51118 }
51119 else if (!Array.isArray(outputs)) {
51120 return formats.map((format) => ({ ...outputs, format }));
51121 }
51122 else if (libOptions.formats) {
51123 // user explicitly specifying own output array
51124 logger.warn(source.yellow(`"build.lib.formats" will be ignored because ` +
51125 `"build.rollupOptions.output" is already an array format`));
51126 }
51127 }
51128 return outputs;
51129}
51130const warningIgnoreList = [`CIRCULAR_DEPENDENCY`, `THIS_IS_UNDEFINED`];
51131const dynamicImportWarningIgnoreList = [
51132 `Unsupported expression`,
51133 `statically analyzed`
51134];
51135function onRollupWarning(warning, warn, config) {
51136 var _a;
51137 if (warning.code === 'UNRESOLVED_IMPORT') {
51138 const id = warning.source;
51139 const importer = warning.importer;
51140 // throw unless it's commonjs external...
51141 if (!importer || !/\?commonjs-external$/.test(importer)) {
51142 throw new Error(`[vite]: Rollup failed to resolve import "${id}" from "${importer}".\n` +
51143 `This is most likely unintended because it can break your application at runtime.\n` +
51144 `If you do want to externalize this module explicitly add it to\n` +
51145 `\`build.rollupOptions.external\``);
51146 }
51147 }
51148 if (warning.plugin === 'rollup-plugin-dynamic-import-variables' &&
51149 dynamicImportWarningIgnoreList.some((msg) => warning.message.includes(msg))) {
51150 return;
51151 }
51152 if (!warningIgnoreList.includes(warning.code)) {
51153 const userOnWarn = (_a = config.build.rollupOptions) === null || _a === void 0 ? void 0 : _a.onwarn;
51154 if (userOnWarn) {
51155 userOnWarn(warning, warn);
51156 }
51157 else if (warning.code === 'PLUGIN_WARNING') {
51158 config.logger.warn(`${source.bold.yellow(`[plugin:${warning.plugin}]`)} ${source.yellow(warning.message)}`);
51159 }
51160 else {
51161 warn(warning);
51162 }
51163 }
51164}
51165function resolveExternal(ssrExternals, user) {
51166 return ((id, parentId, isResolved) => {
51167 if (shouldExternalizeForSSR(id, ssrExternals)) {
51168 return true;
51169 }
51170 if (user) {
51171 if (typeof user === 'function') {
51172 return user(id, parentId, isResolved);
51173 }
51174 else if (Array.isArray(user)) {
51175 return user.some((test) => isExternal(id, test));
51176 }
51177 else {
51178 return isExternal(id, user);
51179 }
51180 }
51181 });
51182}
51183function isExternal(id, test) {
51184 if (typeof test === 'string') {
51185 return id === test;
51186 }
51187 else {
51188 return test.test(id);
51189 }
51190}
51191function injectSsrFlagToHooks(p) {
51192 const { resolveId, load, transform } = p;
51193 return {
51194 ...p,
51195 resolveId: wrapSsrHook(resolveId),
51196 load: wrapSsrHook(load),
51197 transform: wrapSsrHook(transform)
51198 };
51199}
51200function wrapSsrHook(fn) {
51201 if (!fn)
51202 return;
51203 return function (...args) {
51204 return fn.call(this, ...args, true);
51205 };
51206}
51207
51208var build$1 = {
51209 __proto__: null,
51210 resolveBuildOptions: resolveBuildOptions,
51211 resolveBuildPlugins: resolveBuildPlugins,
51212 build: build,
51213 onRollupWarning: onRollupWarning
51214};
51215
51216var src$2 = {exports: {}};
51217
51218var browser$2 = {exports: {}};
51219
51220var debug$8 = {exports: {}};
51221
51222/**
51223 * Helpers.
51224 */
51225
51226var s$1 = 1000;
51227var m$1 = s$1 * 60;
51228var h$1 = m$1 * 60;
51229var d$1 = h$1 * 24;
51230var y$1 = d$1 * 365.25;
51231
51232/**
51233 * Parse or format the given `val`.
51234 *
51235 * Options:
51236 *
51237 * - `long` verbose formatting [false]
51238 *
51239 * @param {String|Number} val
51240 * @param {Object} [options]
51241 * @throws {Error} throw an error if val is not a non-empty string or a number
51242 * @return {String|Number}
51243 * @api public
51244 */
51245
51246var ms$1 = function(val, options) {
51247 options = options || {};
51248 var type = typeof val;
51249 if (type === 'string' && val.length > 0) {
51250 return parse$b(val);
51251 } else if (type === 'number' && isNaN(val) === false) {
51252 return options.long ? fmtLong$1(val) : fmtShort$1(val);
51253 }
51254 throw new Error(
51255 'val is not a non-empty string or a valid number. val=' +
51256 JSON.stringify(val)
51257 );
51258};
51259
51260/**
51261 * Parse the given `str` and return milliseconds.
51262 *
51263 * @param {String} str
51264 * @return {Number}
51265 * @api private
51266 */
51267
51268function parse$b(str) {
51269 str = String(str);
51270 if (str.length > 100) {
51271 return;
51272 }
51273 var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(
51274 str
51275 );
51276 if (!match) {
51277 return;
51278 }
51279 var n = parseFloat(match[1]);
51280 var type = (match[2] || 'ms').toLowerCase();
51281 switch (type) {
51282 case 'years':
51283 case 'year':
51284 case 'yrs':
51285 case 'yr':
51286 case 'y':
51287 return n * y$1;
51288 case 'days':
51289 case 'day':
51290 case 'd':
51291 return n * d$1;
51292 case 'hours':
51293 case 'hour':
51294 case 'hrs':
51295 case 'hr':
51296 case 'h':
51297 return n * h$1;
51298 case 'minutes':
51299 case 'minute':
51300 case 'mins':
51301 case 'min':
51302 case 'm':
51303 return n * m$1;
51304 case 'seconds':
51305 case 'second':
51306 case 'secs':
51307 case 'sec':
51308 case 's':
51309 return n * s$1;
51310 case 'milliseconds':
51311 case 'millisecond':
51312 case 'msecs':
51313 case 'msec':
51314 case 'ms':
51315 return n;
51316 default:
51317 return undefined;
51318 }
51319}
51320
51321/**
51322 * Short format for `ms`.
51323 *
51324 * @param {Number} ms
51325 * @return {String}
51326 * @api private
51327 */
51328
51329function fmtShort$1(ms) {
51330 if (ms >= d$1) {
51331 return Math.round(ms / d$1) + 'd';
51332 }
51333 if (ms >= h$1) {
51334 return Math.round(ms / h$1) + 'h';
51335 }
51336 if (ms >= m$1) {
51337 return Math.round(ms / m$1) + 'm';
51338 }
51339 if (ms >= s$1) {
51340 return Math.round(ms / s$1) + 's';
51341 }
51342 return ms + 'ms';
51343}
51344
51345/**
51346 * Long format for `ms`.
51347 *
51348 * @param {Number} ms
51349 * @return {String}
51350 * @api private
51351 */
51352
51353function fmtLong$1(ms) {
51354 return plural$1(ms, d$1, 'day') ||
51355 plural$1(ms, h$1, 'hour') ||
51356 plural$1(ms, m$1, 'minute') ||
51357 plural$1(ms, s$1, 'second') ||
51358 ms + ' ms';
51359}
51360
51361/**
51362 * Pluralization helper.
51363 */
51364
51365function plural$1(ms, n, name) {
51366 if (ms < n) {
51367 return;
51368 }
51369 if (ms < n * 1.5) {
51370 return Math.floor(ms / n) + ' ' + name;
51371 }
51372 return Math.ceil(ms / n) + ' ' + name + 's';
51373}
51374
51375(function (module, exports) {
51376/**
51377 * This is the common logic for both the Node.js and web browser
51378 * implementations of `debug()`.
51379 *
51380 * Expose `debug()` as the module.
51381 */
51382
51383exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
51384exports.coerce = coerce;
51385exports.disable = disable;
51386exports.enable = enable;
51387exports.enabled = enabled;
51388exports.humanize = ms$1;
51389
51390/**
51391 * The currently active debug mode names, and names to skip.
51392 */
51393
51394exports.names = [];
51395exports.skips = [];
51396
51397/**
51398 * Map of special "%n" handling functions, for the debug "format" argument.
51399 *
51400 * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
51401 */
51402
51403exports.formatters = {};
51404
51405/**
51406 * Previous log timestamp.
51407 */
51408
51409var prevTime;
51410
51411/**
51412 * Select a color.
51413 * @param {String} namespace
51414 * @return {Number}
51415 * @api private
51416 */
51417
51418function selectColor(namespace) {
51419 var hash = 0, i;
51420
51421 for (i in namespace) {
51422 hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
51423 hash |= 0; // Convert to 32bit integer
51424 }
51425
51426 return exports.colors[Math.abs(hash) % exports.colors.length];
51427}
51428
51429/**
51430 * Create a debugger with the given `namespace`.
51431 *
51432 * @param {String} namespace
51433 * @return {Function}
51434 * @api public
51435 */
51436
51437function createDebug(namespace) {
51438
51439 function debug() {
51440 // disabled?
51441 if (!debug.enabled) return;
51442
51443 var self = debug;
51444
51445 // set `diff` timestamp
51446 var curr = +new Date();
51447 var ms = curr - (prevTime || curr);
51448 self.diff = ms;
51449 self.prev = prevTime;
51450 self.curr = curr;
51451 prevTime = curr;
51452
51453 // turn the `arguments` into a proper Array
51454 var args = new Array(arguments.length);
51455 for (var i = 0; i < args.length; i++) {
51456 args[i] = arguments[i];
51457 }
51458
51459 args[0] = exports.coerce(args[0]);
51460
51461 if ('string' !== typeof args[0]) {
51462 // anything else let's inspect with %O
51463 args.unshift('%O');
51464 }
51465
51466 // apply any `formatters` transformations
51467 var index = 0;
51468 args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
51469 // if we encounter an escaped % then don't increase the array index
51470 if (match === '%%') return match;
51471 index++;
51472 var formatter = exports.formatters[format];
51473 if ('function' === typeof formatter) {
51474 var val = args[index];
51475 match = formatter.call(self, val);
51476
51477 // now we need to remove `args[index]` since it's inlined in the `format`
51478 args.splice(index, 1);
51479 index--;
51480 }
51481 return match;
51482 });
51483
51484 // apply env-specific formatting (colors, etc.)
51485 exports.formatArgs.call(self, args);
51486
51487 var logFn = debug.log || exports.log || console.log.bind(console);
51488 logFn.apply(self, args);
51489 }
51490
51491 debug.namespace = namespace;
51492 debug.enabled = exports.enabled(namespace);
51493 debug.useColors = exports.useColors();
51494 debug.color = selectColor(namespace);
51495
51496 // env-specific initialization logic for debug instances
51497 if ('function' === typeof exports.init) {
51498 exports.init(debug);
51499 }
51500
51501 return debug;
51502}
51503
51504/**
51505 * Enables a debug mode by namespaces. This can include modes
51506 * separated by a colon and wildcards.
51507 *
51508 * @param {String} namespaces
51509 * @api public
51510 */
51511
51512function enable(namespaces) {
51513 exports.save(namespaces);
51514
51515 exports.names = [];
51516 exports.skips = [];
51517
51518 var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
51519 var len = split.length;
51520
51521 for (var i = 0; i < len; i++) {
51522 if (!split[i]) continue; // ignore empty strings
51523 namespaces = split[i].replace(/\*/g, '.*?');
51524 if (namespaces[0] === '-') {
51525 exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
51526 } else {
51527 exports.names.push(new RegExp('^' + namespaces + '$'));
51528 }
51529 }
51530}
51531
51532/**
51533 * Disable debug output.
51534 *
51535 * @api public
51536 */
51537
51538function disable() {
51539 exports.enable('');
51540}
51541
51542/**
51543 * Returns true if the given mode name is enabled, false otherwise.
51544 *
51545 * @param {String} name
51546 * @return {Boolean}
51547 * @api public
51548 */
51549
51550function enabled(name) {
51551 var i, len;
51552 for (i = 0, len = exports.skips.length; i < len; i++) {
51553 if (exports.skips[i].test(name)) {
51554 return false;
51555 }
51556 }
51557 for (i = 0, len = exports.names.length; i < len; i++) {
51558 if (exports.names[i].test(name)) {
51559 return true;
51560 }
51561 }
51562 return false;
51563}
51564
51565/**
51566 * Coerce `val`.
51567 *
51568 * @param {Mixed} val
51569 * @return {Mixed}
51570 * @api private
51571 */
51572
51573function coerce(val) {
51574 if (val instanceof Error) return val.stack || val.message;
51575 return val;
51576}
51577}(debug$8, debug$8.exports));
51578
51579/**
51580 * This is the web browser implementation of `debug()`.
51581 *
51582 * Expose `debug()` as the module.
51583 */
51584
51585(function (module, exports) {
51586exports = module.exports = debug$8.exports;
51587exports.log = log;
51588exports.formatArgs = formatArgs;
51589exports.save = save;
51590exports.load = load;
51591exports.useColors = useColors;
51592exports.storage = 'undefined' != typeof chrome
51593 && 'undefined' != typeof chrome.storage
51594 ? chrome.storage.local
51595 : localstorage();
51596
51597/**
51598 * Colors.
51599 */
51600
51601exports.colors = [
51602 'lightseagreen',
51603 'forestgreen',
51604 'goldenrod',
51605 'dodgerblue',
51606 'darkorchid',
51607 'crimson'
51608];
51609
51610/**
51611 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
51612 * and the Firebug extension (any Firefox version) are known
51613 * to support "%c" CSS customizations.
51614 *
51615 * TODO: add a `localStorage` variable to explicitly enable/disable colors
51616 */
51617
51618function useColors() {
51619 // NB: In an Electron preload script, document will be defined but not fully
51620 // initialized. Since we know we're in Chrome, we'll just detect this case
51621 // explicitly
51622 if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
51623 return true;
51624 }
51625
51626 // is webkit? http://stackoverflow.com/a/16459606/376773
51627 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
51628 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
51629 // is firebug? http://stackoverflow.com/a/398120/376773
51630 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
51631 // is firefox >= v31?
51632 // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
51633 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
51634 // double check webkit in userAgent just in case we are in a worker
51635 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
51636}
51637
51638/**
51639 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
51640 */
51641
51642exports.formatters.j = function(v) {
51643 try {
51644 return JSON.stringify(v);
51645 } catch (err) {
51646 return '[UnexpectedJSONParseError]: ' + err.message;
51647 }
51648};
51649
51650
51651/**
51652 * Colorize log arguments if enabled.
51653 *
51654 * @api public
51655 */
51656
51657function formatArgs(args) {
51658 var useColors = this.useColors;
51659
51660 args[0] = (useColors ? '%c' : '')
51661 + this.namespace
51662 + (useColors ? ' %c' : ' ')
51663 + args[0]
51664 + (useColors ? '%c ' : ' ')
51665 + '+' + exports.humanize(this.diff);
51666
51667 if (!useColors) return;
51668
51669 var c = 'color: ' + this.color;
51670 args.splice(1, 0, c, 'color: inherit');
51671
51672 // the final "%c" is somewhat tricky, because there could be other
51673 // arguments passed either before or after the %c, so we need to
51674 // figure out the correct index to insert the CSS into
51675 var index = 0;
51676 var lastC = 0;
51677 args[0].replace(/%[a-zA-Z%]/g, function(match) {
51678 if ('%%' === match) return;
51679 index++;
51680 if ('%c' === match) {
51681 // we only are interested in the *last* %c
51682 // (the user may have provided their own)
51683 lastC = index;
51684 }
51685 });
51686
51687 args.splice(lastC, 0, c);
51688}
51689
51690/**
51691 * Invokes `console.log()` when available.
51692 * No-op when `console.log` is not a "function".
51693 *
51694 * @api public
51695 */
51696
51697function log() {
51698 // this hackery is required for IE8/9, where
51699 // the `console.log` function doesn't have 'apply'
51700 return 'object' === typeof console
51701 && console.log
51702 && Function.prototype.apply.call(console.log, console, arguments);
51703}
51704
51705/**
51706 * Save `namespaces`.
51707 *
51708 * @param {String} namespaces
51709 * @api private
51710 */
51711
51712function save(namespaces) {
51713 try {
51714 if (null == namespaces) {
51715 exports.storage.removeItem('debug');
51716 } else {
51717 exports.storage.debug = namespaces;
51718 }
51719 } catch(e) {}
51720}
51721
51722/**
51723 * Load `namespaces`.
51724 *
51725 * @return {String} returns the previously persisted debug modes
51726 * @api private
51727 */
51728
51729function load() {
51730 var r;
51731 try {
51732 r = exports.storage.debug;
51733 } catch(e) {}
51734
51735 // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
51736 if (!r && typeof process !== 'undefined' && 'env' in process) {
51737 r = process.env.DEBUG;
51738 }
51739
51740 return r;
51741}
51742
51743/**
51744 * Enable namespaces listed in `localStorage.debug` initially.
51745 */
51746
51747exports.enable(load());
51748
51749/**
51750 * Localstorage attempts to return the localstorage.
51751 *
51752 * This is necessary because safari throws
51753 * when a user disables cookies/localstorage
51754 * and you attempt to access it.
51755 *
51756 * @return {LocalStorage}
51757 * @api private
51758 */
51759
51760function localstorage() {
51761 try {
51762 return window.localStorage;
51763 } catch (e) {}
51764}
51765}(browser$2, browser$2.exports));
51766
51767var node$2 = {exports: {}};
51768
51769/**
51770 * Module dependencies.
51771 */
51772
51773(function (module, exports) {
51774var tty = require$$0__default;
51775var util = require$$0__default$3;
51776
51777/**
51778 * This is the Node.js implementation of `debug()`.
51779 *
51780 * Expose `debug()` as the module.
51781 */
51782
51783exports = module.exports = debug$8.exports;
51784exports.init = init;
51785exports.log = log;
51786exports.formatArgs = formatArgs;
51787exports.save = save;
51788exports.load = load;
51789exports.useColors = useColors;
51790
51791/**
51792 * Colors.
51793 */
51794
51795exports.colors = [6, 2, 3, 4, 5, 1];
51796
51797/**
51798 * Build up the default `inspectOpts` object from the environment variables.
51799 *
51800 * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
51801 */
51802
51803exports.inspectOpts = Object.keys(process.env).filter(function (key) {
51804 return /^debug_/i.test(key);
51805}).reduce(function (obj, key) {
51806 // camel-case
51807 var prop = key
51808 .substring(6)
51809 .toLowerCase()
51810 .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() });
51811
51812 // coerce string value into JS value
51813 var val = process.env[key];
51814 if (/^(yes|on|true|enabled)$/i.test(val)) val = true;
51815 else if (/^(no|off|false|disabled)$/i.test(val)) val = false;
51816 else if (val === 'null') val = null;
51817 else val = Number(val);
51818
51819 obj[prop] = val;
51820 return obj;
51821}, {});
51822
51823/**
51824 * The file descriptor to write the `debug()` calls to.
51825 * Set the `DEBUG_FD` env variable to override with another value. i.e.:
51826 *
51827 * $ DEBUG_FD=3 node script.js 3>debug.log
51828 */
51829
51830var fd = parseInt(process.env.DEBUG_FD, 10) || 2;
51831
51832if (1 !== fd && 2 !== fd) {
51833 util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')();
51834}
51835
51836var stream = 1 === fd ? process.stdout :
51837 2 === fd ? process.stderr :
51838 createWritableStdioStream(fd);
51839
51840/**
51841 * Is stdout a TTY? Colored output is enabled when `true`.
51842 */
51843
51844function useColors() {
51845 return 'colors' in exports.inspectOpts
51846 ? Boolean(exports.inspectOpts.colors)
51847 : tty.isatty(fd);
51848}
51849
51850/**
51851 * Map %o to `util.inspect()`, all on a single line.
51852 */
51853
51854exports.formatters.o = function(v) {
51855 this.inspectOpts.colors = this.useColors;
51856 return util.inspect(v, this.inspectOpts)
51857 .split('\n').map(function(str) {
51858 return str.trim()
51859 }).join(' ');
51860};
51861
51862/**
51863 * Map %o to `util.inspect()`, allowing multiple lines if needed.
51864 */
51865
51866exports.formatters.O = function(v) {
51867 this.inspectOpts.colors = this.useColors;
51868 return util.inspect(v, this.inspectOpts);
51869};
51870
51871/**
51872 * Adds ANSI color escape codes if enabled.
51873 *
51874 * @api public
51875 */
51876
51877function formatArgs(args) {
51878 var name = this.namespace;
51879 var useColors = this.useColors;
51880
51881 if (useColors) {
51882 var c = this.color;
51883 var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m';
51884
51885 args[0] = prefix + args[0].split('\n').join('\n' + prefix);
51886 args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m');
51887 } else {
51888 args[0] = new Date().toUTCString()
51889 + ' ' + name + ' ' + args[0];
51890 }
51891}
51892
51893/**
51894 * Invokes `util.format()` with the specified arguments and writes to `stream`.
51895 */
51896
51897function log() {
51898 return stream.write(util.format.apply(util, arguments) + '\n');
51899}
51900
51901/**
51902 * Save `namespaces`.
51903 *
51904 * @param {String} namespaces
51905 * @api private
51906 */
51907
51908function save(namespaces) {
51909 if (null == namespaces) {
51910 // If you set a process.env field to null or undefined, it gets cast to the
51911 // string 'null' or 'undefined'. Just delete instead.
51912 delete process.env.DEBUG;
51913 } else {
51914 process.env.DEBUG = namespaces;
51915 }
51916}
51917
51918/**
51919 * Load `namespaces`.
51920 *
51921 * @return {String} returns the previously persisted debug modes
51922 * @api private
51923 */
51924
51925function load() {
51926 return process.env.DEBUG;
51927}
51928
51929/**
51930 * Copied from `node/src/node.js`.
51931 *
51932 * XXX: It's lame that node doesn't expose this API out-of-the-box. It also
51933 * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame.
51934 */
51935
51936function createWritableStdioStream (fd) {
51937 var stream;
51938 var tty_wrap = process.binding('tty_wrap');
51939
51940 // Note stream._type is used for test-module-load-list.js
51941
51942 switch (tty_wrap.guessHandleType(fd)) {
51943 case 'TTY':
51944 stream = new tty.WriteStream(fd);
51945 stream._type = 'tty';
51946
51947 // Hack to have stream not keep the event loop alive.
51948 // See https://github.com/joyent/node/issues/1726
51949 if (stream._handle && stream._handle.unref) {
51950 stream._handle.unref();
51951 }
51952 break;
51953
51954 case 'FILE':
51955 var fs = fs__default;
51956 stream = new fs.SyncWriteStream(fd, { autoClose: false });
51957 stream._type = 'fs';
51958 break;
51959
51960 case 'PIPE':
51961 case 'TCP':
51962 var net = require$$4__default$1;
51963 stream = new net.Socket({
51964 fd: fd,
51965 readable: false,
51966 writable: true
51967 });
51968
51969 // FIXME Should probably have an option in net.Socket to create a
51970 // stream from an existing fd which is writable only. But for now
51971 // we'll just add this hack and set the `readable` member to false.
51972 // Test: ./node test/fixtures/echo.js < /etc/passwd
51973 stream.readable = false;
51974 stream.read = null;
51975 stream._type = 'pipe';
51976
51977 // FIXME Hack to have stream not keep the event loop alive.
51978 // See https://github.com/joyent/node/issues/1726
51979 if (stream._handle && stream._handle.unref) {
51980 stream._handle.unref();
51981 }
51982 break;
51983
51984 default:
51985 // Probably an error on in uv_guess_handle()
51986 throw new Error('Implement me. Unknown stream file type!');
51987 }
51988
51989 // For supporting legacy API we put the FD here.
51990 stream.fd = fd;
51991
51992 stream._isStdio = true;
51993
51994 return stream;
51995}
51996
51997/**
51998 * Init logic for `debug` instances.
51999 *
52000 * Create a new `inspectOpts` object in case `useColors` is set
52001 * differently for a particular `debug` instance.
52002 */
52003
52004function init (debug) {
52005 debug.inspectOpts = {};
52006
52007 var keys = Object.keys(exports.inspectOpts);
52008 for (var i = 0; i < keys.length; i++) {
52009 debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
52010 }
52011}
52012
52013/**
52014 * Enable namespaces listed in `process.env.DEBUG` initially.
52015 */
52016
52017exports.enable(load());
52018}(node$2, node$2.exports));
52019
52020/**
52021 * Detect Electron renderer process, which is node, but we should
52022 * treat as a browser.
52023 */
52024
52025if (typeof process !== 'undefined' && process.type === 'renderer') {
52026 src$2.exports = browser$2.exports;
52027} else {
52028 src$2.exports = node$2.exports;
52029}
52030
52031var src$1 = {exports: {}};
52032
52033var browser$1 = {exports: {}};
52034
52035var debug$7 = {exports: {}};
52036
52037(function (module, exports) {
52038/**
52039 * This is the common logic for both the Node.js and web browser
52040 * implementations of `debug()`.
52041 *
52042 * Expose `debug()` as the module.
52043 */
52044
52045exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
52046exports.coerce = coerce;
52047exports.disable = disable;
52048exports.enable = enable;
52049exports.enabled = enabled;
52050exports.humanize = ms$1;
52051
52052/**
52053 * The currently active debug mode names, and names to skip.
52054 */
52055
52056exports.names = [];
52057exports.skips = [];
52058
52059/**
52060 * Map of special "%n" handling functions, for the debug "format" argument.
52061 *
52062 * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
52063 */
52064
52065exports.formatters = {};
52066
52067/**
52068 * Previous log timestamp.
52069 */
52070
52071var prevTime;
52072
52073/**
52074 * Select a color.
52075 * @param {String} namespace
52076 * @return {Number}
52077 * @api private
52078 */
52079
52080function selectColor(namespace) {
52081 var hash = 0, i;
52082
52083 for (i in namespace) {
52084 hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
52085 hash |= 0; // Convert to 32bit integer
52086 }
52087
52088 return exports.colors[Math.abs(hash) % exports.colors.length];
52089}
52090
52091/**
52092 * Create a debugger with the given `namespace`.
52093 *
52094 * @param {String} namespace
52095 * @return {Function}
52096 * @api public
52097 */
52098
52099function createDebug(namespace) {
52100
52101 function debug() {
52102 // disabled?
52103 if (!debug.enabled) return;
52104
52105 var self = debug;
52106
52107 // set `diff` timestamp
52108 var curr = +new Date();
52109 var ms = curr - (prevTime || curr);
52110 self.diff = ms;
52111 self.prev = prevTime;
52112 self.curr = curr;
52113 prevTime = curr;
52114
52115 // turn the `arguments` into a proper Array
52116 var args = new Array(arguments.length);
52117 for (var i = 0; i < args.length; i++) {
52118 args[i] = arguments[i];
52119 }
52120
52121 args[0] = exports.coerce(args[0]);
52122
52123 if ('string' !== typeof args[0]) {
52124 // anything else let's inspect with %O
52125 args.unshift('%O');
52126 }
52127
52128 // apply any `formatters` transformations
52129 var index = 0;
52130 args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
52131 // if we encounter an escaped % then don't increase the array index
52132 if (match === '%%') return match;
52133 index++;
52134 var formatter = exports.formatters[format];
52135 if ('function' === typeof formatter) {
52136 var val = args[index];
52137 match = formatter.call(self, val);
52138
52139 // now we need to remove `args[index]` since it's inlined in the `format`
52140 args.splice(index, 1);
52141 index--;
52142 }
52143 return match;
52144 });
52145
52146 // apply env-specific formatting (colors, etc.)
52147 exports.formatArgs.call(self, args);
52148
52149 var logFn = debug.log || exports.log || console.log.bind(console);
52150 logFn.apply(self, args);
52151 }
52152
52153 debug.namespace = namespace;
52154 debug.enabled = exports.enabled(namespace);
52155 debug.useColors = exports.useColors();
52156 debug.color = selectColor(namespace);
52157
52158 // env-specific initialization logic for debug instances
52159 if ('function' === typeof exports.init) {
52160 exports.init(debug);
52161 }
52162
52163 return debug;
52164}
52165
52166/**
52167 * Enables a debug mode by namespaces. This can include modes
52168 * separated by a colon and wildcards.
52169 *
52170 * @param {String} namespaces
52171 * @api public
52172 */
52173
52174function enable(namespaces) {
52175 exports.save(namespaces);
52176
52177 exports.names = [];
52178 exports.skips = [];
52179
52180 var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
52181 var len = split.length;
52182
52183 for (var i = 0; i < len; i++) {
52184 if (!split[i]) continue; // ignore empty strings
52185 namespaces = split[i].replace(/\*/g, '.*?');
52186 if (namespaces[0] === '-') {
52187 exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
52188 } else {
52189 exports.names.push(new RegExp('^' + namespaces + '$'));
52190 }
52191 }
52192}
52193
52194/**
52195 * Disable debug output.
52196 *
52197 * @api public
52198 */
52199
52200function disable() {
52201 exports.enable('');
52202}
52203
52204/**
52205 * Returns true if the given mode name is enabled, false otherwise.
52206 *
52207 * @param {String} name
52208 * @return {Boolean}
52209 * @api public
52210 */
52211
52212function enabled(name) {
52213 var i, len;
52214 for (i = 0, len = exports.skips.length; i < len; i++) {
52215 if (exports.skips[i].test(name)) {
52216 return false;
52217 }
52218 }
52219 for (i = 0, len = exports.names.length; i < len; i++) {
52220 if (exports.names[i].test(name)) {
52221 return true;
52222 }
52223 }
52224 return false;
52225}
52226
52227/**
52228 * Coerce `val`.
52229 *
52230 * @param {Mixed} val
52231 * @return {Mixed}
52232 * @api private
52233 */
52234
52235function coerce(val) {
52236 if (val instanceof Error) return val.stack || val.message;
52237 return val;
52238}
52239}(debug$7, debug$7.exports));
52240
52241/**
52242 * This is the web browser implementation of `debug()`.
52243 *
52244 * Expose `debug()` as the module.
52245 */
52246
52247(function (module, exports) {
52248exports = module.exports = debug$7.exports;
52249exports.log = log;
52250exports.formatArgs = formatArgs;
52251exports.save = save;
52252exports.load = load;
52253exports.useColors = useColors;
52254exports.storage = 'undefined' != typeof chrome
52255 && 'undefined' != typeof chrome.storage
52256 ? chrome.storage.local
52257 : localstorage();
52258
52259/**
52260 * Colors.
52261 */
52262
52263exports.colors = [
52264 'lightseagreen',
52265 'forestgreen',
52266 'goldenrod',
52267 'dodgerblue',
52268 'darkorchid',
52269 'crimson'
52270];
52271
52272/**
52273 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
52274 * and the Firebug extension (any Firefox version) are known
52275 * to support "%c" CSS customizations.
52276 *
52277 * TODO: add a `localStorage` variable to explicitly enable/disable colors
52278 */
52279
52280function useColors() {
52281 // NB: In an Electron preload script, document will be defined but not fully
52282 // initialized. Since we know we're in Chrome, we'll just detect this case
52283 // explicitly
52284 if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
52285 return true;
52286 }
52287
52288 // is webkit? http://stackoverflow.com/a/16459606/376773
52289 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
52290 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
52291 // is firebug? http://stackoverflow.com/a/398120/376773
52292 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
52293 // is firefox >= v31?
52294 // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
52295 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
52296 // double check webkit in userAgent just in case we are in a worker
52297 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
52298}
52299
52300/**
52301 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
52302 */
52303
52304exports.formatters.j = function(v) {
52305 try {
52306 return JSON.stringify(v);
52307 } catch (err) {
52308 return '[UnexpectedJSONParseError]: ' + err.message;
52309 }
52310};
52311
52312
52313/**
52314 * Colorize log arguments if enabled.
52315 *
52316 * @api public
52317 */
52318
52319function formatArgs(args) {
52320 var useColors = this.useColors;
52321
52322 args[0] = (useColors ? '%c' : '')
52323 + this.namespace
52324 + (useColors ? ' %c' : ' ')
52325 + args[0]
52326 + (useColors ? '%c ' : ' ')
52327 + '+' + exports.humanize(this.diff);
52328
52329 if (!useColors) return;
52330
52331 var c = 'color: ' + this.color;
52332 args.splice(1, 0, c, 'color: inherit');
52333
52334 // the final "%c" is somewhat tricky, because there could be other
52335 // arguments passed either before or after the %c, so we need to
52336 // figure out the correct index to insert the CSS into
52337 var index = 0;
52338 var lastC = 0;
52339 args[0].replace(/%[a-zA-Z%]/g, function(match) {
52340 if ('%%' === match) return;
52341 index++;
52342 if ('%c' === match) {
52343 // we only are interested in the *last* %c
52344 // (the user may have provided their own)
52345 lastC = index;
52346 }
52347 });
52348
52349 args.splice(lastC, 0, c);
52350}
52351
52352/**
52353 * Invokes `console.log()` when available.
52354 * No-op when `console.log` is not a "function".
52355 *
52356 * @api public
52357 */
52358
52359function log() {
52360 // this hackery is required for IE8/9, where
52361 // the `console.log` function doesn't have 'apply'
52362 return 'object' === typeof console
52363 && console.log
52364 && Function.prototype.apply.call(console.log, console, arguments);
52365}
52366
52367/**
52368 * Save `namespaces`.
52369 *
52370 * @param {String} namespaces
52371 * @api private
52372 */
52373
52374function save(namespaces) {
52375 try {
52376 if (null == namespaces) {
52377 exports.storage.removeItem('debug');
52378 } else {
52379 exports.storage.debug = namespaces;
52380 }
52381 } catch(e) {}
52382}
52383
52384/**
52385 * Load `namespaces`.
52386 *
52387 * @return {String} returns the previously persisted debug modes
52388 * @api private
52389 */
52390
52391function load() {
52392 var r;
52393 try {
52394 r = exports.storage.debug;
52395 } catch(e) {}
52396
52397 // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
52398 if (!r && typeof process !== 'undefined' && 'env' in process) {
52399 r = process.env.DEBUG;
52400 }
52401
52402 return r;
52403}
52404
52405/**
52406 * Enable namespaces listed in `localStorage.debug` initially.
52407 */
52408
52409exports.enable(load());
52410
52411/**
52412 * Localstorage attempts to return the localstorage.
52413 *
52414 * This is necessary because safari throws
52415 * when a user disables cookies/localstorage
52416 * and you attempt to access it.
52417 *
52418 * @return {LocalStorage}
52419 * @api private
52420 */
52421
52422function localstorage() {
52423 try {
52424 return window.localStorage;
52425 } catch (e) {}
52426}
52427}(browser$1, browser$1.exports));
52428
52429var node$1 = {exports: {}};
52430
52431/**
52432 * Module dependencies.
52433 */
52434
52435(function (module, exports) {
52436var tty = require$$0__default;
52437var util = require$$0__default$3;
52438
52439/**
52440 * This is the Node.js implementation of `debug()`.
52441 *
52442 * Expose `debug()` as the module.
52443 */
52444
52445exports = module.exports = debug$7.exports;
52446exports.init = init;
52447exports.log = log;
52448exports.formatArgs = formatArgs;
52449exports.save = save;
52450exports.load = load;
52451exports.useColors = useColors;
52452
52453/**
52454 * Colors.
52455 */
52456
52457exports.colors = [6, 2, 3, 4, 5, 1];
52458
52459/**
52460 * Build up the default `inspectOpts` object from the environment variables.
52461 *
52462 * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
52463 */
52464
52465exports.inspectOpts = Object.keys(process.env).filter(function (key) {
52466 return /^debug_/i.test(key);
52467}).reduce(function (obj, key) {
52468 // camel-case
52469 var prop = key
52470 .substring(6)
52471 .toLowerCase()
52472 .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() });
52473
52474 // coerce string value into JS value
52475 var val = process.env[key];
52476 if (/^(yes|on|true|enabled)$/i.test(val)) val = true;
52477 else if (/^(no|off|false|disabled)$/i.test(val)) val = false;
52478 else if (val === 'null') val = null;
52479 else val = Number(val);
52480
52481 obj[prop] = val;
52482 return obj;
52483}, {});
52484
52485/**
52486 * The file descriptor to write the `debug()` calls to.
52487 * Set the `DEBUG_FD` env variable to override with another value. i.e.:
52488 *
52489 * $ DEBUG_FD=3 node script.js 3>debug.log
52490 */
52491
52492var fd = parseInt(process.env.DEBUG_FD, 10) || 2;
52493
52494if (1 !== fd && 2 !== fd) {
52495 util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')();
52496}
52497
52498var stream = 1 === fd ? process.stdout :
52499 2 === fd ? process.stderr :
52500 createWritableStdioStream(fd);
52501
52502/**
52503 * Is stdout a TTY? Colored output is enabled when `true`.
52504 */
52505
52506function useColors() {
52507 return 'colors' in exports.inspectOpts
52508 ? Boolean(exports.inspectOpts.colors)
52509 : tty.isatty(fd);
52510}
52511
52512/**
52513 * Map %o to `util.inspect()`, all on a single line.
52514 */
52515
52516exports.formatters.o = function(v) {
52517 this.inspectOpts.colors = this.useColors;
52518 return util.inspect(v, this.inspectOpts)
52519 .split('\n').map(function(str) {
52520 return str.trim()
52521 }).join(' ');
52522};
52523
52524/**
52525 * Map %o to `util.inspect()`, allowing multiple lines if needed.
52526 */
52527
52528exports.formatters.O = function(v) {
52529 this.inspectOpts.colors = this.useColors;
52530 return util.inspect(v, this.inspectOpts);
52531};
52532
52533/**
52534 * Adds ANSI color escape codes if enabled.
52535 *
52536 * @api public
52537 */
52538
52539function formatArgs(args) {
52540 var name = this.namespace;
52541 var useColors = this.useColors;
52542
52543 if (useColors) {
52544 var c = this.color;
52545 var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m';
52546
52547 args[0] = prefix + args[0].split('\n').join('\n' + prefix);
52548 args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m');
52549 } else {
52550 args[0] = new Date().toUTCString()
52551 + ' ' + name + ' ' + args[0];
52552 }
52553}
52554
52555/**
52556 * Invokes `util.format()` with the specified arguments and writes to `stream`.
52557 */
52558
52559function log() {
52560 return stream.write(util.format.apply(util, arguments) + '\n');
52561}
52562
52563/**
52564 * Save `namespaces`.
52565 *
52566 * @param {String} namespaces
52567 * @api private
52568 */
52569
52570function save(namespaces) {
52571 if (null == namespaces) {
52572 // If you set a process.env field to null or undefined, it gets cast to the
52573 // string 'null' or 'undefined'. Just delete instead.
52574 delete process.env.DEBUG;
52575 } else {
52576 process.env.DEBUG = namespaces;
52577 }
52578}
52579
52580/**
52581 * Load `namespaces`.
52582 *
52583 * @return {String} returns the previously persisted debug modes
52584 * @api private
52585 */
52586
52587function load() {
52588 return process.env.DEBUG;
52589}
52590
52591/**
52592 * Copied from `node/src/node.js`.
52593 *
52594 * XXX: It's lame that node doesn't expose this API out-of-the-box. It also
52595 * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame.
52596 */
52597
52598function createWritableStdioStream (fd) {
52599 var stream;
52600 var tty_wrap = process.binding('tty_wrap');
52601
52602 // Note stream._type is used for test-module-load-list.js
52603
52604 switch (tty_wrap.guessHandleType(fd)) {
52605 case 'TTY':
52606 stream = new tty.WriteStream(fd);
52607 stream._type = 'tty';
52608
52609 // Hack to have stream not keep the event loop alive.
52610 // See https://github.com/joyent/node/issues/1726
52611 if (stream._handle && stream._handle.unref) {
52612 stream._handle.unref();
52613 }
52614 break;
52615
52616 case 'FILE':
52617 var fs = fs__default;
52618 stream = new fs.SyncWriteStream(fd, { autoClose: false });
52619 stream._type = 'fs';
52620 break;
52621
52622 case 'PIPE':
52623 case 'TCP':
52624 var net = require$$4__default$1;
52625 stream = new net.Socket({
52626 fd: fd,
52627 readable: false,
52628 writable: true
52629 });
52630
52631 // FIXME Should probably have an option in net.Socket to create a
52632 // stream from an existing fd which is writable only. But for now
52633 // we'll just add this hack and set the `readable` member to false.
52634 // Test: ./node test/fixtures/echo.js < /etc/passwd
52635 stream.readable = false;
52636 stream.read = null;
52637 stream._type = 'pipe';
52638
52639 // FIXME Hack to have stream not keep the event loop alive.
52640 // See https://github.com/joyent/node/issues/1726
52641 if (stream._handle && stream._handle.unref) {
52642 stream._handle.unref();
52643 }
52644 break;
52645
52646 default:
52647 // Probably an error on in uv_guess_handle()
52648 throw new Error('Implement me. Unknown stream file type!');
52649 }
52650
52651 // For supporting legacy API we put the FD here.
52652 stream.fd = fd;
52653
52654 stream._isStdio = true;
52655
52656 return stream;
52657}
52658
52659/**
52660 * Init logic for `debug` instances.
52661 *
52662 * Create a new `inspectOpts` object in case `useColors` is set
52663 * differently for a particular `debug` instance.
52664 */
52665
52666function init (debug) {
52667 debug.inspectOpts = {};
52668
52669 var keys = Object.keys(exports.inspectOpts);
52670 for (var i = 0; i < keys.length; i++) {
52671 debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
52672 }
52673}
52674
52675/**
52676 * Enable namespaces listed in `process.env.DEBUG` initially.
52677 */
52678
52679exports.enable(load());
52680}(node$1, node$1.exports));
52681
52682/**
52683 * Detect Electron renderer process, which is node, but we should
52684 * treat as a browser.
52685 */
52686
52687if (typeof process !== 'undefined' && process.type === 'renderer') {
52688 src$1.exports = browser$1.exports;
52689} else {
52690 src$1.exports = node$1.exports;
52691}
52692
52693/*!
52694 * encodeurl
52695 * Copyright(c) 2016 Douglas Christopher Wilson
52696 * MIT Licensed
52697 */
52698
52699/**
52700 * Module exports.
52701 * @public
52702 */
52703
52704var encodeurl = encodeUrl$1;
52705
52706/**
52707 * RegExp to match non-URL code points, *after* encoding (i.e. not including "%")
52708 * and including invalid escape sequences.
52709 * @private
52710 */
52711
52712var ENCODE_CHARS_REGEXP = /(?:[^\x21\x25\x26-\x3B\x3D\x3F-\x5B\x5D\x5F\x61-\x7A\x7E]|%(?:[^0-9A-Fa-f]|[0-9A-Fa-f][^0-9A-Fa-f]|$))+/g;
52713
52714/**
52715 * RegExp to match unmatched surrogate pair.
52716 * @private
52717 */
52718
52719var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g;
52720
52721/**
52722 * String to replace unmatched surrogate pair with.
52723 * @private
52724 */
52725
52726var UNMATCHED_SURROGATE_PAIR_REPLACE = '$1\uFFFD$2';
52727
52728/**
52729 * Encode a URL to a percent-encoded form, excluding already-encoded sequences.
52730 *
52731 * This function will take an already-encoded URL and encode all the non-URL
52732 * code points. This function will not encode the "%" character unless it is
52733 * not part of a valid sequence (`%20` will be left as-is, but `%foo` will
52734 * be encoded as `%25foo`).
52735 *
52736 * This encode is meant to be "safe" and does not throw errors. It will try as
52737 * hard as it can to properly encode the given URL, including replacing any raw,
52738 * unpaired surrogate pairs with the Unicode replacement character prior to
52739 * encoding.
52740 *
52741 * @param {string} url
52742 * @return {string}
52743 * @public
52744 */
52745
52746function encodeUrl$1 (url) {
52747 return String(url)
52748 .replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE)
52749 .replace(ENCODE_CHARS_REGEXP, encodeURI)
52750}
52751
52752/*!
52753 * escape-html
52754 * Copyright(c) 2012-2013 TJ Holowaychuk
52755 * Copyright(c) 2015 Andreas Lubbe
52756 * Copyright(c) 2015 Tiancheng "Timothy" Gu
52757 * MIT Licensed
52758 */
52759
52760/**
52761 * Module variables.
52762 * @private
52763 */
52764
52765var matchHtmlRegExp = /["'&<>]/;
52766
52767/**
52768 * Module exports.
52769 * @public
52770 */
52771
52772var escapeHtml_1 = escapeHtml$1;
52773
52774/**
52775 * Escape special characters in the given string of html.
52776 *
52777 * @param {string} string The string to escape for inserting into HTML
52778 * @return {string}
52779 * @public
52780 */
52781
52782function escapeHtml$1(string) {
52783 var str = '' + string;
52784 var match = matchHtmlRegExp.exec(str);
52785
52786 if (!match) {
52787 return str;
52788 }
52789
52790 var escape;
52791 var html = '';
52792 var index = 0;
52793 var lastIndex = 0;
52794
52795 for (index = match.index; index < str.length; index++) {
52796 switch (str.charCodeAt(index)) {
52797 case 34: // "
52798 escape = '&quot;';
52799 break;
52800 case 38: // &
52801 escape = '&amp;';
52802 break;
52803 case 39: // '
52804 escape = '&#39;';
52805 break;
52806 case 60: // <
52807 escape = '&lt;';
52808 break;
52809 case 62: // >
52810 escape = '&gt;';
52811 break;
52812 default:
52813 continue;
52814 }
52815
52816 if (lastIndex !== index) {
52817 html += str.substring(lastIndex, index);
52818 }
52819
52820 lastIndex = index + 1;
52821 html += escape;
52822 }
52823
52824 return lastIndex !== index
52825 ? html + str.substring(lastIndex, index)
52826 : html;
52827}
52828
52829var onFinished$2 = {exports: {}};
52830
52831/*!
52832 * ee-first
52833 * Copyright(c) 2014 Jonathan Ong
52834 * MIT Licensed
52835 */
52836
52837/**
52838 * Module exports.
52839 * @public
52840 */
52841
52842var eeFirst = first$1;
52843
52844/**
52845 * Get the first event in a set of event emitters and event pairs.
52846 *
52847 * @param {array} stuff
52848 * @param {function} done
52849 * @public
52850 */
52851
52852function first$1(stuff, done) {
52853 if (!Array.isArray(stuff))
52854 throw new TypeError('arg must be an array of [ee, events...] arrays')
52855
52856 var cleanups = [];
52857
52858 for (var i = 0; i < stuff.length; i++) {
52859 var arr = stuff[i];
52860
52861 if (!Array.isArray(arr) || arr.length < 2)
52862 throw new TypeError('each array member must be [ee, events...]')
52863
52864 var ee = arr[0];
52865
52866 for (var j = 1; j < arr.length; j++) {
52867 var event = arr[j];
52868 var fn = listener(event, callback);
52869
52870 // listen to the event
52871 ee.on(event, fn);
52872 // push this listener to the list of cleanups
52873 cleanups.push({
52874 ee: ee,
52875 event: event,
52876 fn: fn,
52877 });
52878 }
52879 }
52880
52881 function callback() {
52882 cleanup();
52883 done.apply(null, arguments);
52884 }
52885
52886 function cleanup() {
52887 var x;
52888 for (var i = 0; i < cleanups.length; i++) {
52889 x = cleanups[i];
52890 x.ee.removeListener(x.event, x.fn);
52891 }
52892 }
52893
52894 function thunk(fn) {
52895 done = fn;
52896 }
52897
52898 thunk.cancel = cleanup;
52899
52900 return thunk
52901}
52902
52903/**
52904 * Create the event listener.
52905 * @private
52906 */
52907
52908function listener(event, done) {
52909 return function onevent(arg1) {
52910 var args = new Array(arguments.length);
52911 var ee = this;
52912 var err = event === 'error'
52913 ? arg1
52914 : null;
52915
52916 // copy args to prevent arguments escaping scope
52917 for (var i = 0; i < args.length; i++) {
52918 args[i] = arguments[i];
52919 }
52920
52921 done(err, ee, event, args);
52922 }
52923}
52924
52925/*!
52926 * on-finished
52927 * Copyright(c) 2013 Jonathan Ong
52928 * Copyright(c) 2014 Douglas Christopher Wilson
52929 * MIT Licensed
52930 */
52931
52932/**
52933 * Module exports.
52934 * @public
52935 */
52936
52937onFinished$2.exports = onFinished$1;
52938onFinished$2.exports.isFinished = isFinished$1;
52939
52940/**
52941 * Module dependencies.
52942 * @private
52943 */
52944
52945var first = eeFirst;
52946
52947/**
52948 * Variables.
52949 * @private
52950 */
52951
52952/* istanbul ignore next */
52953var defer$2 = typeof setImmediate === 'function'
52954 ? setImmediate
52955 : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)); };
52956
52957/**
52958 * Invoke callback when the response has finished, useful for
52959 * cleaning up resources afterwards.
52960 *
52961 * @param {object} msg
52962 * @param {function} listener
52963 * @return {object}
52964 * @public
52965 */
52966
52967function onFinished$1(msg, listener) {
52968 if (isFinished$1(msg) !== false) {
52969 defer$2(listener, null, msg);
52970 return msg
52971 }
52972
52973 // attach the listener to the message
52974 attachListener(msg, listener);
52975
52976 return msg
52977}
52978
52979/**
52980 * Determine if message is already finished.
52981 *
52982 * @param {object} msg
52983 * @return {boolean}
52984 * @public
52985 */
52986
52987function isFinished$1(msg) {
52988 var socket = msg.socket;
52989
52990 if (typeof msg.finished === 'boolean') {
52991 // OutgoingMessage
52992 return Boolean(msg.finished || (socket && !socket.writable))
52993 }
52994
52995 if (typeof msg.complete === 'boolean') {
52996 // IncomingMessage
52997 return Boolean(msg.upgrade || !socket || !socket.readable || (msg.complete && !msg.readable))
52998 }
52999
53000 // don't know
53001 return undefined
53002}
53003
53004/**
53005 * Attach a finished listener to the message.
53006 *
53007 * @param {object} msg
53008 * @param {function} callback
53009 * @private
53010 */
53011
53012function attachFinishedListener(msg, callback) {
53013 var eeMsg;
53014 var eeSocket;
53015 var finished = false;
53016
53017 function onFinish(error) {
53018 eeMsg.cancel();
53019 eeSocket.cancel();
53020
53021 finished = true;
53022 callback(error);
53023 }
53024
53025 // finished on first message event
53026 eeMsg = eeSocket = first([[msg, 'end', 'finish']], onFinish);
53027
53028 function onSocket(socket) {
53029 // remove listener
53030 msg.removeListener('socket', onSocket);
53031
53032 if (finished) return
53033 if (eeMsg !== eeSocket) return
53034
53035 // finished on first socket event
53036 eeSocket = first([[socket, 'error', 'close']], onFinish);
53037 }
53038
53039 if (msg.socket) {
53040 // socket already assigned
53041 onSocket(msg.socket);
53042 return
53043 }
53044
53045 // wait for socket to be assigned
53046 msg.on('socket', onSocket);
53047
53048 if (msg.socket === undefined) {
53049 // node.js 0.8 patch
53050 patchAssignSocket(msg, onSocket);
53051 }
53052}
53053
53054/**
53055 * Attach the listener to the message.
53056 *
53057 * @param {object} msg
53058 * @return {function}
53059 * @private
53060 */
53061
53062function attachListener(msg, listener) {
53063 var attached = msg.__onFinished;
53064
53065 // create a private single listener with queue
53066 if (!attached || !attached.queue) {
53067 attached = msg.__onFinished = createListener(msg);
53068 attachFinishedListener(msg, attached);
53069 }
53070
53071 attached.queue.push(listener);
53072}
53073
53074/**
53075 * Create listener on message.
53076 *
53077 * @param {object} msg
53078 * @return {function}
53079 * @private
53080 */
53081
53082function createListener(msg) {
53083 function listener(err) {
53084 if (msg.__onFinished === listener) msg.__onFinished = null;
53085 if (!listener.queue) return
53086
53087 var queue = listener.queue;
53088 listener.queue = null;
53089
53090 for (var i = 0; i < queue.length; i++) {
53091 queue[i](err, msg);
53092 }
53093 }
53094
53095 listener.queue = [];
53096
53097 return listener
53098}
53099
53100/**
53101 * Patch ServerResponse.prototype.assignSocket for node.js 0.8.
53102 *
53103 * @param {ServerResponse} res
53104 * @param {function} callback
53105 * @private
53106 */
53107
53108function patchAssignSocket(res, callback) {
53109 var assignSocket = res.assignSocket;
53110
53111 if (typeof assignSocket !== 'function') return
53112
53113 // res.on('socket', callback) is broken in 0.8
53114 res.assignSocket = function _assignSocket(socket) {
53115 assignSocket.call(this, socket);
53116 callback(socket);
53117 };
53118}
53119
53120var parseurl$1 = {exports: {}};
53121
53122/*!
53123 * parseurl
53124 * Copyright(c) 2014 Jonathan Ong
53125 * Copyright(c) 2014-2017 Douglas Christopher Wilson
53126 * MIT Licensed
53127 */
53128
53129/**
53130 * Module dependencies.
53131 * @private
53132 */
53133
53134var url$3 = require$$0__default$7;
53135var parse$a = url$3.parse;
53136var Url = url$3.Url;
53137
53138/**
53139 * Module exports.
53140 * @public
53141 */
53142
53143parseurl$1.exports = parseurl;
53144parseurl$1.exports.original = originalurl;
53145
53146/**
53147 * Parse the `req` url with memoization.
53148 *
53149 * @param {ServerRequest} req
53150 * @return {Object}
53151 * @public
53152 */
53153
53154function parseurl (req) {
53155 var url = req.url;
53156
53157 if (url === undefined) {
53158 // URL is undefined
53159 return undefined
53160 }
53161
53162 var parsed = req._parsedUrl;
53163
53164 if (fresh(url, parsed)) {
53165 // Return cached URL parse
53166 return parsed
53167 }
53168
53169 // Parse the URL
53170 parsed = fastparse(url);
53171 parsed._raw = url;
53172
53173 return (req._parsedUrl = parsed)
53174}
53175/**
53176 * Parse the `req` original url with fallback and memoization.
53177 *
53178 * @param {ServerRequest} req
53179 * @return {Object}
53180 * @public
53181 */
53182
53183function originalurl (req) {
53184 var url = req.originalUrl;
53185
53186 if (typeof url !== 'string') {
53187 // Fallback
53188 return parseurl(req)
53189 }
53190
53191 var parsed = req._parsedOriginalUrl;
53192
53193 if (fresh(url, parsed)) {
53194 // Return cached URL parse
53195 return parsed
53196 }
53197
53198 // Parse the URL
53199 parsed = fastparse(url);
53200 parsed._raw = url;
53201
53202 return (req._parsedOriginalUrl = parsed)
53203}
53204/**
53205 * Parse the `str` url with fast-path short-cut.
53206 *
53207 * @param {string} str
53208 * @return {Object}
53209 * @private
53210 */
53211
53212function fastparse (str) {
53213 if (typeof str !== 'string' || str.charCodeAt(0) !== 0x2f /* / */) {
53214 return parse$a(str)
53215 }
53216
53217 var pathname = str;
53218 var query = null;
53219 var search = null;
53220
53221 // This takes the regexp from https://github.com/joyent/node/pull/7878
53222 // Which is /^(\/[^?#\s]*)(\?[^#\s]*)?$/
53223 // And unrolls it into a for loop
53224 for (var i = 1; i < str.length; i++) {
53225 switch (str.charCodeAt(i)) {
53226 case 0x3f: /* ? */
53227 if (search === null) {
53228 pathname = str.substring(0, i);
53229 query = str.substring(i + 1);
53230 search = str.substring(i);
53231 }
53232 break
53233 case 0x09: /* \t */
53234 case 0x0a: /* \n */
53235 case 0x0c: /* \f */
53236 case 0x0d: /* \r */
53237 case 0x20: /* */
53238 case 0x23: /* # */
53239 case 0xa0:
53240 case 0xfeff:
53241 return parse$a(str)
53242 }
53243 }
53244
53245 var url = Url !== undefined
53246 ? new Url()
53247 : {};
53248
53249 url.path = str;
53250 url.href = str;
53251 url.pathname = pathname;
53252
53253 if (search !== null) {
53254 url.query = query;
53255 url.search = search;
53256 }
53257
53258 return url
53259}
53260
53261/**
53262 * Determine if parsed is still fresh for url.
53263 *
53264 * @param {string} url
53265 * @param {object} parsedUrl
53266 * @return {boolean}
53267 * @private
53268 */
53269
53270function fresh (url, parsedUrl) {
53271 return typeof parsedUrl === 'object' &&
53272 parsedUrl !== null &&
53273 (Url === undefined || parsedUrl instanceof Url) &&
53274 parsedUrl._raw === url
53275}
53276
53277var require$$0$2 = {
53278 "100": "Continue",
53279 "101": "Switching Protocols",
53280 "102": "Processing",
53281 "103": "Early Hints",
53282 "200": "OK",
53283 "201": "Created",
53284 "202": "Accepted",
53285 "203": "Non-Authoritative Information",
53286 "204": "No Content",
53287 "205": "Reset Content",
53288 "206": "Partial Content",
53289 "207": "Multi-Status",
53290 "208": "Already Reported",
53291 "226": "IM Used",
53292 "300": "Multiple Choices",
53293 "301": "Moved Permanently",
53294 "302": "Found",
53295 "303": "See Other",
53296 "304": "Not Modified",
53297 "305": "Use Proxy",
53298 "306": "(Unused)",
53299 "307": "Temporary Redirect",
53300 "308": "Permanent Redirect",
53301 "400": "Bad Request",
53302 "401": "Unauthorized",
53303 "402": "Payment Required",
53304 "403": "Forbidden",
53305 "404": "Not Found",
53306 "405": "Method Not Allowed",
53307 "406": "Not Acceptable",
53308 "407": "Proxy Authentication Required",
53309 "408": "Request Timeout",
53310 "409": "Conflict",
53311 "410": "Gone",
53312 "411": "Length Required",
53313 "412": "Precondition Failed",
53314 "413": "Payload Too Large",
53315 "414": "URI Too Long",
53316 "415": "Unsupported Media Type",
53317 "416": "Range Not Satisfiable",
53318 "417": "Expectation Failed",
53319 "418": "I'm a teapot",
53320 "421": "Misdirected Request",
53321 "422": "Unprocessable Entity",
53322 "423": "Locked",
53323 "424": "Failed Dependency",
53324 "425": "Unordered Collection",
53325 "426": "Upgrade Required",
53326 "428": "Precondition Required",
53327 "429": "Too Many Requests",
53328 "431": "Request Header Fields Too Large",
53329 "451": "Unavailable For Legal Reasons",
53330 "500": "Internal Server Error",
53331 "501": "Not Implemented",
53332 "502": "Bad Gateway",
53333 "503": "Service Unavailable",
53334 "504": "Gateway Timeout",
53335 "505": "HTTP Version Not Supported",
53336 "506": "Variant Also Negotiates",
53337 "507": "Insufficient Storage",
53338 "508": "Loop Detected",
53339 "509": "Bandwidth Limit Exceeded",
53340 "510": "Not Extended",
53341 "511": "Network Authentication Required"
53342};
53343
53344/*!
53345 * statuses
53346 * Copyright(c) 2014 Jonathan Ong
53347 * Copyright(c) 2016 Douglas Christopher Wilson
53348 * MIT Licensed
53349 */
53350
53351/**
53352 * Module dependencies.
53353 * @private
53354 */
53355
53356var codes = require$$0$2;
53357
53358/**
53359 * Module exports.
53360 * @public
53361 */
53362
53363var statuses$1 = status;
53364
53365// status code to message map
53366status.STATUS_CODES = codes;
53367
53368// array of status codes
53369status.codes = populateStatusesMap(status, codes);
53370
53371// status codes for redirects
53372status.redirect = {
53373 300: true,
53374 301: true,
53375 302: true,
53376 303: true,
53377 305: true,
53378 307: true,
53379 308: true
53380};
53381
53382// status codes for empty bodies
53383status.empty = {
53384 204: true,
53385 205: true,
53386 304: true
53387};
53388
53389// status codes for when you should retry the request
53390status.retry = {
53391 502: true,
53392 503: true,
53393 504: true
53394};
53395
53396/**
53397 * Populate the statuses map for given codes.
53398 * @private
53399 */
53400
53401function populateStatusesMap (statuses, codes) {
53402 var arr = [];
53403
53404 Object.keys(codes).forEach(function forEachCode (code) {
53405 var message = codes[code];
53406 var status = Number(code);
53407
53408 // Populate properties
53409 statuses[status] = message;
53410 statuses[message] = status;
53411 statuses[message.toLowerCase()] = status;
53412
53413 // Add to array
53414 arr.push(status);
53415 });
53416
53417 return arr
53418}
53419
53420/**
53421 * Get the status code.
53422 *
53423 * Given a number, this will throw if it is not a known status
53424 * code, otherwise the code will be returned. Given a string,
53425 * the string will be parsed for a number and return the code
53426 * if valid, otherwise will lookup the code assuming this is
53427 * the status message.
53428 *
53429 * @param {string|number} code
53430 * @returns {number}
53431 * @public
53432 */
53433
53434function status (code) {
53435 if (typeof code === 'number') {
53436 if (!status[code]) throw new Error('invalid status code: ' + code)
53437 return code
53438 }
53439
53440 if (typeof code !== 'string') {
53441 throw new TypeError('code must be a number or string')
53442 }
53443
53444 // '403'
53445 var n = parseInt(code, 10);
53446 if (!isNaN(n)) {
53447 if (!status[n]) throw new Error('invalid status code: ' + n)
53448 return n
53449 }
53450
53451 n = status[code.toLowerCase()];
53452 if (!n) throw new Error('invalid status message: "' + code + '"')
53453 return n
53454}
53455
53456/*!
53457 * unpipe
53458 * Copyright(c) 2015 Douglas Christopher Wilson
53459 * MIT Licensed
53460 */
53461
53462/**
53463 * Module exports.
53464 * @public
53465 */
53466
53467var unpipe_1 = unpipe$1;
53468
53469/**
53470 * Determine if there are Node.js pipe-like data listeners.
53471 * @private
53472 */
53473
53474function hasPipeDataListeners(stream) {
53475 var listeners = stream.listeners('data');
53476
53477 for (var i = 0; i < listeners.length; i++) {
53478 if (listeners[i].name === 'ondata') {
53479 return true
53480 }
53481 }
53482
53483 return false
53484}
53485
53486/**
53487 * Unpipe a stream from all destinations.
53488 *
53489 * @param {object} stream
53490 * @public
53491 */
53492
53493function unpipe$1(stream) {
53494 if (!stream) {
53495 throw new TypeError('argument stream is required')
53496 }
53497
53498 if (typeof stream.unpipe === 'function') {
53499 // new-style
53500 stream.unpipe();
53501 return
53502 }
53503
53504 // Node.js 0.8 hack
53505 if (!hasPipeDataListeners(stream)) {
53506 return
53507 }
53508
53509 var listener;
53510 var listeners = stream.listeners('close');
53511
53512 for (var i = 0; i < listeners.length; i++) {
53513 listener = listeners[i];
53514
53515 if (listener.name !== 'cleanup' && listener.name !== 'onclose') {
53516 continue
53517 }
53518
53519 // invoke the listener
53520 listener.call(stream);
53521 }
53522}
53523
53524/*!
53525 * finalhandler
53526 * Copyright(c) 2014-2017 Douglas Christopher Wilson
53527 * MIT Licensed
53528 */
53529
53530/**
53531 * Module dependencies.
53532 * @private
53533 */
53534
53535var debug$6 = src$1.exports('finalhandler');
53536var encodeUrl = encodeurl;
53537var escapeHtml = escapeHtml_1;
53538var onFinished = onFinished$2.exports;
53539var parseUrl$1 = parseurl$1.exports;
53540var statuses = statuses$1;
53541var unpipe = unpipe_1;
53542
53543/**
53544 * Module variables.
53545 * @private
53546 */
53547
53548var DOUBLE_SPACE_REGEXP = /\x20{2}/g;
53549var NEWLINE_REGEXP = /\n/g;
53550
53551/* istanbul ignore next */
53552var defer$1 = typeof setImmediate === 'function'
53553 ? setImmediate
53554 : function (fn) { process.nextTick(fn.bind.apply(fn, arguments)); };
53555var isFinished = onFinished.isFinished;
53556
53557/**
53558 * Create a minimal HTML document.
53559 *
53560 * @param {string} message
53561 * @private
53562 */
53563
53564function createHtmlDocument (message) {
53565 var body = escapeHtml(message)
53566 .replace(NEWLINE_REGEXP, '<br>')
53567 .replace(DOUBLE_SPACE_REGEXP, ' &nbsp;');
53568
53569 return '<!DOCTYPE html>\n' +
53570 '<html lang="en">\n' +
53571 '<head>\n' +
53572 '<meta charset="utf-8">\n' +
53573 '<title>Error</title>\n' +
53574 '</head>\n' +
53575 '<body>\n' +
53576 '<pre>' + body + '</pre>\n' +
53577 '</body>\n' +
53578 '</html>\n'
53579}
53580
53581/**
53582 * Module exports.
53583 * @public
53584 */
53585
53586var finalhandler_1 = finalhandler$1;
53587
53588/**
53589 * Create a function to handle the final response.
53590 *
53591 * @param {Request} req
53592 * @param {Response} res
53593 * @param {Object} [options]
53594 * @return {Function}
53595 * @public
53596 */
53597
53598function finalhandler$1 (req, res, options) {
53599 var opts = options || {};
53600
53601 // get environment
53602 var env = opts.env || process.env.NODE_ENV || 'development';
53603
53604 // get error callback
53605 var onerror = opts.onerror;
53606
53607 return function (err) {
53608 var headers;
53609 var msg;
53610 var status;
53611
53612 // ignore 404 on in-flight response
53613 if (!err && headersSent(res)) {
53614 debug$6('cannot 404 after headers sent');
53615 return
53616 }
53617
53618 // unhandled error
53619 if (err) {
53620 // respect status code from error
53621 status = getErrorStatusCode(err);
53622
53623 if (status === undefined) {
53624 // fallback to status code on response
53625 status = getResponseStatusCode(res);
53626 } else {
53627 // respect headers from error
53628 headers = getErrorHeaders(err);
53629 }
53630
53631 // get error message
53632 msg = getErrorMessage(err, status, env);
53633 } else {
53634 // not found
53635 status = 404;
53636 msg = 'Cannot ' + req.method + ' ' + encodeUrl(getResourceName(req));
53637 }
53638
53639 debug$6('default %s', status);
53640
53641 // schedule onerror callback
53642 if (err && onerror) {
53643 defer$1(onerror, err, req, res);
53644 }
53645
53646 // cannot actually respond
53647 if (headersSent(res)) {
53648 debug$6('cannot %d after headers sent', status);
53649 req.socket.destroy();
53650 return
53651 }
53652
53653 // send response
53654 send$2(req, res, status, headers, msg);
53655 }
53656}
53657
53658/**
53659 * Get headers from Error object.
53660 *
53661 * @param {Error} err
53662 * @return {object}
53663 * @private
53664 */
53665
53666function getErrorHeaders (err) {
53667 if (!err.headers || typeof err.headers !== 'object') {
53668 return undefined
53669 }
53670
53671 var headers = Object.create(null);
53672 var keys = Object.keys(err.headers);
53673
53674 for (var i = 0; i < keys.length; i++) {
53675 var key = keys[i];
53676 headers[key] = err.headers[key];
53677 }
53678
53679 return headers
53680}
53681
53682/**
53683 * Get message from Error object, fallback to status message.
53684 *
53685 * @param {Error} err
53686 * @param {number} status
53687 * @param {string} env
53688 * @return {string}
53689 * @private
53690 */
53691
53692function getErrorMessage (err, status, env) {
53693 var msg;
53694
53695 if (env !== 'production') {
53696 // use err.stack, which typically includes err.message
53697 msg = err.stack;
53698
53699 // fallback to err.toString() when possible
53700 if (!msg && typeof err.toString === 'function') {
53701 msg = err.toString();
53702 }
53703 }
53704
53705 return msg || statuses[status]
53706}
53707
53708/**
53709 * Get status code from Error object.
53710 *
53711 * @param {Error} err
53712 * @return {number}
53713 * @private
53714 */
53715
53716function getErrorStatusCode (err) {
53717 // check err.status
53718 if (typeof err.status === 'number' && err.status >= 400 && err.status < 600) {
53719 return err.status
53720 }
53721
53722 // check err.statusCode
53723 if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) {
53724 return err.statusCode
53725 }
53726
53727 return undefined
53728}
53729
53730/**
53731 * Get resource name for the request.
53732 *
53733 * This is typically just the original pathname of the request
53734 * but will fallback to "resource" is that cannot be determined.
53735 *
53736 * @param {IncomingMessage} req
53737 * @return {string}
53738 * @private
53739 */
53740
53741function getResourceName (req) {
53742 try {
53743 return parseUrl$1.original(req).pathname
53744 } catch (e) {
53745 return 'resource'
53746 }
53747}
53748
53749/**
53750 * Get status code from response.
53751 *
53752 * @param {OutgoingMessage} res
53753 * @return {number}
53754 * @private
53755 */
53756
53757function getResponseStatusCode (res) {
53758 var status = res.statusCode;
53759
53760 // default status code to 500 if outside valid range
53761 if (typeof status !== 'number' || status < 400 || status > 599) {
53762 status = 500;
53763 }
53764
53765 return status
53766}
53767
53768/**
53769 * Determine if the response headers have been sent.
53770 *
53771 * @param {object} res
53772 * @returns {boolean}
53773 * @private
53774 */
53775
53776function headersSent (res) {
53777 return typeof res.headersSent !== 'boolean'
53778 ? Boolean(res._header)
53779 : res.headersSent
53780}
53781
53782/**
53783 * Send response.
53784 *
53785 * @param {IncomingMessage} req
53786 * @param {OutgoingMessage} res
53787 * @param {number} status
53788 * @param {object} headers
53789 * @param {string} message
53790 * @private
53791 */
53792
53793function send$2 (req, res, status, headers, message) {
53794 function write () {
53795 // response body
53796 var body = createHtmlDocument(message);
53797
53798 // response status
53799 res.statusCode = status;
53800 res.statusMessage = statuses[status];
53801
53802 // response headers
53803 setHeaders(res, headers);
53804
53805 // security headers
53806 res.setHeader('Content-Security-Policy', "default-src 'none'");
53807 res.setHeader('X-Content-Type-Options', 'nosniff');
53808
53809 // standard headers
53810 res.setHeader('Content-Type', 'text/html; charset=utf-8');
53811 res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8'));
53812
53813 if (req.method === 'HEAD') {
53814 res.end();
53815 return
53816 }
53817
53818 res.end(body, 'utf8');
53819 }
53820
53821 if (isFinished(req)) {
53822 write();
53823 return
53824 }
53825
53826 // unpipe everything from the request
53827 unpipe(req);
53828
53829 // flush the request
53830 onFinished(req, write);
53831 req.resume();
53832}
53833
53834/**
53835 * Set response headers from an object.
53836 *
53837 * @param {OutgoingMessage} res
53838 * @param {object} headers
53839 * @private
53840 */
53841
53842function setHeaders (res, headers) {
53843 if (!headers) {
53844 return
53845 }
53846
53847 var keys = Object.keys(headers);
53848 for (var i = 0; i < keys.length; i++) {
53849 var key = keys[i];
53850 res.setHeader(key, headers[key]);
53851 }
53852}
53853
53854var utilsMerge = {exports: {}};
53855
53856/**
53857 * Merge object b with object a.
53858 *
53859 * var a = { foo: 'bar' }
53860 * , b = { bar: 'baz' };
53861 *
53862 * merge(a, b);
53863 * // => { foo: 'bar', bar: 'baz' }
53864 *
53865 * @param {Object} a
53866 * @param {Object} b
53867 * @return {Object}
53868 * @api public
53869 */
53870
53871(function (module, exports) {
53872module.exports = function(a, b){
53873 if (a && b) {
53874 for (var key in b) {
53875 a[key] = b[key];
53876 }
53877 }
53878 return a;
53879};
53880}(utilsMerge));
53881
53882/*!
53883 * connect
53884 * Copyright(c) 2010 Sencha Inc.
53885 * Copyright(c) 2011 TJ Holowaychuk
53886 * Copyright(c) 2015 Douglas Christopher Wilson
53887 * MIT Licensed
53888 */
53889
53890/**
53891 * Module dependencies.
53892 * @private
53893 */
53894
53895var debug$5 = src$2.exports('connect:dispatcher');
53896var EventEmitter$3 = require$$0__default$6.EventEmitter;
53897var finalhandler = finalhandler_1;
53898var http$3 = require$$0__default$8;
53899var merge = utilsMerge.exports;
53900var parseUrl = parseurl$1.exports;
53901
53902/**
53903 * Module exports.
53904 * @public
53905 */
53906
53907var connect = createServer$2;
53908
53909/**
53910 * Module variables.
53911 * @private
53912 */
53913
53914var env$1 = process.env.NODE_ENV || 'development';
53915var proto = {};
53916
53917/* istanbul ignore next */
53918var defer = typeof setImmediate === 'function'
53919 ? setImmediate
53920 : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)); };
53921
53922/**
53923 * Create a new connect server.
53924 *
53925 * @return {function}
53926 * @public
53927 */
53928
53929function createServer$2() {
53930 function app(req, res, next){ app.handle(req, res, next); }
53931 merge(app, proto);
53932 merge(app, EventEmitter$3.prototype);
53933 app.route = '/';
53934 app.stack = [];
53935 return app;
53936}
53937
53938/**
53939 * Utilize the given middleware `handle` to the given `route`,
53940 * defaulting to _/_. This "route" is the mount-point for the
53941 * middleware, when given a value other than _/_ the middleware
53942 * is only effective when that segment is present in the request's
53943 * pathname.
53944 *
53945 * For example if we were to mount a function at _/admin_, it would
53946 * be invoked on _/admin_, and _/admin/settings_, however it would
53947 * not be invoked for _/_, or _/posts_.
53948 *
53949 * @param {String|Function|Server} route, callback or server
53950 * @param {Function|Server} callback or server
53951 * @return {Server} for chaining
53952 * @public
53953 */
53954
53955proto.use = function use(route, fn) {
53956 var handle = fn;
53957 var path = route;
53958
53959 // default route to '/'
53960 if (typeof route !== 'string') {
53961 handle = route;
53962 path = '/';
53963 }
53964
53965 // wrap sub-apps
53966 if (typeof handle.handle === 'function') {
53967 var server = handle;
53968 server.route = path;
53969 handle = function (req, res, next) {
53970 server.handle(req, res, next);
53971 };
53972 }
53973
53974 // wrap vanilla http.Servers
53975 if (handle instanceof http$3.Server) {
53976 handle = handle.listeners('request')[0];
53977 }
53978
53979 // strip trailing slash
53980 if (path[path.length - 1] === '/') {
53981 path = path.slice(0, -1);
53982 }
53983
53984 // add the middleware
53985 debug$5('use %s %s', path || '/', handle.name || 'anonymous');
53986 this.stack.push({ route: path, handle: handle });
53987
53988 return this;
53989};
53990
53991/**
53992 * Handle server requests, punting them down
53993 * the middleware stack.
53994 *
53995 * @private
53996 */
53997
53998proto.handle = function handle(req, res, out) {
53999 var index = 0;
54000 var protohost = getProtohost(req.url) || '';
54001 var removed = '';
54002 var slashAdded = false;
54003 var stack = this.stack;
54004
54005 // final function handler
54006 var done = out || finalhandler(req, res, {
54007 env: env$1,
54008 onerror: logerror
54009 });
54010
54011 // store the original URL
54012 req.originalUrl = req.originalUrl || req.url;
54013
54014 function next(err) {
54015 if (slashAdded) {
54016 req.url = req.url.substr(1);
54017 slashAdded = false;
54018 }
54019
54020 if (removed.length !== 0) {
54021 req.url = protohost + removed + req.url.substr(protohost.length);
54022 removed = '';
54023 }
54024
54025 // next callback
54026 var layer = stack[index++];
54027
54028 // all done
54029 if (!layer) {
54030 defer(done, err);
54031 return;
54032 }
54033
54034 // route data
54035 var path = parseUrl(req).pathname || '/';
54036 var route = layer.route;
54037
54038 // skip this layer if the route doesn't match
54039 if (path.toLowerCase().substr(0, route.length) !== route.toLowerCase()) {
54040 return next(err);
54041 }
54042
54043 // skip if route match does not border "/", ".", or end
54044 var c = path.length > route.length && path[route.length];
54045 if (c && c !== '/' && c !== '.') {
54046 return next(err);
54047 }
54048
54049 // trim off the part of the url that matches the route
54050 if (route.length !== 0 && route !== '/') {
54051 removed = route;
54052 req.url = protohost + req.url.substr(protohost.length + removed.length);
54053
54054 // ensure leading slash
54055 if (!protohost && req.url[0] !== '/') {
54056 req.url = '/' + req.url;
54057 slashAdded = true;
54058 }
54059 }
54060
54061 // call the layer handle
54062 call(layer.handle, route, err, req, res, next);
54063 }
54064
54065 next();
54066};
54067
54068/**
54069 * Listen for connections.
54070 *
54071 * This method takes the same arguments
54072 * as node's `http.Server#listen()`.
54073 *
54074 * HTTP and HTTPS:
54075 *
54076 * If you run your application both as HTTP
54077 * and HTTPS you may wrap them individually,
54078 * since your Connect "server" is really just
54079 * a JavaScript `Function`.
54080 *
54081 * var connect = require('connect')
54082 * , http = require('http')
54083 * , https = require('https');
54084 *
54085 * var app = connect();
54086 *
54087 * http.createServer(app).listen(80);
54088 * https.createServer(options, app).listen(443);
54089 *
54090 * @return {http.Server}
54091 * @api public
54092 */
54093
54094proto.listen = function listen() {
54095 var server = http$3.createServer(this);
54096 return server.listen.apply(server, arguments);
54097};
54098
54099/**
54100 * Invoke a route handle.
54101 * @private
54102 */
54103
54104function call(handle, route, err, req, res, next) {
54105 var arity = handle.length;
54106 var error = err;
54107 var hasError = Boolean(err);
54108
54109 debug$5('%s %s : %s', handle.name || '<anonymous>', route, req.originalUrl);
54110
54111 try {
54112 if (hasError && arity === 4) {
54113 // error-handling middleware
54114 handle(err, req, res, next);
54115 return;
54116 } else if (!hasError && arity < 4) {
54117 // request-handling middleware
54118 handle(req, res, next);
54119 return;
54120 }
54121 } catch (e) {
54122 // replace the error
54123 error = e;
54124 }
54125
54126 // continue
54127 next(error);
54128}
54129
54130/**
54131 * Log error using console.error.
54132 *
54133 * @param {Error} err
54134 * @private
54135 */
54136
54137function logerror(err) {
54138 if (env$1 !== 'test') console.error(err.stack || err.toString());
54139}
54140
54141/**
54142 * Get get protocol + host for a URL.
54143 *
54144 * @param {string} url
54145 * @private
54146 */
54147
54148function getProtohost(url) {
54149 if (url.length === 0 || url[0] === '/') {
54150 return undefined;
54151 }
54152
54153 var fqdnIndex = url.indexOf('://');
54154
54155 return fqdnIndex !== -1 && url.lastIndexOf('?', fqdnIndex) === -1
54156 ? url.substr(0, url.indexOf('/', 3 + fqdnIndex))
54157 : undefined;
54158}
54159
54160var lib$1 = {exports: {}};
54161
54162/*
54163object-assign
54164(c) Sindre Sorhus
54165@license MIT
54166*/
54167/* eslint-disable no-unused-vars */
54168var getOwnPropertySymbols = Object.getOwnPropertySymbols;
54169var hasOwnProperty = Object.prototype.hasOwnProperty;
54170var propIsEnumerable = Object.prototype.propertyIsEnumerable;
54171
54172function toObject(val) {
54173 if (val === null || val === undefined) {
54174 throw new TypeError('Object.assign cannot be called with null or undefined');
54175 }
54176
54177 return Object(val);
54178}
54179
54180function shouldUseNative() {
54181 try {
54182 if (!Object.assign) {
54183 return false;
54184 }
54185
54186 // Detect buggy property enumeration order in older V8 versions.
54187
54188 // https://bugs.chromium.org/p/v8/issues/detail?id=4118
54189 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
54190 test1[5] = 'de';
54191 if (Object.getOwnPropertyNames(test1)[0] === '5') {
54192 return false;
54193 }
54194
54195 // https://bugs.chromium.org/p/v8/issues/detail?id=3056
54196 var test2 = {};
54197 for (var i = 0; i < 10; i++) {
54198 test2['_' + String.fromCharCode(i)] = i;
54199 }
54200 var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
54201 return test2[n];
54202 });
54203 if (order2.join('') !== '0123456789') {
54204 return false;
54205 }
54206
54207 // https://bugs.chromium.org/p/v8/issues/detail?id=3056
54208 var test3 = {};
54209 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
54210 test3[letter] = letter;
54211 });
54212 if (Object.keys(Object.assign({}, test3)).join('') !==
54213 'abcdefghijklmnopqrst') {
54214 return false;
54215 }
54216
54217 return true;
54218 } catch (err) {
54219 // We don't expect any of the above to throw, but better to be safe.
54220 return false;
54221 }
54222}
54223
54224var objectAssign = shouldUseNative() ? Object.assign : function (target, source) {
54225 var from;
54226 var to = toObject(target);
54227 var symbols;
54228
54229 for (var s = 1; s < arguments.length; s++) {
54230 from = Object(arguments[s]);
54231
54232 for (var key in from) {
54233 if (hasOwnProperty.call(from, key)) {
54234 to[key] = from[key];
54235 }
54236 }
54237
54238 if (getOwnPropertySymbols) {
54239 symbols = getOwnPropertySymbols(from);
54240 for (var i = 0; i < symbols.length; i++) {
54241 if (propIsEnumerable.call(from, symbols[i])) {
54242 to[symbols[i]] = from[symbols[i]];
54243 }
54244 }
54245 }
54246 }
54247
54248 return to;
54249};
54250
54251var vary$1 = {exports: {}};
54252
54253/*!
54254 * vary
54255 * Copyright(c) 2014-2017 Douglas Christopher Wilson
54256 * MIT Licensed
54257 */
54258
54259/**
54260 * Module exports.
54261 */
54262
54263vary$1.exports = vary;
54264vary$1.exports.append = append;
54265
54266/**
54267 * RegExp to match field-name in RFC 7230 sec 3.2
54268 *
54269 * field-name = token
54270 * token = 1*tchar
54271 * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
54272 * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
54273 * / DIGIT / ALPHA
54274 * ; any VCHAR, except delimiters
54275 */
54276
54277var FIELD_NAME_REGEXP = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
54278
54279/**
54280 * Append a field to a vary header.
54281 *
54282 * @param {String} header
54283 * @param {String|Array} field
54284 * @return {String}
54285 * @public
54286 */
54287
54288function append (header, field) {
54289 if (typeof header !== 'string') {
54290 throw new TypeError('header argument is required')
54291 }
54292
54293 if (!field) {
54294 throw new TypeError('field argument is required')
54295 }
54296
54297 // get fields array
54298 var fields = !Array.isArray(field)
54299 ? parse$9(String(field))
54300 : field;
54301
54302 // assert on invalid field names
54303 for (var j = 0; j < fields.length; j++) {
54304 if (!FIELD_NAME_REGEXP.test(fields[j])) {
54305 throw new TypeError('field argument contains an invalid header name')
54306 }
54307 }
54308
54309 // existing, unspecified vary
54310 if (header === '*') {
54311 return header
54312 }
54313
54314 // enumerate current values
54315 var val = header;
54316 var vals = parse$9(header.toLowerCase());
54317
54318 // unspecified vary
54319 if (fields.indexOf('*') !== -1 || vals.indexOf('*') !== -1) {
54320 return '*'
54321 }
54322
54323 for (var i = 0; i < fields.length; i++) {
54324 var fld = fields[i].toLowerCase();
54325
54326 // append value (case-preserving)
54327 if (vals.indexOf(fld) === -1) {
54328 vals.push(fld);
54329 val = val
54330 ? val + ', ' + fields[i]
54331 : fields[i];
54332 }
54333 }
54334
54335 return val
54336}
54337
54338/**
54339 * Parse a vary header into an array.
54340 *
54341 * @param {String} header
54342 * @return {Array}
54343 * @private
54344 */
54345
54346function parse$9 (header) {
54347 var end = 0;
54348 var list = [];
54349 var start = 0;
54350
54351 // gather tokens
54352 for (var i = 0, len = header.length; i < len; i++) {
54353 switch (header.charCodeAt(i)) {
54354 case 0x20: /* */
54355 if (start === end) {
54356 start = end = i + 1;
54357 }
54358 break
54359 case 0x2c: /* , */
54360 list.push(header.substring(start, end));
54361 start = end = i + 1;
54362 break
54363 default:
54364 end = i + 1;
54365 break
54366 }
54367 }
54368
54369 // final token
54370 list.push(header.substring(start, end));
54371
54372 return list
54373}
54374
54375/**
54376 * Mark that a request is varied on a header field.
54377 *
54378 * @param {Object} res
54379 * @param {String|Array} field
54380 * @public
54381 */
54382
54383function vary (res, field) {
54384 if (!res || !res.getHeader || !res.setHeader) {
54385 // quack quack
54386 throw new TypeError('res argument is required')
54387 }
54388
54389 // get existing header
54390 var val = res.getHeader('Vary') || '';
54391 var header = Array.isArray(val)
54392 ? val.join(', ')
54393 : String(val);
54394
54395 // set new header
54396 if ((val = append(header, field))) {
54397 res.setHeader('Vary', val);
54398 }
54399}
54400
54401(function () {
54402
54403 var assign = objectAssign;
54404 var vary = vary$1.exports;
54405
54406 var defaults = {
54407 origin: '*',
54408 methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
54409 preflightContinue: false,
54410 optionsSuccessStatus: 204
54411 };
54412
54413 function isString(s) {
54414 return typeof s === 'string' || s instanceof String;
54415 }
54416
54417 function isOriginAllowed(origin, allowedOrigin) {
54418 if (Array.isArray(allowedOrigin)) {
54419 for (var i = 0; i < allowedOrigin.length; ++i) {
54420 if (isOriginAllowed(origin, allowedOrigin[i])) {
54421 return true;
54422 }
54423 }
54424 return false;
54425 } else if (isString(allowedOrigin)) {
54426 return origin === allowedOrigin;
54427 } else if (allowedOrigin instanceof RegExp) {
54428 return allowedOrigin.test(origin);
54429 } else {
54430 return !!allowedOrigin;
54431 }
54432 }
54433
54434 function configureOrigin(options, req) {
54435 var requestOrigin = req.headers.origin,
54436 headers = [],
54437 isAllowed;
54438
54439 if (!options.origin || options.origin === '*') {
54440 // allow any origin
54441 headers.push([{
54442 key: 'Access-Control-Allow-Origin',
54443 value: '*'
54444 }]);
54445 } else if (isString(options.origin)) {
54446 // fixed origin
54447 headers.push([{
54448 key: 'Access-Control-Allow-Origin',
54449 value: options.origin
54450 }]);
54451 headers.push([{
54452 key: 'Vary',
54453 value: 'Origin'
54454 }]);
54455 } else {
54456 isAllowed = isOriginAllowed(requestOrigin, options.origin);
54457 // reflect origin
54458 headers.push([{
54459 key: 'Access-Control-Allow-Origin',
54460 value: isAllowed ? requestOrigin : false
54461 }]);
54462 headers.push([{
54463 key: 'Vary',
54464 value: 'Origin'
54465 }]);
54466 }
54467
54468 return headers;
54469 }
54470
54471 function configureMethods(options) {
54472 var methods = options.methods;
54473 if (methods.join) {
54474 methods = options.methods.join(','); // .methods is an array, so turn it into a string
54475 }
54476 return {
54477 key: 'Access-Control-Allow-Methods',
54478 value: methods
54479 };
54480 }
54481
54482 function configureCredentials(options) {
54483 if (options.credentials === true) {
54484 return {
54485 key: 'Access-Control-Allow-Credentials',
54486 value: 'true'
54487 };
54488 }
54489 return null;
54490 }
54491
54492 function configureAllowedHeaders(options, req) {
54493 var allowedHeaders = options.allowedHeaders || options.headers;
54494 var headers = [];
54495
54496 if (!allowedHeaders) {
54497 allowedHeaders = req.headers['access-control-request-headers']; // .headers wasn't specified, so reflect the request headers
54498 headers.push([{
54499 key: 'Vary',
54500 value: 'Access-Control-Request-Headers'
54501 }]);
54502 } else if (allowedHeaders.join) {
54503 allowedHeaders = allowedHeaders.join(','); // .headers is an array, so turn it into a string
54504 }
54505 if (allowedHeaders && allowedHeaders.length) {
54506 headers.push([{
54507 key: 'Access-Control-Allow-Headers',
54508 value: allowedHeaders
54509 }]);
54510 }
54511
54512 return headers;
54513 }
54514
54515 function configureExposedHeaders(options) {
54516 var headers = options.exposedHeaders;
54517 if (!headers) {
54518 return null;
54519 } else if (headers.join) {
54520 headers = headers.join(','); // .headers is an array, so turn it into a string
54521 }
54522 if (headers && headers.length) {
54523 return {
54524 key: 'Access-Control-Expose-Headers',
54525 value: headers
54526 };
54527 }
54528 return null;
54529 }
54530
54531 function configureMaxAge(options) {
54532 var maxAge = (typeof options.maxAge === 'number' || options.maxAge) && options.maxAge.toString();
54533 if (maxAge && maxAge.length) {
54534 return {
54535 key: 'Access-Control-Max-Age',
54536 value: maxAge
54537 };
54538 }
54539 return null;
54540 }
54541
54542 function applyHeaders(headers, res) {
54543 for (var i = 0, n = headers.length; i < n; i++) {
54544 var header = headers[i];
54545 if (header) {
54546 if (Array.isArray(header)) {
54547 applyHeaders(header, res);
54548 } else if (header.key === 'Vary' && header.value) {
54549 vary(res, header.value);
54550 } else if (header.value) {
54551 res.setHeader(header.key, header.value);
54552 }
54553 }
54554 }
54555 }
54556
54557 function cors(options, req, res, next) {
54558 var headers = [],
54559 method = req.method && req.method.toUpperCase && req.method.toUpperCase();
54560
54561 if (method === 'OPTIONS') {
54562 // preflight
54563 headers.push(configureOrigin(options, req));
54564 headers.push(configureCredentials(options));
54565 headers.push(configureMethods(options));
54566 headers.push(configureAllowedHeaders(options, req));
54567 headers.push(configureMaxAge(options));
54568 headers.push(configureExposedHeaders(options));
54569 applyHeaders(headers, res);
54570
54571 if (options.preflightContinue) {
54572 next();
54573 } else {
54574 // Safari (and potentially other browsers) need content-length 0,
54575 // for 204 or they just hang waiting for a body
54576 res.statusCode = options.optionsSuccessStatus;
54577 res.setHeader('Content-Length', '0');
54578 res.end();
54579 }
54580 } else {
54581 // actual response
54582 headers.push(configureOrigin(options, req));
54583 headers.push(configureCredentials(options));
54584 headers.push(configureExposedHeaders(options));
54585 applyHeaders(headers, res);
54586 next();
54587 }
54588 }
54589
54590 function middlewareWrapper(o) {
54591 // if options are static (either via defaults or custom options passed in), wrap in a function
54592 var optionsCallback = null;
54593 if (typeof o === 'function') {
54594 optionsCallback = o;
54595 } else {
54596 optionsCallback = function (req, cb) {
54597 cb(null, o);
54598 };
54599 }
54600
54601 return function corsMiddleware(req, res, next) {
54602 optionsCallback(req, function (err, options) {
54603 if (err) {
54604 next(err);
54605 } else {
54606 var corsOptions = assign({}, defaults, options);
54607 var originCallback = null;
54608 if (corsOptions.origin && typeof corsOptions.origin === 'function') {
54609 originCallback = corsOptions.origin;
54610 } else if (corsOptions.origin) {
54611 originCallback = function (origin, cb) {
54612 cb(null, corsOptions.origin);
54613 };
54614 }
54615
54616 if (originCallback) {
54617 originCallback(req.headers.origin, function (err2, origin) {
54618 if (err2 || !origin) {
54619 next(err2);
54620 } else {
54621 corsOptions.origin = origin;
54622 cors(corsOptions, req, res, next);
54623 }
54624 });
54625 } else {
54626 next();
54627 }
54628 }
54629 });
54630 };
54631 }
54632
54633 // can pass either an options hash, an options delegate, or nothing
54634 lib$1.exports = middlewareWrapper;
54635
54636}());
54637
54638var corsMiddleware = lib$1.exports;
54639
54640var chokidar = {};
54641
54642const fs$b = fs__default;
54643const { Readable } = require$$0__default$2;
54644const sysPath$3 = path__default;
54645const { promisify: promisify$4 } = require$$0__default$3;
54646const picomatch$1 = picomatch$4;
54647
54648const readdir$1 = promisify$4(fs$b.readdir);
54649const stat$3 = promisify$4(fs$b.stat);
54650const lstat$2 = promisify$4(fs$b.lstat);
54651const realpath$1 = promisify$4(fs$b.realpath);
54652
54653/**
54654 * @typedef {Object} EntryInfo
54655 * @property {String} path
54656 * @property {String} fullPath
54657 * @property {fs.Stats=} stats
54658 * @property {fs.Dirent=} dirent
54659 * @property {String} basename
54660 */
54661
54662const BANG$2 = '!';
54663const RECURSIVE_ERROR_CODE = 'READDIRP_RECURSIVE_ERROR';
54664const NORMAL_FLOW_ERRORS = new Set(['ENOENT', 'EPERM', 'EACCES', 'ELOOP', RECURSIVE_ERROR_CODE]);
54665const FILE_TYPE = 'files';
54666const DIR_TYPE = 'directories';
54667const FILE_DIR_TYPE = 'files_directories';
54668const EVERYTHING_TYPE = 'all';
54669const ALL_TYPES = [FILE_TYPE, DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE];
54670
54671const isNormalFlowError = error => NORMAL_FLOW_ERRORS.has(error.code);
54672const [maj, min] = process.versions.node.split('.').slice(0, 2).map(n => Number.parseInt(n, 10));
54673const wantBigintFsStats = process.platform === 'win32' && (maj > 10 || (maj === 10 && min >= 5));
54674
54675const normalizeFilter = filter => {
54676 if (filter === undefined) return;
54677 if (typeof filter === 'function') return filter;
54678
54679 if (typeof filter === 'string') {
54680 const glob = picomatch$1(filter.trim());
54681 return entry => glob(entry.basename);
54682 }
54683
54684 if (Array.isArray(filter)) {
54685 const positive = [];
54686 const negative = [];
54687 for (const item of filter) {
54688 const trimmed = item.trim();
54689 if (trimmed.charAt(0) === BANG$2) {
54690 negative.push(picomatch$1(trimmed.slice(1)));
54691 } else {
54692 positive.push(picomatch$1(trimmed));
54693 }
54694 }
54695
54696 if (negative.length > 0) {
54697 if (positive.length > 0) {
54698 return entry =>
54699 positive.some(f => f(entry.basename)) && !negative.some(f => f(entry.basename));
54700 }
54701 return entry => !negative.some(f => f(entry.basename));
54702 }
54703 return entry => positive.some(f => f(entry.basename));
54704 }
54705};
54706
54707class ReaddirpStream extends Readable {
54708 static get defaultOptions() {
54709 return {
54710 root: '.',
54711 /* eslint-disable no-unused-vars */
54712 fileFilter: (path) => true,
54713 directoryFilter: (path) => true,
54714 /* eslint-enable no-unused-vars */
54715 type: FILE_TYPE,
54716 lstat: false,
54717 depth: 2147483648,
54718 alwaysStat: false
54719 };
54720 }
54721
54722 constructor(options = {}) {
54723 super({
54724 objectMode: true,
54725 autoDestroy: true,
54726 highWaterMark: options.highWaterMark || 4096
54727 });
54728 const opts = { ...ReaddirpStream.defaultOptions, ...options };
54729 const { root, type } = opts;
54730
54731 this._fileFilter = normalizeFilter(opts.fileFilter);
54732 this._directoryFilter = normalizeFilter(opts.directoryFilter);
54733
54734 const statMethod = opts.lstat ? lstat$2 : stat$3;
54735 // Use bigint stats if it's windows and stat() supports options (node 10+).
54736 if (wantBigintFsStats) {
54737 this._stat = path => statMethod(path, { bigint: true });
54738 } else {
54739 this._stat = statMethod;
54740 }
54741
54742 this._maxDepth = opts.depth;
54743 this._wantsDir = [DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
54744 this._wantsFile = [FILE_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
54745 this._wantsEverything = type === EVERYTHING_TYPE;
54746 this._root = sysPath$3.resolve(root);
54747 this._isDirent = ('Dirent' in fs$b) && !opts.alwaysStat;
54748 this._statsProp = this._isDirent ? 'dirent' : 'stats';
54749 this._rdOptions = { encoding: 'utf8', withFileTypes: this._isDirent };
54750
54751 // Launch stream with one parent, the root dir.
54752 this.parents = [this._exploreDir(root, 1)];
54753 this.reading = false;
54754 this.parent = undefined;
54755 }
54756
54757 async _read(batch) {
54758 if (this.reading) return;
54759 this.reading = true;
54760
54761 try {
54762 while (!this.destroyed && batch > 0) {
54763 const { path, depth, files = [] } = this.parent || {};
54764
54765 if (files.length > 0) {
54766 const slice = files.splice(0, batch).map(dirent => this._formatEntry(dirent, path));
54767 for (const entry of await Promise.all(slice)) {
54768 if (this.destroyed) return;
54769
54770 const entryType = await this._getEntryType(entry);
54771 if (entryType === 'directory' && this._directoryFilter(entry)) {
54772 if (depth <= this._maxDepth) {
54773 this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
54774 }
54775
54776 if (this._wantsDir) {
54777 this.push(entry);
54778 batch--;
54779 }
54780 } else if ((entryType === 'file' || this._includeAsFile(entry)) && this._fileFilter(entry)) {
54781 if (this._wantsFile) {
54782 this.push(entry);
54783 batch--;
54784 }
54785 }
54786 }
54787 } else {
54788 const parent = this.parents.pop();
54789 if (!parent) {
54790 this.push(null);
54791 break;
54792 }
54793 this.parent = await parent;
54794 if (this.destroyed) return;
54795 }
54796 }
54797 } catch (error) {
54798 this.destroy(error);
54799 } finally {
54800 this.reading = false;
54801 }
54802 }
54803
54804 async _exploreDir(path, depth) {
54805 let files;
54806 try {
54807 files = await readdir$1(path, this._rdOptions);
54808 } catch (error) {
54809 this._onError(error);
54810 }
54811 return { files, depth, path };
54812 }
54813
54814 async _formatEntry(dirent, path) {
54815 let entry;
54816 try {
54817 const basename = this._isDirent ? dirent.name : dirent;
54818 const fullPath = sysPath$3.resolve(sysPath$3.join(path, basename));
54819 entry = { path: sysPath$3.relative(this._root, fullPath), fullPath, basename };
54820 entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
54821 } catch (err) {
54822 this._onError(err);
54823 }
54824 return entry;
54825 }
54826
54827 _onError(err) {
54828 if (isNormalFlowError(err) && !this.destroyed) {
54829 this.emit('warn', err);
54830 } else {
54831 this.destroy(err);
54832 }
54833 }
54834
54835 async _getEntryType(entry) {
54836 // entry may be undefined, because a warning or an error were emitted
54837 // and the statsProp is undefined
54838 const stats = entry && entry[this._statsProp];
54839 if (!stats) {
54840 return;
54841 }
54842 if (stats.isFile()) {
54843 return 'file';
54844 }
54845 if (stats.isDirectory()) {
54846 return 'directory';
54847 }
54848 if (stats && stats.isSymbolicLink()) {
54849 const full = entry.fullPath;
54850 try {
54851 const entryRealPath = await realpath$1(full);
54852 const entryRealPathStats = await lstat$2(entryRealPath);
54853 if (entryRealPathStats.isFile()) {
54854 return 'file';
54855 }
54856 if (entryRealPathStats.isDirectory()) {
54857 const len = entryRealPath.length;
54858 if (full.startsWith(entryRealPath) && full.substr(len, 1) === sysPath$3.sep) {
54859 const recursiveError = new Error(
54860 `Circular symlink detected: "${full}" points to "${entryRealPath}"`
54861 );
54862 recursiveError.code = RECURSIVE_ERROR_CODE;
54863 return this._onError(recursiveError);
54864 }
54865 return 'directory';
54866 }
54867 } catch (error) {
54868 this._onError(error);
54869 }
54870 }
54871 }
54872
54873 _includeAsFile(entry) {
54874 const stats = entry && entry[this._statsProp];
54875
54876 return stats && this._wantsEverything && !stats.isDirectory();
54877 }
54878}
54879
54880/**
54881 * @typedef {Object} ReaddirpArguments
54882 * @property {Function=} fileFilter
54883 * @property {Function=} directoryFilter
54884 * @property {String=} type
54885 * @property {Number=} depth
54886 * @property {String=} root
54887 * @property {Boolean=} lstat
54888 * @property {Boolean=} bigint
54889 */
54890
54891/**
54892 * Main function which ends up calling readdirRec and reads all files and directories in given root recursively.
54893 * @param {String} root Root directory
54894 * @param {ReaddirpArguments=} options Options to specify root (start directory), filters and recursion depth
54895 */
54896const readdirp$1 = (root, options = {}) => {
54897 let type = options.entryType || options.type;
54898 if (type === 'both') type = FILE_DIR_TYPE; // backwards-compatibility
54899 if (type) options.type = type;
54900 if (!root) {
54901 throw new Error('readdirp: root argument is required. Usage: readdirp(root, options)');
54902 } else if (typeof root !== 'string') {
54903 throw new TypeError('readdirp: root argument must be a string. Usage: readdirp(root, options)');
54904 } else if (type && !ALL_TYPES.includes(type)) {
54905 throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(', ')}`);
54906 }
54907
54908 options.root = root;
54909 return new ReaddirpStream(options);
54910};
54911
54912const readdirpPromise = (root, options = {}) => {
54913 return new Promise((resolve, reject) => {
54914 const files = [];
54915 readdirp$1(root, options)
54916 .on('data', entry => files.push(entry))
54917 .on('end', () => resolve(files))
54918 .on('error', error => reject(error));
54919 });
54920};
54921
54922readdirp$1.promise = readdirpPromise;
54923readdirp$1.ReaddirpStream = ReaddirpStream;
54924readdirp$1.default = readdirp$1;
54925
54926var readdirp_1 = readdirp$1;
54927
54928var anymatch$2 = {exports: {}};
54929
54930/*!
54931 * normalize-path <https://github.com/jonschlinkert/normalize-path>
54932 *
54933 * Copyright (c) 2014-2018, Jon Schlinkert.
54934 * Released under the MIT License.
54935 */
54936
54937var normalizePath$2 = function(path, stripTrailing) {
54938 if (typeof path !== 'string') {
54939 throw new TypeError('expected path to be a string');
54940 }
54941
54942 if (path === '\\' || path === '/') return '/';
54943
54944 var len = path.length;
54945 if (len <= 1) return path;
54946
54947 // ensure that win32 namespaces has two leading slashes, so that the path is
54948 // handled properly by the win32 version of path.parse() after being normalized
54949 // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces
54950 var prefix = '';
54951 if (len > 4 && path[3] === '\\') {
54952 var ch = path[2];
54953 if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\') {
54954 path = path.slice(2);
54955 prefix = '//';
54956 }
54957 }
54958
54959 var segs = path.split(/[/\\]+/);
54960 if (stripTrailing !== false && segs[segs.length - 1] === '') {
54961 segs.pop();
54962 }
54963 return prefix + segs.join('/');
54964};
54965
54966Object.defineProperty(anymatch$2.exports, "__esModule", { value: true });
54967
54968const picomatch = picomatch$4;
54969const normalizePath$1 = normalizePath$2;
54970
54971/**
54972 * @typedef {(testString: string) => boolean} AnymatchFn
54973 * @typedef {string|RegExp|AnymatchFn} AnymatchPattern
54974 * @typedef {AnymatchPattern|AnymatchPattern[]} AnymatchMatcher
54975 */
54976const BANG$1 = '!';
54977const DEFAULT_OPTIONS = {returnIndex: false};
54978const arrify$1 = (item) => Array.isArray(item) ? item : [item];
54979
54980/**
54981 * @param {AnymatchPattern} matcher
54982 * @param {object} options
54983 * @returns {AnymatchFn}
54984 */
54985const createPattern = (matcher, options) => {
54986 if (typeof matcher === 'function') {
54987 return matcher;
54988 }
54989 if (typeof matcher === 'string') {
54990 const glob = picomatch(matcher, options);
54991 return (string) => matcher === string || glob(string);
54992 }
54993 if (matcher instanceof RegExp) {
54994 return (string) => matcher.test(string);
54995 }
54996 return (string) => false;
54997};
54998
54999/**
55000 * @param {Array<Function>} patterns
55001 * @param {Array<Function>} negPatterns
55002 * @param {String|Array} args
55003 * @param {Boolean} returnIndex
55004 * @returns {boolean|number}
55005 */
55006const matchPatterns = (patterns, negPatterns, args, returnIndex) => {
55007 const isList = Array.isArray(args);
55008 const _path = isList ? args[0] : args;
55009 if (!isList && typeof _path !== 'string') {
55010 throw new TypeError('anymatch: second argument must be a string: got ' +
55011 Object.prototype.toString.call(_path))
55012 }
55013 const path = normalizePath$1(_path);
55014
55015 for (let index = 0; index < negPatterns.length; index++) {
55016 const nglob = negPatterns[index];
55017 if (nglob(path)) {
55018 return returnIndex ? -1 : false;
55019 }
55020 }
55021
55022 const applied = isList && [path].concat(args.slice(1));
55023 for (let index = 0; index < patterns.length; index++) {
55024 const pattern = patterns[index];
55025 if (isList ? pattern(...applied) : pattern(path)) {
55026 return returnIndex ? index : true;
55027 }
55028 }
55029
55030 return returnIndex ? -1 : false;
55031};
55032
55033/**
55034 * @param {AnymatchMatcher} matchers
55035 * @param {Array|string} testString
55036 * @param {object} options
55037 * @returns {boolean|number|Function}
55038 */
55039const anymatch$1 = (matchers, testString, options = DEFAULT_OPTIONS) => {
55040 if (matchers == null) {
55041 throw new TypeError('anymatch: specify first argument');
55042 }
55043 const opts = typeof options === 'boolean' ? {returnIndex: options} : options;
55044 const returnIndex = opts.returnIndex || false;
55045
55046 // Early cache for matchers.
55047 const mtchers = arrify$1(matchers);
55048 const negatedGlobs = mtchers
55049 .filter(item => typeof item === 'string' && item.charAt(0) === BANG$1)
55050 .map(item => item.slice(1))
55051 .map(item => picomatch(item, opts));
55052 const patterns = mtchers
55053 .filter(item => typeof item !== 'string' || (typeof item === 'string' && item.charAt(0) !== BANG$1))
55054 .map(matcher => createPattern(matcher, opts));
55055
55056 if (testString == null) {
55057 return (testString, ri = false) => {
55058 const returnIndex = typeof ri === 'boolean' ? ri : false;
55059 return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
55060 }
55061 }
55062
55063 return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
55064};
55065
55066anymatch$1.default = anymatch$1;
55067anymatch$2.exports = anymatch$1;
55068
55069var require$$0$1 = [
55070 "3dm",
55071 "3ds",
55072 "3g2",
55073 "3gp",
55074 "7z",
55075 "a",
55076 "aac",
55077 "adp",
55078 "ai",
55079 "aif",
55080 "aiff",
55081 "alz",
55082 "ape",
55083 "apk",
55084 "appimage",
55085 "ar",
55086 "arj",
55087 "asf",
55088 "au",
55089 "avi",
55090 "bak",
55091 "baml",
55092 "bh",
55093 "bin",
55094 "bk",
55095 "bmp",
55096 "btif",
55097 "bz2",
55098 "bzip2",
55099 "cab",
55100 "caf",
55101 "cgm",
55102 "class",
55103 "cmx",
55104 "cpio",
55105 "cr2",
55106 "cur",
55107 "dat",
55108 "dcm",
55109 "deb",
55110 "dex",
55111 "djvu",
55112 "dll",
55113 "dmg",
55114 "dng",
55115 "doc",
55116 "docm",
55117 "docx",
55118 "dot",
55119 "dotm",
55120 "dra",
55121 "DS_Store",
55122 "dsk",
55123 "dts",
55124 "dtshd",
55125 "dvb",
55126 "dwg",
55127 "dxf",
55128 "ecelp4800",
55129 "ecelp7470",
55130 "ecelp9600",
55131 "egg",
55132 "eol",
55133 "eot",
55134 "epub",
55135 "exe",
55136 "f4v",
55137 "fbs",
55138 "fh",
55139 "fla",
55140 "flac",
55141 "flatpak",
55142 "fli",
55143 "flv",
55144 "fpx",
55145 "fst",
55146 "fvt",
55147 "g3",
55148 "gh",
55149 "gif",
55150 "graffle",
55151 "gz",
55152 "gzip",
55153 "h261",
55154 "h263",
55155 "h264",
55156 "icns",
55157 "ico",
55158 "ief",
55159 "img",
55160 "ipa",
55161 "iso",
55162 "jar",
55163 "jpeg",
55164 "jpg",
55165 "jpgv",
55166 "jpm",
55167 "jxr",
55168 "key",
55169 "ktx",
55170 "lha",
55171 "lib",
55172 "lvp",
55173 "lz",
55174 "lzh",
55175 "lzma",
55176 "lzo",
55177 "m3u",
55178 "m4a",
55179 "m4v",
55180 "mar",
55181 "mdi",
55182 "mht",
55183 "mid",
55184 "midi",
55185 "mj2",
55186 "mka",
55187 "mkv",
55188 "mmr",
55189 "mng",
55190 "mobi",
55191 "mov",
55192 "movie",
55193 "mp3",
55194 "mp4",
55195 "mp4a",
55196 "mpeg",
55197 "mpg",
55198 "mpga",
55199 "mxu",
55200 "nef",
55201 "npx",
55202 "numbers",
55203 "nupkg",
55204 "o",
55205 "odp",
55206 "ods",
55207 "odt",
55208 "oga",
55209 "ogg",
55210 "ogv",
55211 "otf",
55212 "ott",
55213 "pages",
55214 "pbm",
55215 "pcx",
55216 "pdb",
55217 "pdf",
55218 "pea",
55219 "pgm",
55220 "pic",
55221 "png",
55222 "pnm",
55223 "pot",
55224 "potm",
55225 "potx",
55226 "ppa",
55227 "ppam",
55228 "ppm",
55229 "pps",
55230 "ppsm",
55231 "ppsx",
55232 "ppt",
55233 "pptm",
55234 "pptx",
55235 "psd",
55236 "pya",
55237 "pyc",
55238 "pyo",
55239 "pyv",
55240 "qt",
55241 "rar",
55242 "ras",
55243 "raw",
55244 "resources",
55245 "rgb",
55246 "rip",
55247 "rlc",
55248 "rmf",
55249 "rmvb",
55250 "rpm",
55251 "rtf",
55252 "rz",
55253 "s3m",
55254 "s7z",
55255 "scpt",
55256 "sgi",
55257 "shar",
55258 "snap",
55259 "sil",
55260 "sketch",
55261 "slk",
55262 "smv",
55263 "snk",
55264 "so",
55265 "stl",
55266 "suo",
55267 "sub",
55268 "swf",
55269 "tar",
55270 "tbz",
55271 "tbz2",
55272 "tga",
55273 "tgz",
55274 "thmx",
55275 "tif",
55276 "tiff",
55277 "tlz",
55278 "ttc",
55279 "ttf",
55280 "txz",
55281 "udf",
55282 "uvh",
55283 "uvi",
55284 "uvm",
55285 "uvp",
55286 "uvs",
55287 "uvu",
55288 "viv",
55289 "vob",
55290 "war",
55291 "wav",
55292 "wax",
55293 "wbmp",
55294 "wdp",
55295 "weba",
55296 "webm",
55297 "webp",
55298 "whl",
55299 "wim",
55300 "wm",
55301 "wma",
55302 "wmv",
55303 "wmx",
55304 "woff",
55305 "woff2",
55306 "wrm",
55307 "wvx",
55308 "xbm",
55309 "xif",
55310 "xla",
55311 "xlam",
55312 "xls",
55313 "xlsb",
55314 "xlsm",
55315 "xlsx",
55316 "xlt",
55317 "xltm",
55318 "xltx",
55319 "xm",
55320 "xmind",
55321 "xpi",
55322 "xpm",
55323 "xwd",
55324 "xz",
55325 "z",
55326 "zip",
55327 "zipx"
55328];
55329
55330var binaryExtensions$1 = require$$0$1;
55331
55332const path$a = path__default;
55333const binaryExtensions = binaryExtensions$1;
55334
55335const extensions = new Set(binaryExtensions);
55336
55337var isBinaryPath$1 = filePath => extensions.has(path$a.extname(filePath).slice(1).toLowerCase());
55338
55339var constants$1 = {};
55340
55341(function (exports) {
55342
55343const {sep} = path__default;
55344const {platform} = process;
55345const os = require$$0__default$1;
55346
55347exports.EV_ALL = 'all';
55348exports.EV_READY = 'ready';
55349exports.EV_ADD = 'add';
55350exports.EV_CHANGE = 'change';
55351exports.EV_ADD_DIR = 'addDir';
55352exports.EV_UNLINK = 'unlink';
55353exports.EV_UNLINK_DIR = 'unlinkDir';
55354exports.EV_RAW = 'raw';
55355exports.EV_ERROR = 'error';
55356
55357exports.STR_DATA = 'data';
55358exports.STR_END = 'end';
55359exports.STR_CLOSE = 'close';
55360
55361exports.FSEVENT_CREATED = 'created';
55362exports.FSEVENT_MODIFIED = 'modified';
55363exports.FSEVENT_DELETED = 'deleted';
55364exports.FSEVENT_MOVED = 'moved';
55365exports.FSEVENT_CLONED = 'cloned';
55366exports.FSEVENT_UNKNOWN = 'unknown';
55367exports.FSEVENT_TYPE_FILE = 'file';
55368exports.FSEVENT_TYPE_DIRECTORY = 'directory';
55369exports.FSEVENT_TYPE_SYMLINK = 'symlink';
55370
55371exports.KEY_LISTENERS = 'listeners';
55372exports.KEY_ERR = 'errHandlers';
55373exports.KEY_RAW = 'rawEmitters';
55374exports.HANDLER_KEYS = [exports.KEY_LISTENERS, exports.KEY_ERR, exports.KEY_RAW];
55375
55376exports.DOT_SLASH = `.${sep}`;
55377
55378exports.BACK_SLASH_RE = /\\/g;
55379exports.DOUBLE_SLASH_RE = /\/\//;
55380exports.SLASH_OR_BACK_SLASH_RE = /[/\\]/;
55381exports.DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
55382exports.REPLACER_RE = /^\.[/\\]/;
55383
55384exports.SLASH = '/';
55385exports.SLASH_SLASH = '//';
55386exports.BRACE_START = '{';
55387exports.BANG = '!';
55388exports.ONE_DOT = '.';
55389exports.TWO_DOTS = '..';
55390exports.STAR = '*';
55391exports.GLOBSTAR = '**';
55392exports.ROOT_GLOBSTAR = '/**/*';
55393exports.SLASH_GLOBSTAR = '/**';
55394exports.DIR_SUFFIX = 'Dir';
55395exports.ANYMATCH_OPTS = {dot: true};
55396exports.STRING_TYPE = 'string';
55397exports.FUNCTION_TYPE = 'function';
55398exports.EMPTY_STR = '';
55399exports.EMPTY_FN = () => {};
55400exports.IDENTITY_FN = val => val;
55401
55402exports.isWindows = platform === 'win32';
55403exports.isMacos = platform === 'darwin';
55404exports.isLinux = platform === 'linux';
55405exports.isIBMi = os.type() === 'OS400';
55406}(constants$1));
55407
55408const fs$a = fs__default;
55409const sysPath$2 = path__default;
55410const { promisify: promisify$3 } = require$$0__default$3;
55411const isBinaryPath = isBinaryPath$1;
55412const {
55413 isWindows: isWindows$2,
55414 isLinux,
55415 EMPTY_FN: EMPTY_FN$2,
55416 EMPTY_STR: EMPTY_STR$1,
55417 KEY_LISTENERS,
55418 KEY_ERR,
55419 KEY_RAW,
55420 HANDLER_KEYS,
55421 EV_CHANGE: EV_CHANGE$2,
55422 EV_ADD: EV_ADD$2,
55423 EV_ADD_DIR: EV_ADD_DIR$2,
55424 EV_ERROR: EV_ERROR$2,
55425 STR_DATA: STR_DATA$1,
55426 STR_END: STR_END$2,
55427 BRACE_START: BRACE_START$1,
55428 STAR
55429} = constants$1;
55430
55431const THROTTLE_MODE_WATCH = 'watch';
55432
55433const open$1 = promisify$3(fs$a.open);
55434const stat$2 = promisify$3(fs$a.stat);
55435const lstat$1 = promisify$3(fs$a.lstat);
55436const close = promisify$3(fs$a.close);
55437const fsrealpath = promisify$3(fs$a.realpath);
55438
55439const statMethods$1 = { lstat: lstat$1, stat: stat$2 };
55440
55441// TODO: emit errors properly. Example: EMFILE on Macos.
55442const foreach = (val, fn) => {
55443 if (val instanceof Set) {
55444 val.forEach(fn);
55445 } else {
55446 fn(val);
55447 }
55448};
55449
55450const addAndConvert = (main, prop, item) => {
55451 let container = main[prop];
55452 if (!(container instanceof Set)) {
55453 main[prop] = container = new Set([container]);
55454 }
55455 container.add(item);
55456};
55457
55458const clearItem = cont => key => {
55459 const set = cont[key];
55460 if (set instanceof Set) {
55461 set.clear();
55462 } else {
55463 delete cont[key];
55464 }
55465};
55466
55467const delFromSet = (main, prop, item) => {
55468 const container = main[prop];
55469 if (container instanceof Set) {
55470 container.delete(item);
55471 } else if (container === item) {
55472 delete main[prop];
55473 }
55474};
55475
55476const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
55477
55478/**
55479 * @typedef {String} Path
55480 */
55481
55482// fs_watch helpers
55483
55484// object to hold per-process fs_watch instances
55485// (may be shared across chokidar FSWatcher instances)
55486
55487/**
55488 * @typedef {Object} FsWatchContainer
55489 * @property {Set} listeners
55490 * @property {Set} errHandlers
55491 * @property {Set} rawEmitters
55492 * @property {fs.FSWatcher=} watcher
55493 * @property {Boolean=} watcherUnusable
55494 */
55495
55496/**
55497 * @type {Map<String,FsWatchContainer>}
55498 */
55499const FsWatchInstances = new Map();
55500
55501/**
55502 * Instantiates the fs_watch interface
55503 * @param {String} path to be watched
55504 * @param {Object} options to be passed to fs_watch
55505 * @param {Function} listener main event handler
55506 * @param {Function} errHandler emits info about errors
55507 * @param {Function} emitRaw emits raw event data
55508 * @returns {fs.FSWatcher} new fsevents instance
55509 */
55510function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
55511 const handleEvent = (rawEvent, evPath) => {
55512 listener(path);
55513 emitRaw(rawEvent, evPath, {watchedPath: path});
55514
55515 // emit based on events occurring for files from a directory's watcher in
55516 // case the file's watcher misses it (and rely on throttling to de-dupe)
55517 if (evPath && path !== evPath) {
55518 fsWatchBroadcast(
55519 sysPath$2.resolve(path, evPath), KEY_LISTENERS, sysPath$2.join(path, evPath)
55520 );
55521 }
55522 };
55523 try {
55524 return fs$a.watch(path, options, handleEvent);
55525 } catch (error) {
55526 errHandler(error);
55527 }
55528}
55529
55530/**
55531 * Helper for passing fs_watch event data to a collection of listeners
55532 * @param {Path} fullPath absolute path bound to fs_watch instance
55533 * @param {String} type listener type
55534 * @param {*=} val1 arguments to be passed to listeners
55535 * @param {*=} val2
55536 * @param {*=} val3
55537 */
55538const fsWatchBroadcast = (fullPath, type, val1, val2, val3) => {
55539 const cont = FsWatchInstances.get(fullPath);
55540 if (!cont) return;
55541 foreach(cont[type], (listener) => {
55542 listener(val1, val2, val3);
55543 });
55544};
55545
55546/**
55547 * Instantiates the fs_watch interface or binds listeners
55548 * to an existing one covering the same file system entry
55549 * @param {String} path
55550 * @param {String} fullPath absolute path
55551 * @param {Object} options to be passed to fs_watch
55552 * @param {Object} handlers container for event listener functions
55553 */
55554const setFsWatchListener = (path, fullPath, options, handlers) => {
55555 const {listener, errHandler, rawEmitter} = handlers;
55556 let cont = FsWatchInstances.get(fullPath);
55557
55558 /** @type {fs.FSWatcher=} */
55559 let watcher;
55560 if (!options.persistent) {
55561 watcher = createFsWatchInstance(
55562 path, options, listener, errHandler, rawEmitter
55563 );
55564 return watcher.close.bind(watcher);
55565 }
55566 if (cont) {
55567 addAndConvert(cont, KEY_LISTENERS, listener);
55568 addAndConvert(cont, KEY_ERR, errHandler);
55569 addAndConvert(cont, KEY_RAW, rawEmitter);
55570 } else {
55571 watcher = createFsWatchInstance(
55572 path,
55573 options,
55574 fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
55575 errHandler, // no need to use broadcast here
55576 fsWatchBroadcast.bind(null, fullPath, KEY_RAW)
55577 );
55578 if (!watcher) return;
55579 watcher.on(EV_ERROR$2, async (error) => {
55580 const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
55581 cont.watcherUnusable = true; // documented since Node 10.4.1
55582 // Workaround for https://github.com/joyent/node/issues/4337
55583 if (isWindows$2 && error.code === 'EPERM') {
55584 try {
55585 const fd = await open$1(path, 'r');
55586 await close(fd);
55587 broadcastErr(error);
55588 } catch (err) {}
55589 } else {
55590 broadcastErr(error);
55591 }
55592 });
55593 cont = {
55594 listeners: listener,
55595 errHandlers: errHandler,
55596 rawEmitters: rawEmitter,
55597 watcher
55598 };
55599 FsWatchInstances.set(fullPath, cont);
55600 }
55601 // const index = cont.listeners.indexOf(listener);
55602
55603 // removes this instance's listeners and closes the underlying fs_watch
55604 // instance if there are no more listeners left
55605 return () => {
55606 delFromSet(cont, KEY_LISTENERS, listener);
55607 delFromSet(cont, KEY_ERR, errHandler);
55608 delFromSet(cont, KEY_RAW, rawEmitter);
55609 if (isEmptySet(cont.listeners)) {
55610 // Check to protect against issue gh-730.
55611 // if (cont.watcherUnusable) {
55612 cont.watcher.close();
55613 // }
55614 FsWatchInstances.delete(fullPath);
55615 HANDLER_KEYS.forEach(clearItem(cont));
55616 cont.watcher = undefined;
55617 Object.freeze(cont);
55618 }
55619 };
55620};
55621
55622// fs_watchFile helpers
55623
55624// object to hold per-process fs_watchFile instances
55625// (may be shared across chokidar FSWatcher instances)
55626const FsWatchFileInstances = new Map();
55627
55628/**
55629 * Instantiates the fs_watchFile interface or binds listeners
55630 * to an existing one covering the same file system entry
55631 * @param {String} path to be watched
55632 * @param {String} fullPath absolute path
55633 * @param {Object} options options to be passed to fs_watchFile
55634 * @param {Object} handlers container for event listener functions
55635 * @returns {Function} closer
55636 */
55637const setFsWatchFileListener = (path, fullPath, options, handlers) => {
55638 const {listener, rawEmitter} = handlers;
55639 let cont = FsWatchFileInstances.get(fullPath);
55640
55641 const copts = cont && cont.options;
55642 if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
55643 fs$a.unwatchFile(fullPath);
55644 cont = undefined;
55645 }
55646
55647 /* eslint-enable no-unused-vars, prefer-destructuring */
55648
55649 if (cont) {
55650 addAndConvert(cont, KEY_LISTENERS, listener);
55651 addAndConvert(cont, KEY_RAW, rawEmitter);
55652 } else {
55653 // TODO
55654 // listeners.add(listener);
55655 // rawEmitters.add(rawEmitter);
55656 cont = {
55657 listeners: listener,
55658 rawEmitters: rawEmitter,
55659 options,
55660 watcher: fs$a.watchFile(fullPath, options, (curr, prev) => {
55661 foreach(cont.rawEmitters, (rawEmitter) => {
55662 rawEmitter(EV_CHANGE$2, fullPath, {curr, prev});
55663 });
55664 const currmtime = curr.mtimeMs;
55665 if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
55666 foreach(cont.listeners, (listener) => listener(path, curr));
55667 }
55668 })
55669 };
55670 FsWatchFileInstances.set(fullPath, cont);
55671 }
55672 // const index = cont.listeners.indexOf(listener);
55673
55674 // Removes this instance's listeners and closes the underlying fs_watchFile
55675 // instance if there are no more listeners left.
55676 return () => {
55677 delFromSet(cont, KEY_LISTENERS, listener);
55678 delFromSet(cont, KEY_RAW, rawEmitter);
55679 if (isEmptySet(cont.listeners)) {
55680 FsWatchFileInstances.delete(fullPath);
55681 fs$a.unwatchFile(fullPath);
55682 cont.options = cont.watcher = undefined;
55683 Object.freeze(cont);
55684 }
55685 };
55686};
55687
55688/**
55689 * @mixin
55690 */
55691class NodeFsHandler$1 {
55692
55693/**
55694 * @param {import("../index").FSWatcher} fsW
55695 */
55696constructor(fsW) {
55697 this.fsw = fsW;
55698 this._boundHandleError = (error) => fsW._handleError(error);
55699}
55700
55701/**
55702 * Watch file for changes with fs_watchFile or fs_watch.
55703 * @param {String} path to file or dir
55704 * @param {Function} listener on fs change
55705 * @returns {Function} closer for the watcher instance
55706 */
55707_watchWithNodeFs(path, listener) {
55708 const opts = this.fsw.options;
55709 const directory = sysPath$2.dirname(path);
55710 const basename = sysPath$2.basename(path);
55711 const parent = this.fsw._getWatchedDir(directory);
55712 parent.add(basename);
55713 const absolutePath = sysPath$2.resolve(path);
55714 const options = {persistent: opts.persistent};
55715 if (!listener) listener = EMPTY_FN$2;
55716
55717 let closer;
55718 if (opts.usePolling) {
55719 options.interval = opts.enableBinaryInterval && isBinaryPath(basename) ?
55720 opts.binaryInterval : opts.interval;
55721 closer = setFsWatchFileListener(path, absolutePath, options, {
55722 listener,
55723 rawEmitter: this.fsw._emitRaw
55724 });
55725 } else {
55726 closer = setFsWatchListener(path, absolutePath, options, {
55727 listener,
55728 errHandler: this._boundHandleError,
55729 rawEmitter: this.fsw._emitRaw
55730 });
55731 }
55732 return closer;
55733}
55734
55735/**
55736 * Watch a file and emit add event if warranted.
55737 * @param {Path} file Path
55738 * @param {fs.Stats} stats result of fs_stat
55739 * @param {Boolean} initialAdd was the file added at watch instantiation?
55740 * @returns {Function} closer for the watcher instance
55741 */
55742_handleFile(file, stats, initialAdd) {
55743 if (this.fsw.closed) {
55744 return;
55745 }
55746 const dirname = sysPath$2.dirname(file);
55747 const basename = sysPath$2.basename(file);
55748 const parent = this.fsw._getWatchedDir(dirname);
55749 // stats is always present
55750 let prevStats = stats;
55751
55752 // if the file is already being watched, do nothing
55753 if (parent.has(basename)) return;
55754
55755 const listener = async (path, newStats) => {
55756 if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return;
55757 if (!newStats || newStats.mtimeMs === 0) {
55758 try {
55759 const newStats = await stat$2(file);
55760 if (this.fsw.closed) return;
55761 // Check that change event was not fired because of changed only accessTime.
55762 const at = newStats.atimeMs;
55763 const mt = newStats.mtimeMs;
55764 if (!at || at <= mt || mt !== prevStats.mtimeMs) {
55765 this.fsw._emit(EV_CHANGE$2, file, newStats);
55766 }
55767 if (isLinux && prevStats.ino !== newStats.ino) {
55768 this.fsw._closeFile(path);
55769 prevStats = newStats;
55770 this.fsw._addPathCloser(path, this._watchWithNodeFs(file, listener));
55771 } else {
55772 prevStats = newStats;
55773 }
55774 } catch (error) {
55775 // Fix issues where mtime is null but file is still present
55776 this.fsw._remove(dirname, basename);
55777 }
55778 // add is about to be emitted if file not already tracked in parent
55779 } else if (parent.has(basename)) {
55780 // Check that change event was not fired because of changed only accessTime.
55781 const at = newStats.atimeMs;
55782 const mt = newStats.mtimeMs;
55783 if (!at || at <= mt || mt !== prevStats.mtimeMs) {
55784 this.fsw._emit(EV_CHANGE$2, file, newStats);
55785 }
55786 prevStats = newStats;
55787 }
55788 };
55789 // kick off the watcher
55790 const closer = this._watchWithNodeFs(file, listener);
55791
55792 // emit an add event if we're supposed to
55793 if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
55794 if (!this.fsw._throttle(EV_ADD$2, file, 0)) return;
55795 this.fsw._emit(EV_ADD$2, file, stats);
55796 }
55797
55798 return closer;
55799}
55800
55801/**
55802 * Handle symlinks encountered while reading a dir.
55803 * @param {Object} entry returned by readdirp
55804 * @param {String} directory path of dir being read
55805 * @param {String} path of this item
55806 * @param {String} item basename of this item
55807 * @returns {Promise<Boolean>} true if no more processing is needed for this entry.
55808 */
55809async _handleSymlink(entry, directory, path, item) {
55810 if (this.fsw.closed) {
55811 return;
55812 }
55813 const full = entry.fullPath;
55814 const dir = this.fsw._getWatchedDir(directory);
55815
55816 if (!this.fsw.options.followSymlinks) {
55817 // watch symlink directly (don't follow) and detect changes
55818 this.fsw._incrReadyCount();
55819 const linkPath = await fsrealpath(path);
55820 if (this.fsw.closed) return;
55821 if (dir.has(item)) {
55822 if (this.fsw._symlinkPaths.get(full) !== linkPath) {
55823 this.fsw._symlinkPaths.set(full, linkPath);
55824 this.fsw._emit(EV_CHANGE$2, path, entry.stats);
55825 }
55826 } else {
55827 dir.add(item);
55828 this.fsw._symlinkPaths.set(full, linkPath);
55829 this.fsw._emit(EV_ADD$2, path, entry.stats);
55830 }
55831 this.fsw._emitReady();
55832 return true;
55833 }
55834
55835 // don't follow the same symlink more than once
55836 if (this.fsw._symlinkPaths.has(full)) {
55837 return true;
55838 }
55839
55840 this.fsw._symlinkPaths.set(full, true);
55841}
55842
55843_handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
55844 // Normalize the directory name on Windows
55845 directory = sysPath$2.join(directory, EMPTY_STR$1);
55846
55847 if (!wh.hasGlob) {
55848 throttler = this.fsw._throttle('readdir', directory, 1000);
55849 if (!throttler) return;
55850 }
55851
55852 const previous = this.fsw._getWatchedDir(wh.path);
55853 const current = new Set();
55854
55855 let stream = this.fsw._readdirp(directory, {
55856 fileFilter: entry => wh.filterPath(entry),
55857 directoryFilter: entry => wh.filterDir(entry),
55858 depth: 0
55859 }).on(STR_DATA$1, async (entry) => {
55860 if (this.fsw.closed) {
55861 stream = undefined;
55862 return;
55863 }
55864 const item = entry.path;
55865 let path = sysPath$2.join(directory, item);
55866 current.add(item);
55867
55868 if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) {
55869 return;
55870 }
55871
55872 if (this.fsw.closed) {
55873 stream = undefined;
55874 return;
55875 }
55876 // Files that present in current directory snapshot
55877 // but absent in previous are added to watch list and
55878 // emit `add` event.
55879 if (item === target || !target && !previous.has(item)) {
55880 this.fsw._incrReadyCount();
55881
55882 // ensure relativeness of path is preserved in case of watcher reuse
55883 path = sysPath$2.join(dir, sysPath$2.relative(dir, path));
55884
55885 this._addToNodeFs(path, initialAdd, wh, depth + 1);
55886 }
55887 }).on(EV_ERROR$2, this._boundHandleError);
55888
55889 return new Promise(resolve =>
55890 stream.once(STR_END$2, () => {
55891 if (this.fsw.closed) {
55892 stream = undefined;
55893 return;
55894 }
55895 const wasThrottled = throttler ? throttler.clear() : false;
55896
55897 resolve();
55898
55899 // Files that absent in current directory snapshot
55900 // but present in previous emit `remove` event
55901 // and are removed from @watched[directory].
55902 previous.getChildren().filter((item) => {
55903 return item !== directory &&
55904 !current.has(item) &&
55905 // in case of intersecting globs;
55906 // a path may have been filtered out of this readdir, but
55907 // shouldn't be removed because it matches a different glob
55908 (!wh.hasGlob || wh.filterPath({
55909 fullPath: sysPath$2.resolve(directory, item)
55910 }));
55911 }).forEach((item) => {
55912 this.fsw._remove(directory, item);
55913 });
55914
55915 stream = undefined;
55916
55917 // one more time for any missed in case changes came in extremely quickly
55918 if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler);
55919 })
55920 );
55921}
55922
55923/**
55924 * Read directory to add / remove files from `@watched` list and re-read it on change.
55925 * @param {String} dir fs path
55926 * @param {fs.Stats} stats
55927 * @param {Boolean} initialAdd
55928 * @param {Number} depth relative to user-supplied path
55929 * @param {String} target child path targeted for watch
55930 * @param {Object} wh Common watch helpers for this path
55931 * @param {String} realpath
55932 * @returns {Promise<Function>} closer for the watcher instance.
55933 */
55934async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {
55935 const parentDir = this.fsw._getWatchedDir(sysPath$2.dirname(dir));
55936 const tracked = parentDir.has(sysPath$2.basename(dir));
55937 if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
55938 if (!wh.hasGlob || wh.globFilter(dir)) this.fsw._emit(EV_ADD_DIR$2, dir, stats);
55939 }
55940
55941 // ensure dir is tracked (harmless if redundant)
55942 parentDir.add(sysPath$2.basename(dir));
55943 this.fsw._getWatchedDir(dir);
55944 let throttler;
55945 let closer;
55946
55947 const oDepth = this.fsw.options.depth;
55948 if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {
55949 if (!target) {
55950 await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
55951 if (this.fsw.closed) return;
55952 }
55953
55954 closer = this._watchWithNodeFs(dir, (dirPath, stats) => {
55955 // if current directory is removed, do nothing
55956 if (stats && stats.mtimeMs === 0) return;
55957
55958 this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
55959 });
55960 }
55961 return closer;
55962}
55963
55964/**
55965 * Handle added file, directory, or glob pattern.
55966 * Delegates call to _handleFile / _handleDir after checks.
55967 * @param {String} path to file or ir
55968 * @param {Boolean} initialAdd was the file added at watch instantiation?
55969 * @param {Object} priorWh depth relative to user-supplied path
55970 * @param {Number} depth Child path actually targeted for watch
55971 * @param {String=} target Child path actually targeted for watch
55972 * @returns {Promise}
55973 */
55974async _addToNodeFs(path, initialAdd, priorWh, depth, target) {
55975 const ready = this.fsw._emitReady;
55976 if (this.fsw._isIgnored(path) || this.fsw.closed) {
55977 ready();
55978 return false;
55979 }
55980
55981 const wh = this.fsw._getWatchHelpers(path, depth);
55982 if (!wh.hasGlob && priorWh) {
55983 wh.hasGlob = priorWh.hasGlob;
55984 wh.globFilter = priorWh.globFilter;
55985 wh.filterPath = entry => priorWh.filterPath(entry);
55986 wh.filterDir = entry => priorWh.filterDir(entry);
55987 }
55988
55989 // evaluate what is at the path we're being asked to watch
55990 try {
55991 const stats = await statMethods$1[wh.statMethod](wh.watchPath);
55992 if (this.fsw.closed) return;
55993 if (this.fsw._isIgnored(wh.watchPath, stats)) {
55994 ready();
55995 return false;
55996 }
55997
55998 const follow = this.fsw.options.followSymlinks && !path.includes(STAR) && !path.includes(BRACE_START$1);
55999 let closer;
56000 if (stats.isDirectory()) {
56001 const absPath = sysPath$2.resolve(path);
56002 const targetPath = follow ? await fsrealpath(path) : path;
56003 if (this.fsw.closed) return;
56004 closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
56005 if (this.fsw.closed) return;
56006 // preserve this symlink's target path
56007 if (absPath !== targetPath && targetPath !== undefined) {
56008 this.fsw._symlinkPaths.set(absPath, targetPath);
56009 }
56010 } else if (stats.isSymbolicLink()) {
56011 const targetPath = follow ? await fsrealpath(path) : path;
56012 if (this.fsw.closed) return;
56013 const parent = sysPath$2.dirname(wh.watchPath);
56014 this.fsw._getWatchedDir(parent).add(wh.watchPath);
56015 this.fsw._emit(EV_ADD$2, wh.watchPath, stats);
56016 closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);
56017 if (this.fsw.closed) return;
56018
56019 // preserve this symlink's target path
56020 if (targetPath !== undefined) {
56021 this.fsw._symlinkPaths.set(sysPath$2.resolve(path), targetPath);
56022 }
56023 } else {
56024 closer = this._handleFile(wh.watchPath, stats, initialAdd);
56025 }
56026 ready();
56027
56028 this.fsw._addPathCloser(path, closer);
56029 return false;
56030
56031 } catch (error) {
56032 if (this.fsw._handleError(error)) {
56033 ready();
56034 return path;
56035 }
56036 }
56037}
56038
56039}
56040
56041var nodefsHandler = NodeFsHandler$1;
56042
56043var fseventsHandler = {exports: {}};
56044
56045const fs$9 = fs__default;
56046const sysPath$1 = path__default;
56047const { promisify: promisify$2 } = require$$0__default$3;
56048
56049let fsevents;
56050try {
56051 fsevents = eval('require')('fsevents');
56052} catch (error) {
56053 if (process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR) console.error(error);
56054}
56055
56056if (fsevents) {
56057 // TODO: real check
56058 const mtch = process.version.match(/v(\d+)\.(\d+)/);
56059 if (mtch && mtch[1] && mtch[2]) {
56060 const maj = Number.parseInt(mtch[1], 10);
56061 const min = Number.parseInt(mtch[2], 10);
56062 if (maj === 8 && min < 16) {
56063 fsevents = undefined;
56064 }
56065 }
56066}
56067
56068const {
56069 EV_ADD: EV_ADD$1,
56070 EV_CHANGE: EV_CHANGE$1,
56071 EV_ADD_DIR: EV_ADD_DIR$1,
56072 EV_UNLINK: EV_UNLINK$1,
56073 EV_ERROR: EV_ERROR$1,
56074 STR_DATA,
56075 STR_END: STR_END$1,
56076 FSEVENT_CREATED,
56077 FSEVENT_MODIFIED,
56078 FSEVENT_DELETED,
56079 FSEVENT_MOVED,
56080 // FSEVENT_CLONED,
56081 FSEVENT_UNKNOWN,
56082 FSEVENT_TYPE_FILE,
56083 FSEVENT_TYPE_DIRECTORY,
56084 FSEVENT_TYPE_SYMLINK,
56085
56086 ROOT_GLOBSTAR,
56087 DIR_SUFFIX,
56088 DOT_SLASH,
56089 FUNCTION_TYPE: FUNCTION_TYPE$1,
56090 EMPTY_FN: EMPTY_FN$1,
56091 IDENTITY_FN
56092} = constants$1;
56093
56094const Depth = (value) => isNaN(value) ? {} : {depth: value};
56095
56096const stat$1 = promisify$2(fs$9.stat);
56097const lstat = promisify$2(fs$9.lstat);
56098const realpath = promisify$2(fs$9.realpath);
56099
56100const statMethods = { stat: stat$1, lstat };
56101
56102/**
56103 * @typedef {String} Path
56104 */
56105
56106/**
56107 * @typedef {Object} FsEventsWatchContainer
56108 * @property {Set<Function>} listeners
56109 * @property {Function} rawEmitter
56110 * @property {{stop: Function}} watcher
56111 */
56112
56113// fsevents instance helper functions
56114/**
56115 * Object to hold per-process fsevents instances (may be shared across chokidar FSWatcher instances)
56116 * @type {Map<Path,FsEventsWatchContainer>}
56117 */
56118const FSEventsWatchers = new Map();
56119
56120// Threshold of duplicate path prefixes at which to start
56121// consolidating going forward
56122const consolidateThreshhold = 10;
56123
56124const wrongEventFlags = new Set([
56125 69888, 70400, 71424, 72704, 73472, 131328, 131840, 262912
56126]);
56127
56128/**
56129 * Instantiates the fsevents interface
56130 * @param {Path} path path to be watched
56131 * @param {Function} callback called when fsevents is bound and ready
56132 * @returns {{stop: Function}} new fsevents instance
56133 */
56134const createFSEventsInstance = (path, callback) => {
56135 const stop = fsevents.watch(path, callback);
56136 return {stop};
56137};
56138
56139/**
56140 * Instantiates the fsevents interface or binds listeners to an existing one covering
56141 * the same file tree.
56142 * @param {Path} path - to be watched
56143 * @param {Path} realPath - real path for symlinks
56144 * @param {Function} listener - called when fsevents emits events
56145 * @param {Function} rawEmitter - passes data to listeners of the 'raw' event
56146 * @returns {Function} closer
56147 */
56148function setFSEventsListener(path, realPath, listener, rawEmitter) {
56149 let watchPath = sysPath$1.extname(realPath) ? sysPath$1.dirname(realPath) : realPath;
56150
56151 const parentPath = sysPath$1.dirname(watchPath);
56152 let cont = FSEventsWatchers.get(watchPath);
56153
56154 // If we've accumulated a substantial number of paths that
56155 // could have been consolidated by watching one directory
56156 // above the current one, create a watcher on the parent
56157 // path instead, so that we do consolidate going forward.
56158 if (couldConsolidate(parentPath)) {
56159 watchPath = parentPath;
56160 }
56161
56162 const resolvedPath = sysPath$1.resolve(path);
56163 const hasSymlink = resolvedPath !== realPath;
56164
56165 const filteredListener = (fullPath, flags, info) => {
56166 if (hasSymlink) fullPath = fullPath.replace(realPath, resolvedPath);
56167 if (
56168 fullPath === resolvedPath ||
56169 !fullPath.indexOf(resolvedPath + sysPath$1.sep)
56170 ) listener(fullPath, flags, info);
56171 };
56172
56173 // check if there is already a watcher on a parent path
56174 // modifies `watchPath` to the parent path when it finds a match
56175 let watchedParent = false;
56176 for (const watchedPath of FSEventsWatchers.keys()) {
56177 if (realPath.indexOf(sysPath$1.resolve(watchedPath) + sysPath$1.sep) === 0) {
56178 watchPath = watchedPath;
56179 cont = FSEventsWatchers.get(watchPath);
56180 watchedParent = true;
56181 break;
56182 }
56183 }
56184
56185 if (cont || watchedParent) {
56186 cont.listeners.add(filteredListener);
56187 } else {
56188 cont = {
56189 listeners: new Set([filteredListener]),
56190 rawEmitter,
56191 watcher: createFSEventsInstance(watchPath, (fullPath, flags) => {
56192 if (!cont.listeners.size) return;
56193 const info = fsevents.getInfo(fullPath, flags);
56194 cont.listeners.forEach(list => {
56195 list(fullPath, flags, info);
56196 });
56197
56198 cont.rawEmitter(info.event, fullPath, info);
56199 })
56200 };
56201 FSEventsWatchers.set(watchPath, cont);
56202 }
56203
56204 // removes this instance's listeners and closes the underlying fsevents
56205 // instance if there are no more listeners left
56206 return () => {
56207 const lst = cont.listeners;
56208
56209 lst.delete(filteredListener);
56210 if (!lst.size) {
56211 FSEventsWatchers.delete(watchPath);
56212 if (cont.watcher) return cont.watcher.stop().then(() => {
56213 cont.rawEmitter = cont.watcher = undefined;
56214 Object.freeze(cont);
56215 });
56216 }
56217 };
56218}
56219
56220// Decide whether or not we should start a new higher-level
56221// parent watcher
56222const couldConsolidate = (path) => {
56223 let count = 0;
56224 for (const watchPath of FSEventsWatchers.keys()) {
56225 if (watchPath.indexOf(path) === 0) {
56226 count++;
56227 if (count >= consolidateThreshhold) {
56228 return true;
56229 }
56230 }
56231 }
56232
56233 return false;
56234};
56235
56236// returns boolean indicating whether fsevents can be used
56237const canUse = () => fsevents && FSEventsWatchers.size < 128;
56238
56239// determines subdirectory traversal levels from root to path
56240const calcDepth = (path, root) => {
56241 let i = 0;
56242 while (!path.indexOf(root) && (path = sysPath$1.dirname(path)) !== root) i++;
56243 return i;
56244};
56245
56246// returns boolean indicating whether the fsevents' event info has the same type
56247// as the one returned by fs.stat
56248const sameTypes = (info, stats) => (
56249 info.type === FSEVENT_TYPE_DIRECTORY && stats.isDirectory() ||
56250 info.type === FSEVENT_TYPE_SYMLINK && stats.isSymbolicLink() ||
56251 info.type === FSEVENT_TYPE_FILE && stats.isFile()
56252);
56253
56254/**
56255 * @mixin
56256 */
56257class FsEventsHandler$1 {
56258
56259/**
56260 * @param {import('../index').FSWatcher} fsw
56261 */
56262constructor(fsw) {
56263 this.fsw = fsw;
56264}
56265checkIgnored(path, stats) {
56266 const ipaths = this.fsw._ignoredPaths;
56267 if (this.fsw._isIgnored(path, stats)) {
56268 ipaths.add(path);
56269 if (stats && stats.isDirectory()) {
56270 ipaths.add(path + ROOT_GLOBSTAR);
56271 }
56272 return true;
56273 }
56274
56275 ipaths.delete(path);
56276 ipaths.delete(path + ROOT_GLOBSTAR);
56277}
56278
56279addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
56280 const event = watchedDir.has(item) ? EV_CHANGE$1 : EV_ADD$1;
56281 this.handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts);
56282}
56283
56284async checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
56285 try {
56286 const stats = await stat$1(path);
56287 if (this.fsw.closed) return;
56288 if (sameTypes(info, stats)) {
56289 this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
56290 } else {
56291 this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
56292 }
56293 } catch (error) {
56294 if (error.code === 'EACCES') {
56295 this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
56296 } else {
56297 this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
56298 }
56299 }
56300}
56301
56302handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts) {
56303 if (this.fsw.closed || this.checkIgnored(path)) return;
56304
56305 if (event === EV_UNLINK$1) {
56306 const isDirectory = info.type === FSEVENT_TYPE_DIRECTORY;
56307 // suppress unlink events on never before seen files
56308 if (isDirectory || watchedDir.has(item)) {
56309 this.fsw._remove(parent, item, isDirectory);
56310 }
56311 } else {
56312 if (event === EV_ADD$1) {
56313 // track new directories
56314 if (info.type === FSEVENT_TYPE_DIRECTORY) this.fsw._getWatchedDir(path);
56315
56316 if (info.type === FSEVENT_TYPE_SYMLINK && opts.followSymlinks) {
56317 // push symlinks back to the top of the stack to get handled
56318 const curDepth = opts.depth === undefined ?
56319 undefined : calcDepth(fullPath, realPath) + 1;
56320 return this._addToFsEvents(path, false, true, curDepth);
56321 }
56322
56323 // track new paths
56324 // (other than symlinks being followed, which will be tracked soon)
56325 this.fsw._getWatchedDir(parent).add(item);
56326 }
56327 /**
56328 * @type {'add'|'addDir'|'unlink'|'unlinkDir'}
56329 */
56330 const eventName = info.type === FSEVENT_TYPE_DIRECTORY ? event + DIR_SUFFIX : event;
56331 this.fsw._emit(eventName, path);
56332 if (eventName === EV_ADD_DIR$1) this._addToFsEvents(path, false, true);
56333 }
56334}
56335
56336/**
56337 * Handle symlinks encountered during directory scan
56338 * @param {String} watchPath - file/dir path to be watched with fsevents
56339 * @param {String} realPath - real path (in case of symlinks)
56340 * @param {Function} transform - path transformer
56341 * @param {Function} globFilter - path filter in case a glob pattern was provided
56342 * @returns {Function} closer for the watcher instance
56343*/
56344_watchWithFsEvents(watchPath, realPath, transform, globFilter) {
56345 if (this.fsw.closed || this.fsw._isIgnored(watchPath)) return;
56346 const opts = this.fsw.options;
56347 const watchCallback = async (fullPath, flags, info) => {
56348 if (this.fsw.closed) return;
56349 if (
56350 opts.depth !== undefined &&
56351 calcDepth(fullPath, realPath) > opts.depth
56352 ) return;
56353 const path = transform(sysPath$1.join(
56354 watchPath, sysPath$1.relative(watchPath, fullPath)
56355 ));
56356 if (globFilter && !globFilter(path)) return;
56357 // ensure directories are tracked
56358 const parent = sysPath$1.dirname(path);
56359 const item = sysPath$1.basename(path);
56360 const watchedDir = this.fsw._getWatchedDir(
56361 info.type === FSEVENT_TYPE_DIRECTORY ? path : parent
56362 );
56363
56364 // correct for wrong events emitted
56365 if (wrongEventFlags.has(flags) || info.event === FSEVENT_UNKNOWN) {
56366 if (typeof opts.ignored === FUNCTION_TYPE$1) {
56367 let stats;
56368 try {
56369 stats = await stat$1(path);
56370 } catch (error) {}
56371 if (this.fsw.closed) return;
56372 if (this.checkIgnored(path, stats)) return;
56373 if (sameTypes(info, stats)) {
56374 this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
56375 } else {
56376 this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
56377 }
56378 } else {
56379 this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
56380 }
56381 } else {
56382 switch (info.event) {
56383 case FSEVENT_CREATED:
56384 case FSEVENT_MODIFIED:
56385 return this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
56386 case FSEVENT_DELETED:
56387 case FSEVENT_MOVED:
56388 return this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
56389 }
56390 }
56391 };
56392
56393 const closer = setFSEventsListener(
56394 watchPath,
56395 realPath,
56396 watchCallback,
56397 this.fsw._emitRaw
56398 );
56399
56400 this.fsw._emitReady();
56401 return closer;
56402}
56403
56404/**
56405 * Handle symlinks encountered during directory scan
56406 * @param {String} linkPath path to symlink
56407 * @param {String} fullPath absolute path to the symlink
56408 * @param {Function} transform pre-existing path transformer
56409 * @param {Number} curDepth level of subdirectories traversed to where symlink is
56410 * @returns {Promise<void>}
56411 */
56412async _handleFsEventsSymlink(linkPath, fullPath, transform, curDepth) {
56413 // don't follow the same symlink more than once
56414 if (this.fsw.closed || this.fsw._symlinkPaths.has(fullPath)) return;
56415
56416 this.fsw._symlinkPaths.set(fullPath, true);
56417 this.fsw._incrReadyCount();
56418
56419 try {
56420 const linkTarget = await realpath(linkPath);
56421 if (this.fsw.closed) return;
56422 if (this.fsw._isIgnored(linkTarget)) {
56423 return this.fsw._emitReady();
56424 }
56425
56426 this.fsw._incrReadyCount();
56427
56428 // add the linkTarget for watching with a wrapper for transform
56429 // that causes emitted paths to incorporate the link's path
56430 this._addToFsEvents(linkTarget || linkPath, (path) => {
56431 let aliasedPath = linkPath;
56432 if (linkTarget && linkTarget !== DOT_SLASH) {
56433 aliasedPath = path.replace(linkTarget, linkPath);
56434 } else if (path !== DOT_SLASH) {
56435 aliasedPath = sysPath$1.join(linkPath, path);
56436 }
56437 return transform(aliasedPath);
56438 }, false, curDepth);
56439 } catch(error) {
56440 if (this.fsw._handleError(error)) {
56441 return this.fsw._emitReady();
56442 }
56443 }
56444}
56445
56446/**
56447 *
56448 * @param {Path} newPath
56449 * @param {fs.Stats} stats
56450 */
56451emitAdd(newPath, stats, processPath, opts, forceAdd) {
56452 const pp = processPath(newPath);
56453 const isDir = stats.isDirectory();
56454 const dirObj = this.fsw._getWatchedDir(sysPath$1.dirname(pp));
56455 const base = sysPath$1.basename(pp);
56456
56457 // ensure empty dirs get tracked
56458 if (isDir) this.fsw._getWatchedDir(pp);
56459 if (dirObj.has(base)) return;
56460 dirObj.add(base);
56461
56462 if (!opts.ignoreInitial || forceAdd === true) {
56463 this.fsw._emit(isDir ? EV_ADD_DIR$1 : EV_ADD$1, pp, stats);
56464 }
56465}
56466
56467initWatch(realPath, path, wh, processPath) {
56468 if (this.fsw.closed) return;
56469 const closer = this._watchWithFsEvents(
56470 wh.watchPath,
56471 sysPath$1.resolve(realPath || wh.watchPath),
56472 processPath,
56473 wh.globFilter
56474 );
56475 this.fsw._addPathCloser(path, closer);
56476}
56477
56478/**
56479 * Handle added path with fsevents
56480 * @param {String} path file/dir path or glob pattern
56481 * @param {Function|Boolean=} transform converts working path to what the user expects
56482 * @param {Boolean=} forceAdd ensure add is emitted
56483 * @param {Number=} priorDepth Level of subdirectories already traversed.
56484 * @returns {Promise<void>}
56485 */
56486async _addToFsEvents(path, transform, forceAdd, priorDepth) {
56487 if (this.fsw.closed) {
56488 return;
56489 }
56490 const opts = this.fsw.options;
56491 const processPath = typeof transform === FUNCTION_TYPE$1 ? transform : IDENTITY_FN;
56492
56493 const wh = this.fsw._getWatchHelpers(path);
56494
56495 // evaluate what is at the path we're being asked to watch
56496 try {
56497 const stats = await statMethods[wh.statMethod](wh.watchPath);
56498 if (this.fsw.closed) return;
56499 if (this.fsw._isIgnored(wh.watchPath, stats)) {
56500 throw null;
56501 }
56502 if (stats.isDirectory()) {
56503 // emit addDir unless this is a glob parent
56504 if (!wh.globFilter) this.emitAdd(processPath(path), stats, processPath, opts, forceAdd);
56505
56506 // don't recurse further if it would exceed depth setting
56507 if (priorDepth && priorDepth > opts.depth) return;
56508
56509 // scan the contents of the dir
56510 this.fsw._readdirp(wh.watchPath, {
56511 fileFilter: entry => wh.filterPath(entry),
56512 directoryFilter: entry => wh.filterDir(entry),
56513 ...Depth(opts.depth - (priorDepth || 0))
56514 }).on(STR_DATA, (entry) => {
56515 // need to check filterPath on dirs b/c filterDir is less restrictive
56516 if (this.fsw.closed) {
56517 return;
56518 }
56519 if (entry.stats.isDirectory() && !wh.filterPath(entry)) return;
56520
56521 const joinedPath = sysPath$1.join(wh.watchPath, entry.path);
56522 const {fullPath} = entry;
56523
56524 if (wh.followSymlinks && entry.stats.isSymbolicLink()) {
56525 // preserve the current depth here since it can't be derived from
56526 // real paths past the symlink
56527 const curDepth = opts.depth === undefined ?
56528 undefined : calcDepth(joinedPath, sysPath$1.resolve(wh.watchPath)) + 1;
56529
56530 this._handleFsEventsSymlink(joinedPath, fullPath, processPath, curDepth);
56531 } else {
56532 this.emitAdd(joinedPath, entry.stats, processPath, opts, forceAdd);
56533 }
56534 }).on(EV_ERROR$1, EMPTY_FN$1).on(STR_END$1, () => {
56535 this.fsw._emitReady();
56536 });
56537 } else {
56538 this.emitAdd(wh.watchPath, stats, processPath, opts, forceAdd);
56539 this.fsw._emitReady();
56540 }
56541 } catch (error) {
56542 if (!error || this.fsw._handleError(error)) {
56543 // TODO: Strange thing: "should not choke on an ignored watch path" will be failed without 2 ready calls -__-
56544 this.fsw._emitReady();
56545 this.fsw._emitReady();
56546 }
56547 }
56548
56549 if (opts.persistent && forceAdd !== true) {
56550 if (typeof transform === FUNCTION_TYPE$1) {
56551 // realpath has already been resolved
56552 this.initWatch(undefined, path, wh, processPath);
56553 } else {
56554 let realPath;
56555 try {
56556 realPath = await realpath(wh.watchPath);
56557 } catch (e) {}
56558 this.initWatch(realPath, path, wh, processPath);
56559 }
56560 }
56561}
56562
56563}
56564
56565fseventsHandler.exports = FsEventsHandler$1;
56566fseventsHandler.exports.canUse = canUse;
56567
56568const { EventEmitter: EventEmitter$2 } = require$$0__default$6;
56569const fs$8 = fs__default;
56570const sysPath = path__default;
56571const { promisify: promisify$1 } = require$$0__default$3;
56572const readdirp = readdirp_1;
56573const anymatch = anymatch$2.exports.default;
56574const globParent = globParent$3;
56575const isGlob = isGlob$2;
56576const braces = braces_1;
56577const normalizePath = normalizePath$2;
56578
56579const NodeFsHandler = nodefsHandler;
56580const FsEventsHandler = fseventsHandler.exports;
56581const {
56582 EV_ALL,
56583 EV_READY,
56584 EV_ADD,
56585 EV_CHANGE,
56586 EV_UNLINK,
56587 EV_ADD_DIR,
56588 EV_UNLINK_DIR,
56589 EV_RAW,
56590 EV_ERROR,
56591
56592 STR_CLOSE,
56593 STR_END,
56594
56595 BACK_SLASH_RE,
56596 DOUBLE_SLASH_RE,
56597 SLASH_OR_BACK_SLASH_RE,
56598 DOT_RE,
56599 REPLACER_RE,
56600
56601 SLASH,
56602 SLASH_SLASH,
56603 BRACE_START,
56604 BANG,
56605 ONE_DOT,
56606 TWO_DOTS,
56607 GLOBSTAR,
56608 SLASH_GLOBSTAR,
56609 ANYMATCH_OPTS,
56610 STRING_TYPE,
56611 FUNCTION_TYPE,
56612 EMPTY_STR,
56613 EMPTY_FN,
56614
56615 isWindows: isWindows$1,
56616 isMacos,
56617 isIBMi
56618} = constants$1;
56619
56620const stat = promisify$1(fs$8.stat);
56621const readdir = promisify$1(fs$8.readdir);
56622
56623/**
56624 * @typedef {String} Path
56625 * @typedef {'all'|'add'|'addDir'|'change'|'unlink'|'unlinkDir'|'raw'|'error'|'ready'} EventName
56626 * @typedef {'readdir'|'watch'|'add'|'remove'|'change'} ThrottleType
56627 */
56628
56629/**
56630 *
56631 * @typedef {Object} WatchHelpers
56632 * @property {Boolean} followSymlinks
56633 * @property {'stat'|'lstat'} statMethod
56634 * @property {Path} path
56635 * @property {Path} watchPath
56636 * @property {Function} entryPath
56637 * @property {Boolean} hasGlob
56638 * @property {Object} globFilter
56639 * @property {Function} filterPath
56640 * @property {Function} filterDir
56641 */
56642
56643const arrify = (value = []) => Array.isArray(value) ? value : [value];
56644const flatten = (list, result = []) => {
56645 list.forEach(item => {
56646 if (Array.isArray(item)) {
56647 flatten(item, result);
56648 } else {
56649 result.push(item);
56650 }
56651 });
56652 return result;
56653};
56654
56655const unifyPaths = (paths_) => {
56656 /**
56657 * @type {Array<String>}
56658 */
56659 const paths = flatten(arrify(paths_));
56660 if (!paths.every(p => typeof p === STRING_TYPE)) {
56661 throw new TypeError(`Non-string provided as watch path: ${paths}`);
56662 }
56663 return paths.map(normalizePathToUnix);
56664};
56665
56666// If SLASH_SLASH occurs at the beginning of path, it is not replaced
56667// because "//StoragePC/DrivePool/Movies" is a valid network path
56668const toUnix = (string) => {
56669 let str = string.replace(BACK_SLASH_RE, SLASH);
56670 let prepend = false;
56671 if (str.startsWith(SLASH_SLASH)) {
56672 prepend = true;
56673 }
56674 while (str.match(DOUBLE_SLASH_RE)) {
56675 str = str.replace(DOUBLE_SLASH_RE, SLASH);
56676 }
56677 if (prepend) {
56678 str = SLASH + str;
56679 }
56680 return str;
56681};
56682
56683// Our version of upath.normalize
56684// TODO: this is not equal to path-normalize module - investigate why
56685const normalizePathToUnix = (path) => toUnix(sysPath.normalize(toUnix(path)));
56686
56687const normalizeIgnored = (cwd = EMPTY_STR) => (path) => {
56688 if (typeof path !== STRING_TYPE) return path;
56689 return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path));
56690};
56691
56692const getAbsolutePath = (path, cwd) => {
56693 if (sysPath.isAbsolute(path)) {
56694 return path;
56695 }
56696 if (path.startsWith(BANG)) {
56697 return BANG + sysPath.join(cwd, path.slice(1));
56698 }
56699 return sysPath.join(cwd, path);
56700};
56701
56702const undef = (opts, key) => opts[key] === undefined;
56703
56704/**
56705 * Directory entry.
56706 * @property {Path} path
56707 * @property {Set<Path>} items
56708 */
56709class DirEntry {
56710 /**
56711 * @param {Path} dir
56712 * @param {Function} removeWatcher
56713 */
56714 constructor(dir, removeWatcher) {
56715 this.path = dir;
56716 this._removeWatcher = removeWatcher;
56717 /** @type {Set<Path>} */
56718 this.items = new Set();
56719 }
56720
56721 add(item) {
56722 const {items} = this;
56723 if (!items) return;
56724 if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item);
56725 }
56726
56727 async remove(item) {
56728 const {items} = this;
56729 if (!items) return;
56730 items.delete(item);
56731 if (items.size > 0) return;
56732
56733 const dir = this.path;
56734 try {
56735 await readdir(dir);
56736 } catch (err) {
56737 if (this._removeWatcher) {
56738 this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir));
56739 }
56740 }
56741 }
56742
56743 has(item) {
56744 const {items} = this;
56745 if (!items) return;
56746 return items.has(item);
56747 }
56748
56749 /**
56750 * @returns {Array<String>}
56751 */
56752 getChildren() {
56753 const {items} = this;
56754 if (!items) return;
56755 return [...items.values()];
56756 }
56757
56758 dispose() {
56759 this.items.clear();
56760 delete this.path;
56761 delete this._removeWatcher;
56762 delete this.items;
56763 Object.freeze(this);
56764 }
56765}
56766
56767const STAT_METHOD_F = 'stat';
56768const STAT_METHOD_L = 'lstat';
56769class WatchHelper {
56770 constructor(path, watchPath, follow, fsw) {
56771 this.fsw = fsw;
56772 this.path = path = path.replace(REPLACER_RE, EMPTY_STR);
56773 this.watchPath = watchPath;
56774 this.fullWatchPath = sysPath.resolve(watchPath);
56775 this.hasGlob = watchPath !== path;
56776 /** @type {object|boolean} */
56777 if (path === EMPTY_STR) this.hasGlob = false;
56778 this.globSymlink = this.hasGlob && follow ? undefined : false;
56779 this.globFilter = this.hasGlob ? anymatch(path, undefined, ANYMATCH_OPTS) : false;
56780 this.dirParts = this.getDirParts(path);
56781 this.dirParts.forEach((parts) => {
56782 if (parts.length > 1) parts.pop();
56783 });
56784 this.followSymlinks = follow;
56785 this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
56786 }
56787
56788 checkGlobSymlink(entry) {
56789 // only need to resolve once
56790 // first entry should always have entry.parentDir === EMPTY_STR
56791 if (this.globSymlink === undefined) {
56792 this.globSymlink = entry.fullParentDir === this.fullWatchPath ?
56793 false : {realPath: entry.fullParentDir, linkPath: this.fullWatchPath};
56794 }
56795
56796 if (this.globSymlink) {
56797 return entry.fullPath.replace(this.globSymlink.realPath, this.globSymlink.linkPath);
56798 }
56799
56800 return entry.fullPath;
56801 }
56802
56803 entryPath(entry) {
56804 return sysPath.join(this.watchPath,
56805 sysPath.relative(this.watchPath, this.checkGlobSymlink(entry))
56806 );
56807 }
56808
56809 filterPath(entry) {
56810 const {stats} = entry;
56811 if (stats && stats.isSymbolicLink()) return this.filterDir(entry);
56812 const resolvedPath = this.entryPath(entry);
56813 const matchesGlob = this.hasGlob && typeof this.globFilter === FUNCTION_TYPE ?
56814 this.globFilter(resolvedPath) : true;
56815 return matchesGlob &&
56816 this.fsw._isntIgnored(resolvedPath, stats) &&
56817 this.fsw._hasReadPermissions(stats);
56818 }
56819
56820 getDirParts(path) {
56821 if (!this.hasGlob) return [];
56822 const parts = [];
56823 const expandedPath = path.includes(BRACE_START) ? braces.expand(path) : [path];
56824 expandedPath.forEach((path) => {
56825 parts.push(sysPath.relative(this.watchPath, path).split(SLASH_OR_BACK_SLASH_RE));
56826 });
56827 return parts;
56828 }
56829
56830 filterDir(entry) {
56831 if (this.hasGlob) {
56832 const entryParts = this.getDirParts(this.checkGlobSymlink(entry));
56833 let globstar = false;
56834 this.unmatchedGlob = !this.dirParts.some((parts) => {
56835 return parts.every((part, i) => {
56836 if (part === GLOBSTAR) globstar = true;
56837 return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i], ANYMATCH_OPTS);
56838 });
56839 });
56840 }
56841 return !this.unmatchedGlob && this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
56842 }
56843}
56844
56845/**
56846 * Watches files & directories for changes. Emitted events:
56847 * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
56848 *
56849 * new FSWatcher()
56850 * .add(directories)
56851 * .on('add', path => log('File', path, 'was added'))
56852 */
56853class FSWatcher extends EventEmitter$2 {
56854// Not indenting methods for history sake; for now.
56855constructor(_opts) {
56856 super();
56857
56858 const opts = {};
56859 if (_opts) Object.assign(opts, _opts); // for frozen objects
56860
56861 /** @type {Map<String, DirEntry>} */
56862 this._watched = new Map();
56863 /** @type {Map<String, Array>} */
56864 this._closers = new Map();
56865 /** @type {Set<String>} */
56866 this._ignoredPaths = new Set();
56867
56868 /** @type {Map<ThrottleType, Map>} */
56869 this._throttled = new Map();
56870
56871 /** @type {Map<Path, String|Boolean>} */
56872 this._symlinkPaths = new Map();
56873
56874 this._streams = new Set();
56875 this.closed = false;
56876
56877 // Set up default options.
56878 if (undef(opts, 'persistent')) opts.persistent = true;
56879 if (undef(opts, 'ignoreInitial')) opts.ignoreInitial = false;
56880 if (undef(opts, 'ignorePermissionErrors')) opts.ignorePermissionErrors = false;
56881 if (undef(opts, 'interval')) opts.interval = 100;
56882 if (undef(opts, 'binaryInterval')) opts.binaryInterval = 300;
56883 if (undef(opts, 'disableGlobbing')) opts.disableGlobbing = false;
56884 opts.enableBinaryInterval = opts.binaryInterval !== opts.interval;
56885
56886 // Enable fsevents on OS X when polling isn't explicitly enabled.
56887 if (undef(opts, 'useFsEvents')) opts.useFsEvents = !opts.usePolling;
56888
56889 // If we can't use fsevents, ensure the options reflect it's disabled.
56890 const canUseFsEvents = FsEventsHandler.canUse();
56891 if (!canUseFsEvents) opts.useFsEvents = false;
56892
56893 // Use polling on Mac if not using fsevents.
56894 // Other platforms use non-polling fs_watch.
56895 if (undef(opts, 'usePolling') && !opts.useFsEvents) {
56896 opts.usePolling = isMacos;
56897 }
56898
56899 // Always default to polling on IBM i because fs.watch() is not available on IBM i.
56900 if(isIBMi) {
56901 opts.usePolling = true;
56902 }
56903
56904 // Global override (useful for end-developers that need to force polling for all
56905 // instances of chokidar, regardless of usage/dependency depth)
56906 const envPoll = process.env.CHOKIDAR_USEPOLLING;
56907 if (envPoll !== undefined) {
56908 const envLower = envPoll.toLowerCase();
56909
56910 if (envLower === 'false' || envLower === '0') {
56911 opts.usePolling = false;
56912 } else if (envLower === 'true' || envLower === '1') {
56913 opts.usePolling = true;
56914 } else {
56915 opts.usePolling = !!envLower;
56916 }
56917 }
56918 const envInterval = process.env.CHOKIDAR_INTERVAL;
56919 if (envInterval) {
56920 opts.interval = Number.parseInt(envInterval, 10);
56921 }
56922
56923 // Editor atomic write normalization enabled by default with fs.watch
56924 if (undef(opts, 'atomic')) opts.atomic = !opts.usePolling && !opts.useFsEvents;
56925 if (opts.atomic) this._pendingUnlinks = new Map();
56926
56927 if (undef(opts, 'followSymlinks')) opts.followSymlinks = true;
56928
56929 if (undef(opts, 'awaitWriteFinish')) opts.awaitWriteFinish = false;
56930 if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {};
56931 const awf = opts.awaitWriteFinish;
56932 if (awf) {
56933 if (!awf.stabilityThreshold) awf.stabilityThreshold = 2000;
56934 if (!awf.pollInterval) awf.pollInterval = 100;
56935 this._pendingWrites = new Map();
56936 }
56937 if (opts.ignored) opts.ignored = arrify(opts.ignored);
56938
56939 let readyCalls = 0;
56940 this._emitReady = () => {
56941 readyCalls++;
56942 if (readyCalls >= this._readyCount) {
56943 this._emitReady = EMPTY_FN;
56944 this._readyEmitted = true;
56945 // use process.nextTick to allow time for listener to be bound
56946 process.nextTick(() => this.emit(EV_READY));
56947 }
56948 };
56949 this._emitRaw = (...args) => this.emit(EV_RAW, ...args);
56950 this._readyEmitted = false;
56951 this.options = opts;
56952
56953 // Initialize with proper watcher.
56954 if (opts.useFsEvents) {
56955 this._fsEventsHandler = new FsEventsHandler(this);
56956 } else {
56957 this._nodeFsHandler = new NodeFsHandler(this);
56958 }
56959
56960 // You’re frozen when your heart’s not open.
56961 Object.freeze(opts);
56962}
56963
56964// Public methods
56965
56966/**
56967 * Adds paths to be watched on an existing FSWatcher instance
56968 * @param {Path|Array<Path>} paths_
56969 * @param {String=} _origAdd private; for handling non-existent paths to be watched
56970 * @param {Boolean=} _internal private; indicates a non-user add
56971 * @returns {FSWatcher} for chaining
56972 */
56973add(paths_, _origAdd, _internal) {
56974 const {cwd, disableGlobbing} = this.options;
56975 this.closed = false;
56976 let paths = unifyPaths(paths_);
56977 if (cwd) {
56978 paths = paths.map((path) => {
56979 const absPath = getAbsolutePath(path, cwd);
56980
56981 // Check `path` instead of `absPath` because the cwd portion can't be a glob
56982 if (disableGlobbing || !isGlob(path)) {
56983 return absPath;
56984 }
56985 return normalizePath(absPath);
56986 });
56987 }
56988
56989 // set aside negated glob strings
56990 paths = paths.filter((path) => {
56991 if (path.startsWith(BANG)) {
56992 this._ignoredPaths.add(path.slice(1));
56993 return false;
56994 }
56995
56996 // if a path is being added that was previously ignored, stop ignoring it
56997 this._ignoredPaths.delete(path);
56998 this._ignoredPaths.delete(path + SLASH_GLOBSTAR);
56999
57000 // reset the cached userIgnored anymatch fn
57001 // to make ignoredPaths changes effective
57002 this._userIgnored = undefined;
57003
57004 return true;
57005 });
57006
57007 if (this.options.useFsEvents && this._fsEventsHandler) {
57008 if (!this._readyCount) this._readyCount = paths.length;
57009 if (this.options.persistent) this._readyCount *= 2;
57010 paths.forEach((path) => this._fsEventsHandler._addToFsEvents(path));
57011 } else {
57012 if (!this._readyCount) this._readyCount = 0;
57013 this._readyCount += paths.length;
57014 Promise.all(
57015 paths.map(async path => {
57016 const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, 0, 0, _origAdd);
57017 if (res) this._emitReady();
57018 return res;
57019 })
57020 ).then(results => {
57021 if (this.closed) return;
57022 results.filter(item => item).forEach(item => {
57023 this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));
57024 });
57025 });
57026 }
57027
57028 return this;
57029}
57030
57031/**
57032 * Close watchers or start ignoring events from specified paths.
57033 * @param {Path|Array<Path>} paths_ - string or array of strings, file/directory paths and/or globs
57034 * @returns {FSWatcher} for chaining
57035*/
57036unwatch(paths_) {
57037 if (this.closed) return this;
57038 const paths = unifyPaths(paths_);
57039 const {cwd} = this.options;
57040
57041 paths.forEach((path) => {
57042 // convert to absolute path unless relative path already matches
57043 if (!sysPath.isAbsolute(path) && !this._closers.has(path)) {
57044 if (cwd) path = sysPath.join(cwd, path);
57045 path = sysPath.resolve(path);
57046 }
57047
57048 this._closePath(path);
57049
57050 this._ignoredPaths.add(path);
57051 if (this._watched.has(path)) {
57052 this._ignoredPaths.add(path + SLASH_GLOBSTAR);
57053 }
57054
57055 // reset the cached userIgnored anymatch fn
57056 // to make ignoredPaths changes effective
57057 this._userIgnored = undefined;
57058 });
57059
57060 return this;
57061}
57062
57063/**
57064 * Close watchers and remove all listeners from watched paths.
57065 * @returns {Promise<void>}.
57066*/
57067close() {
57068 if (this.closed) return this._closePromise;
57069 this.closed = true;
57070
57071 // Memory management.
57072 this.removeAllListeners();
57073 const closers = [];
57074 this._closers.forEach(closerList => closerList.forEach(closer => {
57075 const promise = closer();
57076 if (promise instanceof Promise) closers.push(promise);
57077 }));
57078 this._streams.forEach(stream => stream.destroy());
57079 this._userIgnored = undefined;
57080 this._readyCount = 0;
57081 this._readyEmitted = false;
57082 this._watched.forEach(dirent => dirent.dispose());
57083 ['closers', 'watched', 'streams', 'symlinkPaths', 'throttled'].forEach(key => {
57084 this[`_${key}`].clear();
57085 });
57086
57087 this._closePromise = closers.length ? Promise.all(closers).then(() => undefined) : Promise.resolve();
57088 return this._closePromise;
57089}
57090
57091/**
57092 * Expose list of watched paths
57093 * @returns {Object} for chaining
57094*/
57095getWatched() {
57096 const watchList = {};
57097 this._watched.forEach((entry, dir) => {
57098 const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir;
57099 watchList[key || ONE_DOT] = entry.getChildren().sort();
57100 });
57101 return watchList;
57102}
57103
57104emitWithAll(event, args) {
57105 this.emit(...args);
57106 if (event !== EV_ERROR) this.emit(EV_ALL, ...args);
57107}
57108
57109// Common helpers
57110// --------------
57111
57112/**
57113 * Normalize and emit events.
57114 * Calling _emit DOES NOT MEAN emit() would be called!
57115 * @param {EventName} event Type of event
57116 * @param {Path} path File or directory path
57117 * @param {*=} val1 arguments to be passed with event
57118 * @param {*=} val2
57119 * @param {*=} val3
57120 * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
57121 */
57122async _emit(event, path, val1, val2, val3) {
57123 if (this.closed) return;
57124
57125 const opts = this.options;
57126 if (isWindows$1) path = sysPath.normalize(path);
57127 if (opts.cwd) path = sysPath.relative(opts.cwd, path);
57128 /** @type Array<any> */
57129 const args = [event, path];
57130 if (val3 !== undefined) args.push(val1, val2, val3);
57131 else if (val2 !== undefined) args.push(val1, val2);
57132 else if (val1 !== undefined) args.push(val1);
57133
57134 const awf = opts.awaitWriteFinish;
57135 let pw;
57136 if (awf && (pw = this._pendingWrites.get(path))) {
57137 pw.lastChange = new Date();
57138 return this;
57139 }
57140
57141 if (opts.atomic) {
57142 if (event === EV_UNLINK) {
57143 this._pendingUnlinks.set(path, args);
57144 setTimeout(() => {
57145 this._pendingUnlinks.forEach((entry, path) => {
57146 this.emit(...entry);
57147 this.emit(EV_ALL, ...entry);
57148 this._pendingUnlinks.delete(path);
57149 });
57150 }, typeof opts.atomic === 'number' ? opts.atomic : 100);
57151 return this;
57152 }
57153 if (event === EV_ADD && this._pendingUnlinks.has(path)) {
57154 event = args[0] = EV_CHANGE;
57155 this._pendingUnlinks.delete(path);
57156 }
57157 }
57158
57159 if (awf && (event === EV_ADD || event === EV_CHANGE) && this._readyEmitted) {
57160 const awfEmit = (err, stats) => {
57161 if (err) {
57162 event = args[0] = EV_ERROR;
57163 args[1] = err;
57164 this.emitWithAll(event, args);
57165 } else if (stats) {
57166 // if stats doesn't exist the file must have been deleted
57167 if (args.length > 2) {
57168 args[2] = stats;
57169 } else {
57170 args.push(stats);
57171 }
57172 this.emitWithAll(event, args);
57173 }
57174 };
57175
57176 this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
57177 return this;
57178 }
57179
57180 if (event === EV_CHANGE) {
57181 const isThrottled = !this._throttle(EV_CHANGE, path, 50);
57182 if (isThrottled) return this;
57183 }
57184
57185 if (opts.alwaysStat && val1 === undefined &&
57186 (event === EV_ADD || event === EV_ADD_DIR || event === EV_CHANGE)
57187 ) {
57188 const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path;
57189 let stats;
57190 try {
57191 stats = await stat(fullPath);
57192 } catch (err) {}
57193 // Suppress event when fs_stat fails, to avoid sending undefined 'stat'
57194 if (!stats || this.closed) return;
57195 args.push(stats);
57196 }
57197 this.emitWithAll(event, args);
57198
57199 return this;
57200}
57201
57202/**
57203 * Common handler for errors
57204 * @param {Error} error
57205 * @returns {Error|Boolean} The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
57206 */
57207_handleError(error) {
57208 const code = error && error.code;
57209 if (error && code !== 'ENOENT' && code !== 'ENOTDIR' &&
57210 (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES'))
57211 ) {
57212 this.emit(EV_ERROR, error);
57213 }
57214 return error || this.closed;
57215}
57216
57217/**
57218 * Helper utility for throttling
57219 * @param {ThrottleType} actionType type being throttled
57220 * @param {Path} path being acted upon
57221 * @param {Number} timeout duration of time to suppress duplicate actions
57222 * @returns {Object|false} tracking object or false if action should be suppressed
57223 */
57224_throttle(actionType, path, timeout) {
57225 if (!this._throttled.has(actionType)) {
57226 this._throttled.set(actionType, new Map());
57227 }
57228
57229 /** @type {Map<Path, Object>} */
57230 const action = this._throttled.get(actionType);
57231 /** @type {Object} */
57232 const actionPath = action.get(path);
57233
57234 if (actionPath) {
57235 actionPath.count++;
57236 return false;
57237 }
57238
57239 let timeoutObject;
57240 const clear = () => {
57241 const item = action.get(path);
57242 const count = item ? item.count : 0;
57243 action.delete(path);
57244 clearTimeout(timeoutObject);
57245 if (item) clearTimeout(item.timeoutObject);
57246 return count;
57247 };
57248 timeoutObject = setTimeout(clear, timeout);
57249 const thr = {timeoutObject, clear, count: 0};
57250 action.set(path, thr);
57251 return thr;
57252}
57253
57254_incrReadyCount() {
57255 return this._readyCount++;
57256}
57257
57258/**
57259 * Awaits write operation to finish.
57260 * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
57261 * @param {Path} path being acted upon
57262 * @param {Number} threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
57263 * @param {EventName} event
57264 * @param {Function} awfEmit Callback to be called when ready for event to be emitted.
57265 */
57266_awaitWriteFinish(path, threshold, event, awfEmit) {
57267 let timeoutHandler;
57268
57269 let fullPath = path;
57270 if (this.options.cwd && !sysPath.isAbsolute(path)) {
57271 fullPath = sysPath.join(this.options.cwd, path);
57272 }
57273
57274 const now = new Date();
57275
57276 const awaitWriteFinish = (prevStat) => {
57277 fs$8.stat(fullPath, (err, curStat) => {
57278 if (err || !this._pendingWrites.has(path)) {
57279 if (err && err.code !== 'ENOENT') awfEmit(err);
57280 return;
57281 }
57282
57283 const now = Number(new Date());
57284
57285 if (prevStat && curStat.size !== prevStat.size) {
57286 this._pendingWrites.get(path).lastChange = now;
57287 }
57288 const pw = this._pendingWrites.get(path);
57289 const df = now - pw.lastChange;
57290
57291 if (df >= threshold) {
57292 this._pendingWrites.delete(path);
57293 awfEmit(undefined, curStat);
57294 } else {
57295 timeoutHandler = setTimeout(
57296 awaitWriteFinish,
57297 this.options.awaitWriteFinish.pollInterval,
57298 curStat
57299 );
57300 }
57301 });
57302 };
57303
57304 if (!this._pendingWrites.has(path)) {
57305 this._pendingWrites.set(path, {
57306 lastChange: now,
57307 cancelWait: () => {
57308 this._pendingWrites.delete(path);
57309 clearTimeout(timeoutHandler);
57310 return event;
57311 }
57312 });
57313 timeoutHandler = setTimeout(
57314 awaitWriteFinish,
57315 this.options.awaitWriteFinish.pollInterval
57316 );
57317 }
57318}
57319
57320_getGlobIgnored() {
57321 return [...this._ignoredPaths.values()];
57322}
57323
57324/**
57325 * Determines whether user has asked to ignore this path.
57326 * @param {Path} path filepath or dir
57327 * @param {fs.Stats=} stats result of fs.stat
57328 * @returns {Boolean}
57329 */
57330_isIgnored(path, stats) {
57331 if (this.options.atomic && DOT_RE.test(path)) return true;
57332 if (!this._userIgnored) {
57333 const {cwd} = this.options;
57334 const ign = this.options.ignored;
57335
57336 const ignored = ign && ign.map(normalizeIgnored(cwd));
57337 const paths = arrify(ignored)
57338 .filter((path) => typeof path === STRING_TYPE && !isGlob(path))
57339 .map((path) => path + SLASH_GLOBSTAR);
57340 const list = this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored, paths);
57341 this._userIgnored = anymatch(list, undefined, ANYMATCH_OPTS);
57342 }
57343
57344 return this._userIgnored([path, stats]);
57345}
57346
57347_isntIgnored(path, stat) {
57348 return !this._isIgnored(path, stat);
57349}
57350
57351/**
57352 * Provides a set of common helpers and properties relating to symlink and glob handling.
57353 * @param {Path} path file, directory, or glob pattern being watched
57354 * @param {Number=} depth at any depth > 0, this isn't a glob
57355 * @returns {WatchHelper} object containing helpers for this path
57356 */
57357_getWatchHelpers(path, depth) {
57358 const watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path);
57359 const follow = this.options.followSymlinks;
57360
57361 return new WatchHelper(path, watchPath, follow, this);
57362}
57363
57364// Directory helpers
57365// -----------------
57366
57367/**
57368 * Provides directory tracking objects
57369 * @param {String} directory path of the directory
57370 * @returns {DirEntry} the directory's tracking object
57371 */
57372_getWatchedDir(directory) {
57373 if (!this._boundRemove) this._boundRemove = this._remove.bind(this);
57374 const dir = sysPath.resolve(directory);
57375 if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove));
57376 return this._watched.get(dir);
57377}
57378
57379// File helpers
57380// ------------
57381
57382/**
57383 * Check for read permissions.
57384 * Based on this answer on SO: https://stackoverflow.com/a/11781404/1358405
57385 * @param {fs.Stats} stats - object, result of fs_stat
57386 * @returns {Boolean} indicates whether the file can be read
57387*/
57388_hasReadPermissions(stats) {
57389 if (this.options.ignorePermissionErrors) return true;
57390
57391 // stats.mode may be bigint
57392 const md = stats && Number.parseInt(stats.mode, 10);
57393 const st = md & 0o777;
57394 const it = Number.parseInt(st.toString(8)[0], 10);
57395 return Boolean(4 & it);
57396}
57397
57398/**
57399 * Handles emitting unlink events for
57400 * files and directories, and via recursion, for
57401 * files and directories within directories that are unlinked
57402 * @param {String} directory within which the following item is located
57403 * @param {String} item base path of item/directory
57404 * @returns {void}
57405*/
57406_remove(directory, item, isDirectory) {
57407 // if what is being deleted is a directory, get that directory's paths
57408 // for recursive deleting and cleaning of watched object
57409 // if it is not a directory, nestedDirectoryChildren will be empty array
57410 const path = sysPath.join(directory, item);
57411 const fullPath = sysPath.resolve(path);
57412 isDirectory = isDirectory != null
57413 ? isDirectory
57414 : this._watched.has(path) || this._watched.has(fullPath);
57415
57416 // prevent duplicate handling in case of arriving here nearly simultaneously
57417 // via multiple paths (such as _handleFile and _handleDir)
57418 if (!this._throttle('remove', path, 100)) return;
57419
57420 // if the only watched file is removed, watch for its return
57421 if (!isDirectory && !this.options.useFsEvents && this._watched.size === 1) {
57422 this.add(directory, item, true);
57423 }
57424
57425 // This will create a new entry in the watched object in either case
57426 // so we got to do the directory check beforehand
57427 const wp = this._getWatchedDir(path);
57428 const nestedDirectoryChildren = wp.getChildren();
57429
57430 // Recursively remove children directories / files.
57431 nestedDirectoryChildren.forEach(nested => this._remove(path, nested));
57432
57433 // Check if item was on the watched list and remove it
57434 const parent = this._getWatchedDir(directory);
57435 const wasTracked = parent.has(item);
57436 parent.remove(item);
57437
57438 // Fixes issue #1042 -> Relative paths were detected and added as symlinks
57439 // (https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L612),
57440 // but never removed from the map in case the path was deleted.
57441 // This leads to an incorrect state if the path was recreated:
57442 // https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L553
57443 if (this._symlinkPaths.has(fullPath)) {
57444 this._symlinkPaths.delete(fullPath);
57445 }
57446
57447 // If we wait for this file to be fully written, cancel the wait.
57448 let relPath = path;
57449 if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path);
57450 if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
57451 const event = this._pendingWrites.get(relPath).cancelWait();
57452 if (event === EV_ADD) return;
57453 }
57454
57455 // The Entry will either be a directory that just got removed
57456 // or a bogus entry to a file, in either case we have to remove it
57457 this._watched.delete(path);
57458 this._watched.delete(fullPath);
57459 const eventName = isDirectory ? EV_UNLINK_DIR : EV_UNLINK;
57460 if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);
57461
57462 // Avoid conflicts if we later create another file with the same name
57463 if (!this.options.useFsEvents) {
57464 this._closePath(path);
57465 }
57466}
57467
57468/**
57469 * Closes all watchers for a path
57470 * @param {Path} path
57471 */
57472_closePath(path) {
57473 this._closeFile(path);
57474 const dir = sysPath.dirname(path);
57475 this._getWatchedDir(dir).remove(sysPath.basename(path));
57476}
57477
57478/**
57479 * Closes only file-specific watchers
57480 * @param {Path} path
57481 */
57482_closeFile(path) {
57483 const closers = this._closers.get(path);
57484 if (!closers) return;
57485 closers.forEach(closer => closer());
57486 this._closers.delete(path);
57487}
57488
57489/**
57490 *
57491 * @param {Path} path
57492 * @param {Function} closer
57493 */
57494_addPathCloser(path, closer) {
57495 if (!closer) return;
57496 let list = this._closers.get(path);
57497 if (!list) {
57498 list = [];
57499 this._closers.set(path, list);
57500 }
57501 list.push(closer);
57502}
57503
57504_readdirp(root, opts) {
57505 if (this.closed) return;
57506 const options = {type: EV_ALL, alwaysStat: true, lstat: true, ...opts};
57507 let stream = readdirp(root, options);
57508 this._streams.add(stream);
57509 stream.once(STR_CLOSE, () => {
57510 stream = undefined;
57511 });
57512 stream.once(STR_END, () => {
57513 if (stream) {
57514 this._streams.delete(stream);
57515 stream = undefined;
57516 }
57517 });
57518 return stream;
57519}
57520
57521}
57522
57523// Export FSWatcher class
57524chokidar.FSWatcher = FSWatcher;
57525
57526/**
57527 * Instantiates watcher with paths to be tracked.
57528 * @param {String|Array<String>} paths file/directory paths and/or globs
57529 * @param {Object=} options chokidar opts
57530 * @returns an instance of FSWatcher for chaining.
57531 */
57532const watch = (paths, options) => {
57533 const watcher = new FSWatcher(options);
57534 watcher.add(paths);
57535 return watcher;
57536};
57537
57538chokidar.watch = watch;
57539
57540async function resolveHttpServer({ proxy }, app, httpsOptions) {
57541 if (!httpsOptions) {
57542 return require('http').createServer(app);
57543 }
57544 if (proxy) {
57545 // #484 fallback to http1 when proxy is needed.
57546 return require('https').createServer(httpsOptions, app);
57547 }
57548 else {
57549 return require('http2').createSecureServer({
57550 ...httpsOptions,
57551 allowHTTP1: true
57552 }, app);
57553 }
57554}
57555async function resolveHttpsConfig(config) {
57556 if (!config.server.https)
57557 return undefined;
57558 const httpsOption = typeof config.server.https === 'object' ? config.server.https : {};
57559 const { ca, cert, key, pfx } = httpsOption;
57560 Object.assign(httpsOption, {
57561 ca: readFileIfExists(ca),
57562 cert: readFileIfExists(cert),
57563 key: readFileIfExists(key),
57564 pfx: readFileIfExists(pfx)
57565 });
57566 if (!httpsOption.key || !httpsOption.cert) {
57567 httpsOption.cert = httpsOption.key = await createCertificate();
57568 }
57569 return httpsOption;
57570}
57571function readFileIfExists(value) {
57572 if (typeof value === 'string') {
57573 try {
57574 return fs__default.readFileSync(path__default.resolve(value));
57575 }
57576 catch (e) {
57577 return value;
57578 }
57579 }
57580 return value;
57581}
57582/**
57583 * https://github.com/webpack/webpack-dev-server/blob/master/lib/utils/createCertificate.js
57584 *
57585 * Copyright JS Foundation and other contributors
57586 * This source code is licensed under the MIT license found in the
57587 * LICENSE file at
57588 * https://github.com/webpack/webpack-dev-server/blob/master/LICENSE
57589 */
57590async function createCertificate() {
57591 const { generate } = await Promise.resolve().then(function () { return require('./dep-d25c0094.js'); }).then(function (n) { return n.index; });
57592 const pems = generate(null, {
57593 algorithm: 'sha256',
57594 days: 30,
57595 keySize: 2048,
57596 extensions: [
57597 // {
57598 // name: 'basicConstraints',
57599 // cA: true,
57600 // },
57601 {
57602 name: 'keyUsage',
57603 keyCertSign: true,
57604 digitalSignature: true,
57605 nonRepudiation: true,
57606 keyEncipherment: true,
57607 dataEncipherment: true
57608 },
57609 {
57610 name: 'extKeyUsage',
57611 serverAuth: true,
57612 clientAuth: true,
57613 codeSigning: true,
57614 timeStamping: true
57615 },
57616 {
57617 name: 'subjectAltName',
57618 altNames: [
57619 {
57620 // type 2 is DNS
57621 type: 2,
57622 value: 'localhost'
57623 },
57624 {
57625 type: 2,
57626 value: 'localhost.localdomain'
57627 },
57628 {
57629 type: 2,
57630 value: 'lvh.me'
57631 },
57632 {
57633 type: 2,
57634 value: '*.lvh.me'
57635 },
57636 {
57637 type: 2,
57638 value: '[::1]'
57639 },
57640 {
57641 // type 7 is IP
57642 type: 7,
57643 ip: '127.0.0.1'
57644 },
57645 {
57646 type: 7,
57647 ip: 'fe80::1'
57648 }
57649 ]
57650 }
57651 ]
57652 });
57653 return pems.private + pems.cert;
57654}
57655
57656var bufferUtil$1 = {exports: {}};
57657
57658var constants = {
57659 BINARY_TYPES: ['nodebuffer', 'arraybuffer', 'fragments'],
57660 GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11',
57661 kStatusCode: Symbol('status-code'),
57662 kWebSocket: Symbol('websocket'),
57663 EMPTY_BUFFER: Buffer.alloc(0),
57664 NOOP: () => {}
57665};
57666
57667var bufferutil = {
57668 __proto__: null
57669};
57670
57671var require$$1 = /*@__PURE__*/getAugmentedNamespace(bufferutil);
57672
57673const { EMPTY_BUFFER: EMPTY_BUFFER$3 } = constants;
57674
57675/**
57676 * Merges an array of buffers into a new buffer.
57677 *
57678 * @param {Buffer[]} list The array of buffers to concat
57679 * @param {Number} totalLength The total length of buffers in the list
57680 * @return {Buffer} The resulting buffer
57681 * @public
57682 */
57683function concat$1(list, totalLength) {
57684 if (list.length === 0) return EMPTY_BUFFER$3;
57685 if (list.length === 1) return list[0];
57686
57687 const target = Buffer.allocUnsafe(totalLength);
57688 let offset = 0;
57689
57690 for (let i = 0; i < list.length; i++) {
57691 const buf = list[i];
57692 target.set(buf, offset);
57693 offset += buf.length;
57694 }
57695
57696 if (offset < totalLength) return target.slice(0, offset);
57697
57698 return target;
57699}
57700
57701/**
57702 * Masks a buffer using the given mask.
57703 *
57704 * @param {Buffer} source The buffer to mask
57705 * @param {Buffer} mask The mask to use
57706 * @param {Buffer} output The buffer where to store the result
57707 * @param {Number} offset The offset at which to start writing
57708 * @param {Number} length The number of bytes to mask.
57709 * @public
57710 */
57711function _mask(source, mask, output, offset, length) {
57712 for (let i = 0; i < length; i++) {
57713 output[offset + i] = source[i] ^ mask[i & 3];
57714 }
57715}
57716
57717/**
57718 * Unmasks a buffer using the given mask.
57719 *
57720 * @param {Buffer} buffer The buffer to unmask
57721 * @param {Buffer} mask The mask to use
57722 * @public
57723 */
57724function _unmask(buffer, mask) {
57725 // Required until https://github.com/nodejs/node/issues/9006 is resolved.
57726 const length = buffer.length;
57727 for (let i = 0; i < length; i++) {
57728 buffer[i] ^= mask[i & 3];
57729 }
57730}
57731
57732/**
57733 * Converts a buffer to an `ArrayBuffer`.
57734 *
57735 * @param {Buffer} buf The buffer to convert
57736 * @return {ArrayBuffer} Converted buffer
57737 * @public
57738 */
57739function toArrayBuffer$1(buf) {
57740 if (buf.byteLength === buf.buffer.byteLength) {
57741 return buf.buffer;
57742 }
57743
57744 return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
57745}
57746
57747/**
57748 * Converts `data` to a `Buffer`.
57749 *
57750 * @param {*} data The data to convert
57751 * @return {Buffer} The buffer
57752 * @throws {TypeError}
57753 * @public
57754 */
57755function toBuffer$2(data) {
57756 toBuffer$2.readOnly = true;
57757
57758 if (Buffer.isBuffer(data)) return data;
57759
57760 let buf;
57761
57762 if (data instanceof ArrayBuffer) {
57763 buf = Buffer.from(data);
57764 } else if (ArrayBuffer.isView(data)) {
57765 buf = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
57766 } else {
57767 buf = Buffer.from(data);
57768 toBuffer$2.readOnly = false;
57769 }
57770
57771 return buf;
57772}
57773
57774try {
57775 const bufferUtil = require$$1;
57776 const bu = bufferUtil.BufferUtil || bufferUtil;
57777
57778 bufferUtil$1.exports = {
57779 concat: concat$1,
57780 mask(source, mask, output, offset, length) {
57781 if (length < 48) _mask(source, mask, output, offset, length);
57782 else bu.mask(source, mask, output, offset, length);
57783 },
57784 toArrayBuffer: toArrayBuffer$1,
57785 toBuffer: toBuffer$2,
57786 unmask(buffer, mask) {
57787 if (buffer.length < 32) _unmask(buffer, mask);
57788 else bu.unmask(buffer, mask);
57789 }
57790 };
57791} catch (e) /* istanbul ignore next */ {
57792 bufferUtil$1.exports = {
57793 concat: concat$1,
57794 mask: _mask,
57795 toArrayBuffer: toArrayBuffer$1,
57796 toBuffer: toBuffer$2,
57797 unmask: _unmask
57798 };
57799}
57800
57801const kDone = Symbol('kDone');
57802const kRun = Symbol('kRun');
57803
57804/**
57805 * A very simple job queue with adjustable concurrency. Adapted from
57806 * https://github.com/STRML/async-limiter
57807 */
57808class Limiter$1 {
57809 /**
57810 * Creates a new `Limiter`.
57811 *
57812 * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
57813 * to run concurrently
57814 */
57815 constructor(concurrency) {
57816 this[kDone] = () => {
57817 this.pending--;
57818 this[kRun]();
57819 };
57820 this.concurrency = concurrency || Infinity;
57821 this.jobs = [];
57822 this.pending = 0;
57823 }
57824
57825 /**
57826 * Adds a job to the queue.
57827 *
57828 * @param {Function} job The job to run
57829 * @public
57830 */
57831 add(job) {
57832 this.jobs.push(job);
57833 this[kRun]();
57834 }
57835
57836 /**
57837 * Removes a job from the queue and runs it if possible.
57838 *
57839 * @private
57840 */
57841 [kRun]() {
57842 if (this.pending === this.concurrency) return;
57843
57844 if (this.jobs.length) {
57845 const job = this.jobs.shift();
57846
57847 this.pending++;
57848 job(this[kDone]);
57849 }
57850 }
57851}
57852
57853var limiter = Limiter$1;
57854
57855const zlib = require$$0__default$4;
57856
57857const bufferUtil = bufferUtil$1.exports;
57858const Limiter = limiter;
57859const { kStatusCode: kStatusCode$2, NOOP: NOOP$1 } = constants;
57860
57861const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);
57862const kPerMessageDeflate = Symbol('permessage-deflate');
57863const kTotalLength = Symbol('total-length');
57864const kCallback = Symbol('callback');
57865const kBuffers = Symbol('buffers');
57866const kError = Symbol('error');
57867
57868//
57869// We limit zlib concurrency, which prevents severe memory fragmentation
57870// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913
57871// and https://github.com/websockets/ws/issues/1202
57872//
57873// Intentionally global; it's the global thread pool that's an issue.
57874//
57875let zlibLimiter;
57876
57877/**
57878 * permessage-deflate implementation.
57879 */
57880class PerMessageDeflate$4 {
57881 /**
57882 * Creates a PerMessageDeflate instance.
57883 *
57884 * @param {Object} [options] Configuration options
57885 * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
57886 * disabling of server context takeover
57887 * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
57888 * acknowledge disabling of client context takeover
57889 * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
57890 * use of a custom server window size
57891 * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
57892 * for, or request, a custom client window size
57893 * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
57894 * deflate
57895 * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
57896 * inflate
57897 * @param {Number} [options.threshold=1024] Size (in bytes) below which
57898 * messages should not be compressed
57899 * @param {Number} [options.concurrencyLimit=10] The number of concurrent
57900 * calls to zlib
57901 * @param {Boolean} [isServer=false] Create the instance in either server or
57902 * client mode
57903 * @param {Number} [maxPayload=0] The maximum allowed message length
57904 */
57905 constructor(options, isServer, maxPayload) {
57906 this._maxPayload = maxPayload | 0;
57907 this._options = options || {};
57908 this._threshold =
57909 this._options.threshold !== undefined ? this._options.threshold : 1024;
57910 this._isServer = !!isServer;
57911 this._deflate = null;
57912 this._inflate = null;
57913
57914 this.params = null;
57915
57916 if (!zlibLimiter) {
57917 const concurrency =
57918 this._options.concurrencyLimit !== undefined
57919 ? this._options.concurrencyLimit
57920 : 10;
57921 zlibLimiter = new Limiter(concurrency);
57922 }
57923 }
57924
57925 /**
57926 * @type {String}
57927 */
57928 static get extensionName() {
57929 return 'permessage-deflate';
57930 }
57931
57932 /**
57933 * Create an extension negotiation offer.
57934 *
57935 * @return {Object} Extension parameters
57936 * @public
57937 */
57938 offer() {
57939 const params = {};
57940
57941 if (this._options.serverNoContextTakeover) {
57942 params.server_no_context_takeover = true;
57943 }
57944 if (this._options.clientNoContextTakeover) {
57945 params.client_no_context_takeover = true;
57946 }
57947 if (this._options.serverMaxWindowBits) {
57948 params.server_max_window_bits = this._options.serverMaxWindowBits;
57949 }
57950 if (this._options.clientMaxWindowBits) {
57951 params.client_max_window_bits = this._options.clientMaxWindowBits;
57952 } else if (this._options.clientMaxWindowBits == null) {
57953 params.client_max_window_bits = true;
57954 }
57955
57956 return params;
57957 }
57958
57959 /**
57960 * Accept an extension negotiation offer/response.
57961 *
57962 * @param {Array} configurations The extension negotiation offers/reponse
57963 * @return {Object} Accepted configuration
57964 * @public
57965 */
57966 accept(configurations) {
57967 configurations = this.normalizeParams(configurations);
57968
57969 this.params = this._isServer
57970 ? this.acceptAsServer(configurations)
57971 : this.acceptAsClient(configurations);
57972
57973 return this.params;
57974 }
57975
57976 /**
57977 * Releases all resources used by the extension.
57978 *
57979 * @public
57980 */
57981 cleanup() {
57982 if (this._inflate) {
57983 this._inflate.close();
57984 this._inflate = null;
57985 }
57986
57987 if (this._deflate) {
57988 const callback = this._deflate[kCallback];
57989
57990 this._deflate.close();
57991 this._deflate = null;
57992
57993 if (callback) {
57994 callback(
57995 new Error(
57996 'The deflate stream was closed while data was being processed'
57997 )
57998 );
57999 }
58000 }
58001 }
58002
58003 /**
58004 * Accept an extension negotiation offer.
58005 *
58006 * @param {Array} offers The extension negotiation offers
58007 * @return {Object} Accepted configuration
58008 * @private
58009 */
58010 acceptAsServer(offers) {
58011 const opts = this._options;
58012 const accepted = offers.find((params) => {
58013 if (
58014 (opts.serverNoContextTakeover === false &&
58015 params.server_no_context_takeover) ||
58016 (params.server_max_window_bits &&
58017 (opts.serverMaxWindowBits === false ||
58018 (typeof opts.serverMaxWindowBits === 'number' &&
58019 opts.serverMaxWindowBits > params.server_max_window_bits))) ||
58020 (typeof opts.clientMaxWindowBits === 'number' &&
58021 !params.client_max_window_bits)
58022 ) {
58023 return false;
58024 }
58025
58026 return true;
58027 });
58028
58029 if (!accepted) {
58030 throw new Error('None of the extension offers can be accepted');
58031 }
58032
58033 if (opts.serverNoContextTakeover) {
58034 accepted.server_no_context_takeover = true;
58035 }
58036 if (opts.clientNoContextTakeover) {
58037 accepted.client_no_context_takeover = true;
58038 }
58039 if (typeof opts.serverMaxWindowBits === 'number') {
58040 accepted.server_max_window_bits = opts.serverMaxWindowBits;
58041 }
58042 if (typeof opts.clientMaxWindowBits === 'number') {
58043 accepted.client_max_window_bits = opts.clientMaxWindowBits;
58044 } else if (
58045 accepted.client_max_window_bits === true ||
58046 opts.clientMaxWindowBits === false
58047 ) {
58048 delete accepted.client_max_window_bits;
58049 }
58050
58051 return accepted;
58052 }
58053
58054 /**
58055 * Accept the extension negotiation response.
58056 *
58057 * @param {Array} response The extension negotiation response
58058 * @return {Object} Accepted configuration
58059 * @private
58060 */
58061 acceptAsClient(response) {
58062 const params = response[0];
58063
58064 if (
58065 this._options.clientNoContextTakeover === false &&
58066 params.client_no_context_takeover
58067 ) {
58068 throw new Error('Unexpected parameter "client_no_context_takeover"');
58069 }
58070
58071 if (!params.client_max_window_bits) {
58072 if (typeof this._options.clientMaxWindowBits === 'number') {
58073 params.client_max_window_bits = this._options.clientMaxWindowBits;
58074 }
58075 } else if (
58076 this._options.clientMaxWindowBits === false ||
58077 (typeof this._options.clientMaxWindowBits === 'number' &&
58078 params.client_max_window_bits > this._options.clientMaxWindowBits)
58079 ) {
58080 throw new Error(
58081 'Unexpected or invalid parameter "client_max_window_bits"'
58082 );
58083 }
58084
58085 return params;
58086 }
58087
58088 /**
58089 * Normalize parameters.
58090 *
58091 * @param {Array} configurations The extension negotiation offers/reponse
58092 * @return {Array} The offers/response with normalized parameters
58093 * @private
58094 */
58095 normalizeParams(configurations) {
58096 configurations.forEach((params) => {
58097 Object.keys(params).forEach((key) => {
58098 let value = params[key];
58099
58100 if (value.length > 1) {
58101 throw new Error(`Parameter "${key}" must have only a single value`);
58102 }
58103
58104 value = value[0];
58105
58106 if (key === 'client_max_window_bits') {
58107 if (value !== true) {
58108 const num = +value;
58109 if (!Number.isInteger(num) || num < 8 || num > 15) {
58110 throw new TypeError(
58111 `Invalid value for parameter "${key}": ${value}`
58112 );
58113 }
58114 value = num;
58115 } else if (!this._isServer) {
58116 throw new TypeError(
58117 `Invalid value for parameter "${key}": ${value}`
58118 );
58119 }
58120 } else if (key === 'server_max_window_bits') {
58121 const num = +value;
58122 if (!Number.isInteger(num) || num < 8 || num > 15) {
58123 throw new TypeError(
58124 `Invalid value for parameter "${key}": ${value}`
58125 );
58126 }
58127 value = num;
58128 } else if (
58129 key === 'client_no_context_takeover' ||
58130 key === 'server_no_context_takeover'
58131 ) {
58132 if (value !== true) {
58133 throw new TypeError(
58134 `Invalid value for parameter "${key}": ${value}`
58135 );
58136 }
58137 } else {
58138 throw new Error(`Unknown parameter "${key}"`);
58139 }
58140
58141 params[key] = value;
58142 });
58143 });
58144
58145 return configurations;
58146 }
58147
58148 /**
58149 * Decompress data. Concurrency limited.
58150 *
58151 * @param {Buffer} data Compressed data
58152 * @param {Boolean} fin Specifies whether or not this is the last fragment
58153 * @param {Function} callback Callback
58154 * @public
58155 */
58156 decompress(data, fin, callback) {
58157 zlibLimiter.add((done) => {
58158 this._decompress(data, fin, (err, result) => {
58159 done();
58160 callback(err, result);
58161 });
58162 });
58163 }
58164
58165 /**
58166 * Compress data. Concurrency limited.
58167 *
58168 * @param {Buffer} data Data to compress
58169 * @param {Boolean} fin Specifies whether or not this is the last fragment
58170 * @param {Function} callback Callback
58171 * @public
58172 */
58173 compress(data, fin, callback) {
58174 zlibLimiter.add((done) => {
58175 this._compress(data, fin, (err, result) => {
58176 done();
58177 callback(err, result);
58178 });
58179 });
58180 }
58181
58182 /**
58183 * Decompress data.
58184 *
58185 * @param {Buffer} data Compressed data
58186 * @param {Boolean} fin Specifies whether or not this is the last fragment
58187 * @param {Function} callback Callback
58188 * @private
58189 */
58190 _decompress(data, fin, callback) {
58191 const endpoint = this._isServer ? 'client' : 'server';
58192
58193 if (!this._inflate) {
58194 const key = `${endpoint}_max_window_bits`;
58195 const windowBits =
58196 typeof this.params[key] !== 'number'
58197 ? zlib.Z_DEFAULT_WINDOWBITS
58198 : this.params[key];
58199
58200 this._inflate = zlib.createInflateRaw({
58201 ...this._options.zlibInflateOptions,
58202 windowBits
58203 });
58204 this._inflate[kPerMessageDeflate] = this;
58205 this._inflate[kTotalLength] = 0;
58206 this._inflate[kBuffers] = [];
58207 this._inflate.on('error', inflateOnError);
58208 this._inflate.on('data', inflateOnData);
58209 }
58210
58211 this._inflate[kCallback] = callback;
58212
58213 this._inflate.write(data);
58214 if (fin) this._inflate.write(TRAILER);
58215
58216 this._inflate.flush(() => {
58217 const err = this._inflate[kError];
58218
58219 if (err) {
58220 this._inflate.close();
58221 this._inflate = null;
58222 callback(err);
58223 return;
58224 }
58225
58226 const data = bufferUtil.concat(
58227 this._inflate[kBuffers],
58228 this._inflate[kTotalLength]
58229 );
58230
58231 if (this._inflate._readableState.endEmitted) {
58232 this._inflate.close();
58233 this._inflate = null;
58234 } else {
58235 this._inflate[kTotalLength] = 0;
58236 this._inflate[kBuffers] = [];
58237
58238 if (fin && this.params[`${endpoint}_no_context_takeover`]) {
58239 this._inflate.reset();
58240 }
58241 }
58242
58243 callback(null, data);
58244 });
58245 }
58246
58247 /**
58248 * Compress data.
58249 *
58250 * @param {Buffer} data Data to compress
58251 * @param {Boolean} fin Specifies whether or not this is the last fragment
58252 * @param {Function} callback Callback
58253 * @private
58254 */
58255 _compress(data, fin, callback) {
58256 const endpoint = this._isServer ? 'server' : 'client';
58257
58258 if (!this._deflate) {
58259 const key = `${endpoint}_max_window_bits`;
58260 const windowBits =
58261 typeof this.params[key] !== 'number'
58262 ? zlib.Z_DEFAULT_WINDOWBITS
58263 : this.params[key];
58264
58265 this._deflate = zlib.createDeflateRaw({
58266 ...this._options.zlibDeflateOptions,
58267 windowBits
58268 });
58269
58270 this._deflate[kTotalLength] = 0;
58271 this._deflate[kBuffers] = [];
58272
58273 //
58274 // An `'error'` event is emitted, only on Node.js < 10.0.0, if the
58275 // `zlib.DeflateRaw` instance is closed while data is being processed.
58276 // This can happen if `PerMessageDeflate#cleanup()` is called at the wrong
58277 // time due to an abnormal WebSocket closure.
58278 //
58279 this._deflate.on('error', NOOP$1);
58280 this._deflate.on('data', deflateOnData);
58281 }
58282
58283 this._deflate[kCallback] = callback;
58284
58285 this._deflate.write(data);
58286 this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
58287 if (!this._deflate) {
58288 //
58289 // The deflate stream was closed while data was being processed.
58290 //
58291 return;
58292 }
58293
58294 let data = bufferUtil.concat(
58295 this._deflate[kBuffers],
58296 this._deflate[kTotalLength]
58297 );
58298
58299 if (fin) data = data.slice(0, data.length - 4);
58300
58301 //
58302 // Ensure that the callback will not be called again in
58303 // `PerMessageDeflate#cleanup()`.
58304 //
58305 this._deflate[kCallback] = null;
58306
58307 this._deflate[kTotalLength] = 0;
58308 this._deflate[kBuffers] = [];
58309
58310 if (fin && this.params[`${endpoint}_no_context_takeover`]) {
58311 this._deflate.reset();
58312 }
58313
58314 callback(null, data);
58315 });
58316 }
58317}
58318
58319var permessageDeflate = PerMessageDeflate$4;
58320
58321/**
58322 * The listener of the `zlib.DeflateRaw` stream `'data'` event.
58323 *
58324 * @param {Buffer} chunk A chunk of data
58325 * @private
58326 */
58327function deflateOnData(chunk) {
58328 this[kBuffers].push(chunk);
58329 this[kTotalLength] += chunk.length;
58330}
58331
58332/**
58333 * The listener of the `zlib.InflateRaw` stream `'data'` event.
58334 *
58335 * @param {Buffer} chunk A chunk of data
58336 * @private
58337 */
58338function inflateOnData(chunk) {
58339 this[kTotalLength] += chunk.length;
58340
58341 if (
58342 this[kPerMessageDeflate]._maxPayload < 1 ||
58343 this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload
58344 ) {
58345 this[kBuffers].push(chunk);
58346 return;
58347 }
58348
58349 this[kError] = new RangeError('Max payload size exceeded');
58350 this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH';
58351 this[kError][kStatusCode$2] = 1009;
58352 this.removeListener('data', inflateOnData);
58353 this.reset();
58354}
58355
58356/**
58357 * The listener of the `zlib.InflateRaw` stream `'error'` event.
58358 *
58359 * @param {Error} err The emitted error
58360 * @private
58361 */
58362function inflateOnError(err) {
58363 //
58364 // There is no need to call `Zlib#close()` as the handle is automatically
58365 // closed when an error is emitted.
58366 //
58367 this[kPerMessageDeflate]._inflate = null;
58368 err[kStatusCode$2] = 1007;
58369 this[kCallback](err);
58370}
58371
58372var validation = {exports: {}};
58373
58374var utf8Validate = {
58375 __proto__: null
58376};
58377
58378var require$$0 = /*@__PURE__*/getAugmentedNamespace(utf8Validate);
58379
58380/**
58381 * Checks if a status code is allowed in a close frame.
58382 *
58383 * @param {Number} code The status code
58384 * @return {Boolean} `true` if the status code is valid, else `false`
58385 * @public
58386 */
58387function isValidStatusCode$2(code) {
58388 return (
58389 (code >= 1000 &&
58390 code <= 1014 &&
58391 code !== 1004 &&
58392 code !== 1005 &&
58393 code !== 1006) ||
58394 (code >= 3000 && code <= 4999)
58395 );
58396}
58397
58398/**
58399 * Checks if a given buffer contains only correct UTF-8.
58400 * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by
58401 * Markus Kuhn.
58402 *
58403 * @param {Buffer} buf The buffer to check
58404 * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`
58405 * @public
58406 */
58407function _isValidUTF8(buf) {
58408 const len = buf.length;
58409 let i = 0;
58410
58411 while (i < len) {
58412 if ((buf[i] & 0x80) === 0) {
58413 // 0xxxxxxx
58414 i++;
58415 } else if ((buf[i] & 0xe0) === 0xc0) {
58416 // 110xxxxx 10xxxxxx
58417 if (
58418 i + 1 === len ||
58419 (buf[i + 1] & 0xc0) !== 0x80 ||
58420 (buf[i] & 0xfe) === 0xc0 // Overlong
58421 ) {
58422 return false;
58423 }
58424
58425 i += 2;
58426 } else if ((buf[i] & 0xf0) === 0xe0) {
58427 // 1110xxxx 10xxxxxx 10xxxxxx
58428 if (
58429 i + 2 >= len ||
58430 (buf[i + 1] & 0xc0) !== 0x80 ||
58431 (buf[i + 2] & 0xc0) !== 0x80 ||
58432 (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong
58433 (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF)
58434 ) {
58435 return false;
58436 }
58437
58438 i += 3;
58439 } else if ((buf[i] & 0xf8) === 0xf0) {
58440 // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
58441 if (
58442 i + 3 >= len ||
58443 (buf[i + 1] & 0xc0) !== 0x80 ||
58444 (buf[i + 2] & 0xc0) !== 0x80 ||
58445 (buf[i + 3] & 0xc0) !== 0x80 ||
58446 (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong
58447 (buf[i] === 0xf4 && buf[i + 1] > 0x8f) ||
58448 buf[i] > 0xf4 // > U+10FFFF
58449 ) {
58450 return false;
58451 }
58452
58453 i += 4;
58454 } else {
58455 return false;
58456 }
58457 }
58458
58459 return true;
58460}
58461
58462try {
58463 let isValidUTF8 = require$$0;
58464
58465 /* istanbul ignore if */
58466 if (typeof isValidUTF8 === 'object') {
58467 isValidUTF8 = isValidUTF8.Validation.isValidUTF8; // utf-8-validate@<3.0.0
58468 }
58469
58470 validation.exports = {
58471 isValidStatusCode: isValidStatusCode$2,
58472 isValidUTF8(buf) {
58473 return buf.length < 150 ? _isValidUTF8(buf) : isValidUTF8(buf);
58474 }
58475 };
58476} catch (e) /* istanbul ignore next */ {
58477 validation.exports = {
58478 isValidStatusCode: isValidStatusCode$2,
58479 isValidUTF8: _isValidUTF8
58480 };
58481}
58482
58483const { Writable: Writable$1 } = require$$0__default$2;
58484
58485const PerMessageDeflate$3 = permessageDeflate;
58486const {
58487 BINARY_TYPES: BINARY_TYPES$1,
58488 EMPTY_BUFFER: EMPTY_BUFFER$2,
58489 kStatusCode: kStatusCode$1,
58490 kWebSocket: kWebSocket$2
58491} = constants;
58492const { concat, toArrayBuffer, unmask } = bufferUtil$1.exports;
58493const { isValidStatusCode: isValidStatusCode$1, isValidUTF8 } = validation.exports;
58494
58495const GET_INFO = 0;
58496const GET_PAYLOAD_LENGTH_16 = 1;
58497const GET_PAYLOAD_LENGTH_64 = 2;
58498const GET_MASK = 3;
58499const GET_DATA = 4;
58500const INFLATING = 5;
58501
58502/**
58503 * HyBi Receiver implementation.
58504 *
58505 * @extends stream.Writable
58506 */
58507class Receiver$1 extends Writable$1 {
58508 /**
58509 * Creates a Receiver instance.
58510 *
58511 * @param {String} [binaryType=nodebuffer] The type for binary data
58512 * @param {Object} [extensions] An object containing the negotiated extensions
58513 * @param {Boolean} [isServer=false] Specifies whether to operate in client or
58514 * server mode
58515 * @param {Number} [maxPayload=0] The maximum allowed message length
58516 */
58517 constructor(binaryType, extensions, isServer, maxPayload) {
58518 super();
58519
58520 this._binaryType = binaryType || BINARY_TYPES$1[0];
58521 this[kWebSocket$2] = undefined;
58522 this._extensions = extensions || {};
58523 this._isServer = !!isServer;
58524 this._maxPayload = maxPayload | 0;
58525
58526 this._bufferedBytes = 0;
58527 this._buffers = [];
58528
58529 this._compressed = false;
58530 this._payloadLength = 0;
58531 this._mask = undefined;
58532 this._fragmented = 0;
58533 this._masked = false;
58534 this._fin = false;
58535 this._opcode = 0;
58536
58537 this._totalPayloadLength = 0;
58538 this._messageLength = 0;
58539 this._fragments = [];
58540
58541 this._state = GET_INFO;
58542 this._loop = false;
58543 }
58544
58545 /**
58546 * Implements `Writable.prototype._write()`.
58547 *
58548 * @param {Buffer} chunk The chunk of data to write
58549 * @param {String} encoding The character encoding of `chunk`
58550 * @param {Function} cb Callback
58551 * @private
58552 */
58553 _write(chunk, encoding, cb) {
58554 if (this._opcode === 0x08 && this._state == GET_INFO) return cb();
58555
58556 this._bufferedBytes += chunk.length;
58557 this._buffers.push(chunk);
58558 this.startLoop(cb);
58559 }
58560
58561 /**
58562 * Consumes `n` bytes from the buffered data.
58563 *
58564 * @param {Number} n The number of bytes to consume
58565 * @return {Buffer} The consumed bytes
58566 * @private
58567 */
58568 consume(n) {
58569 this._bufferedBytes -= n;
58570
58571 if (n === this._buffers[0].length) return this._buffers.shift();
58572
58573 if (n < this._buffers[0].length) {
58574 const buf = this._buffers[0];
58575 this._buffers[0] = buf.slice(n);
58576 return buf.slice(0, n);
58577 }
58578
58579 const dst = Buffer.allocUnsafe(n);
58580
58581 do {
58582 const buf = this._buffers[0];
58583 const offset = dst.length - n;
58584
58585 if (n >= buf.length) {
58586 dst.set(this._buffers.shift(), offset);
58587 } else {
58588 dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
58589 this._buffers[0] = buf.slice(n);
58590 }
58591
58592 n -= buf.length;
58593 } while (n > 0);
58594
58595 return dst;
58596 }
58597
58598 /**
58599 * Starts the parsing loop.
58600 *
58601 * @param {Function} cb Callback
58602 * @private
58603 */
58604 startLoop(cb) {
58605 let err;
58606 this._loop = true;
58607
58608 do {
58609 switch (this._state) {
58610 case GET_INFO:
58611 err = this.getInfo();
58612 break;
58613 case GET_PAYLOAD_LENGTH_16:
58614 err = this.getPayloadLength16();
58615 break;
58616 case GET_PAYLOAD_LENGTH_64:
58617 err = this.getPayloadLength64();
58618 break;
58619 case GET_MASK:
58620 this.getMask();
58621 break;
58622 case GET_DATA:
58623 err = this.getData(cb);
58624 break;
58625 default:
58626 // `INFLATING`
58627 this._loop = false;
58628 return;
58629 }
58630 } while (this._loop);
58631
58632 cb(err);
58633 }
58634
58635 /**
58636 * Reads the first two bytes of a frame.
58637 *
58638 * @return {(RangeError|undefined)} A possible error
58639 * @private
58640 */
58641 getInfo() {
58642 if (this._bufferedBytes < 2) {
58643 this._loop = false;
58644 return;
58645 }
58646
58647 const buf = this.consume(2);
58648
58649 if ((buf[0] & 0x30) !== 0x00) {
58650 this._loop = false;
58651 return error$2(
58652 RangeError,
58653 'RSV2 and RSV3 must be clear',
58654 true,
58655 1002,
58656 'WS_ERR_UNEXPECTED_RSV_2_3'
58657 );
58658 }
58659
58660 const compressed = (buf[0] & 0x40) === 0x40;
58661
58662 if (compressed && !this._extensions[PerMessageDeflate$3.extensionName]) {
58663 this._loop = false;
58664 return error$2(
58665 RangeError,
58666 'RSV1 must be clear',
58667 true,
58668 1002,
58669 'WS_ERR_UNEXPECTED_RSV_1'
58670 );
58671 }
58672
58673 this._fin = (buf[0] & 0x80) === 0x80;
58674 this._opcode = buf[0] & 0x0f;
58675 this._payloadLength = buf[1] & 0x7f;
58676
58677 if (this._opcode === 0x00) {
58678 if (compressed) {
58679 this._loop = false;
58680 return error$2(
58681 RangeError,
58682 'RSV1 must be clear',
58683 true,
58684 1002,
58685 'WS_ERR_UNEXPECTED_RSV_1'
58686 );
58687 }
58688
58689 if (!this._fragmented) {
58690 this._loop = false;
58691 return error$2(
58692 RangeError,
58693 'invalid opcode 0',
58694 true,
58695 1002,
58696 'WS_ERR_INVALID_OPCODE'
58697 );
58698 }
58699
58700 this._opcode = this._fragmented;
58701 } else if (this._opcode === 0x01 || this._opcode === 0x02) {
58702 if (this._fragmented) {
58703 this._loop = false;
58704 return error$2(
58705 RangeError,
58706 `invalid opcode ${this._opcode}`,
58707 true,
58708 1002,
58709 'WS_ERR_INVALID_OPCODE'
58710 );
58711 }
58712
58713 this._compressed = compressed;
58714 } else if (this._opcode > 0x07 && this._opcode < 0x0b) {
58715 if (!this._fin) {
58716 this._loop = false;
58717 return error$2(
58718 RangeError,
58719 'FIN must be set',
58720 true,
58721 1002,
58722 'WS_ERR_EXPECTED_FIN'
58723 );
58724 }
58725
58726 if (compressed) {
58727 this._loop = false;
58728 return error$2(
58729 RangeError,
58730 'RSV1 must be clear',
58731 true,
58732 1002,
58733 'WS_ERR_UNEXPECTED_RSV_1'
58734 );
58735 }
58736
58737 if (this._payloadLength > 0x7d) {
58738 this._loop = false;
58739 return error$2(
58740 RangeError,
58741 `invalid payload length ${this._payloadLength}`,
58742 true,
58743 1002,
58744 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH'
58745 );
58746 }
58747 } else {
58748 this._loop = false;
58749 return error$2(
58750 RangeError,
58751 `invalid opcode ${this._opcode}`,
58752 true,
58753 1002,
58754 'WS_ERR_INVALID_OPCODE'
58755 );
58756 }
58757
58758 if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
58759 this._masked = (buf[1] & 0x80) === 0x80;
58760
58761 if (this._isServer) {
58762 if (!this._masked) {
58763 this._loop = false;
58764 return error$2(
58765 RangeError,
58766 'MASK must be set',
58767 true,
58768 1002,
58769 'WS_ERR_EXPECTED_MASK'
58770 );
58771 }
58772 } else if (this._masked) {
58773 this._loop = false;
58774 return error$2(
58775 RangeError,
58776 'MASK must be clear',
58777 true,
58778 1002,
58779 'WS_ERR_UNEXPECTED_MASK'
58780 );
58781 }
58782
58783 if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
58784 else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
58785 else return this.haveLength();
58786 }
58787
58788 /**
58789 * Gets extended payload length (7+16).
58790 *
58791 * @return {(RangeError|undefined)} A possible error
58792 * @private
58793 */
58794 getPayloadLength16() {
58795 if (this._bufferedBytes < 2) {
58796 this._loop = false;
58797 return;
58798 }
58799
58800 this._payloadLength = this.consume(2).readUInt16BE(0);
58801 return this.haveLength();
58802 }
58803
58804 /**
58805 * Gets extended payload length (7+64).
58806 *
58807 * @return {(RangeError|undefined)} A possible error
58808 * @private
58809 */
58810 getPayloadLength64() {
58811 if (this._bufferedBytes < 8) {
58812 this._loop = false;
58813 return;
58814 }
58815
58816 const buf = this.consume(8);
58817 const num = buf.readUInt32BE(0);
58818
58819 //
58820 // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned
58821 // if payload length is greater than this number.
58822 //
58823 if (num > Math.pow(2, 53 - 32) - 1) {
58824 this._loop = false;
58825 return error$2(
58826 RangeError,
58827 'Unsupported WebSocket frame: payload length > 2^53 - 1',
58828 false,
58829 1009,
58830 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH'
58831 );
58832 }
58833
58834 this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
58835 return this.haveLength();
58836 }
58837
58838 /**
58839 * Payload length has been read.
58840 *
58841 * @return {(RangeError|undefined)} A possible error
58842 * @private
58843 */
58844 haveLength() {
58845 if (this._payloadLength && this._opcode < 0x08) {
58846 this._totalPayloadLength += this._payloadLength;
58847 if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
58848 this._loop = false;
58849 return error$2(
58850 RangeError,
58851 'Max payload size exceeded',
58852 false,
58853 1009,
58854 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'
58855 );
58856 }
58857 }
58858
58859 if (this._masked) this._state = GET_MASK;
58860 else this._state = GET_DATA;
58861 }
58862
58863 /**
58864 * Reads mask bytes.
58865 *
58866 * @private
58867 */
58868 getMask() {
58869 if (this._bufferedBytes < 4) {
58870 this._loop = false;
58871 return;
58872 }
58873
58874 this._mask = this.consume(4);
58875 this._state = GET_DATA;
58876 }
58877
58878 /**
58879 * Reads data bytes.
58880 *
58881 * @param {Function} cb Callback
58882 * @return {(Error|RangeError|undefined)} A possible error
58883 * @private
58884 */
58885 getData(cb) {
58886 let data = EMPTY_BUFFER$2;
58887
58888 if (this._payloadLength) {
58889 if (this._bufferedBytes < this._payloadLength) {
58890 this._loop = false;
58891 return;
58892 }
58893
58894 data = this.consume(this._payloadLength);
58895 if (this._masked) unmask(data, this._mask);
58896 }
58897
58898 if (this._opcode > 0x07) return this.controlMessage(data);
58899
58900 if (this._compressed) {
58901 this._state = INFLATING;
58902 this.decompress(data, cb);
58903 return;
58904 }
58905
58906 if (data.length) {
58907 //
58908 // This message is not compressed so its lenght is the sum of the payload
58909 // length of all fragments.
58910 //
58911 this._messageLength = this._totalPayloadLength;
58912 this._fragments.push(data);
58913 }
58914
58915 return this.dataMessage();
58916 }
58917
58918 /**
58919 * Decompresses data.
58920 *
58921 * @param {Buffer} data Compressed data
58922 * @param {Function} cb Callback
58923 * @private
58924 */
58925 decompress(data, cb) {
58926 const perMessageDeflate = this._extensions[PerMessageDeflate$3.extensionName];
58927
58928 perMessageDeflate.decompress(data, this._fin, (err, buf) => {
58929 if (err) return cb(err);
58930
58931 if (buf.length) {
58932 this._messageLength += buf.length;
58933 if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
58934 return cb(
58935 error$2(
58936 RangeError,
58937 'Max payload size exceeded',
58938 false,
58939 1009,
58940 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'
58941 )
58942 );
58943 }
58944
58945 this._fragments.push(buf);
58946 }
58947
58948 const er = this.dataMessage();
58949 if (er) return cb(er);
58950
58951 this.startLoop(cb);
58952 });
58953 }
58954
58955 /**
58956 * Handles a data message.
58957 *
58958 * @return {(Error|undefined)} A possible error
58959 * @private
58960 */
58961 dataMessage() {
58962 if (this._fin) {
58963 const messageLength = this._messageLength;
58964 const fragments = this._fragments;
58965
58966 this._totalPayloadLength = 0;
58967 this._messageLength = 0;
58968 this._fragmented = 0;
58969 this._fragments = [];
58970
58971 if (this._opcode === 2) {
58972 let data;
58973
58974 if (this._binaryType === 'nodebuffer') {
58975 data = concat(fragments, messageLength);
58976 } else if (this._binaryType === 'arraybuffer') {
58977 data = toArrayBuffer(concat(fragments, messageLength));
58978 } else {
58979 data = fragments;
58980 }
58981
58982 this.emit('message', data);
58983 } else {
58984 const buf = concat(fragments, messageLength);
58985
58986 if (!isValidUTF8(buf)) {
58987 this._loop = false;
58988 return error$2(
58989 Error,
58990 'invalid UTF-8 sequence',
58991 true,
58992 1007,
58993 'WS_ERR_INVALID_UTF8'
58994 );
58995 }
58996
58997 this.emit('message', buf.toString());
58998 }
58999 }
59000
59001 this._state = GET_INFO;
59002 }
59003
59004 /**
59005 * Handles a control message.
59006 *
59007 * @param {Buffer} data Data to handle
59008 * @return {(Error|RangeError|undefined)} A possible error
59009 * @private
59010 */
59011 controlMessage(data) {
59012 if (this._opcode === 0x08) {
59013 this._loop = false;
59014
59015 if (data.length === 0) {
59016 this.emit('conclude', 1005, '');
59017 this.end();
59018 } else if (data.length === 1) {
59019 return error$2(
59020 RangeError,
59021 'invalid payload length 1',
59022 true,
59023 1002,
59024 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH'
59025 );
59026 } else {
59027 const code = data.readUInt16BE(0);
59028
59029 if (!isValidStatusCode$1(code)) {
59030 return error$2(
59031 RangeError,
59032 `invalid status code ${code}`,
59033 true,
59034 1002,
59035 'WS_ERR_INVALID_CLOSE_CODE'
59036 );
59037 }
59038
59039 const buf = data.slice(2);
59040
59041 if (!isValidUTF8(buf)) {
59042 return error$2(
59043 Error,
59044 'invalid UTF-8 sequence',
59045 true,
59046 1007,
59047 'WS_ERR_INVALID_UTF8'
59048 );
59049 }
59050
59051 this.emit('conclude', code, buf.toString());
59052 this.end();
59053 }
59054 } else if (this._opcode === 0x09) {
59055 this.emit('ping', data);
59056 } else {
59057 this.emit('pong', data);
59058 }
59059
59060 this._state = GET_INFO;
59061 }
59062}
59063
59064var receiver = Receiver$1;
59065
59066/**
59067 * Builds an error object.
59068 *
59069 * @param {(Error|RangeError)} ErrorCtor The error constructor
59070 * @param {String} message The error message
59071 * @param {Boolean} prefix Specifies whether or not to add a default prefix to
59072 * `message`
59073 * @param {Number} statusCode The status code
59074 * @param {String} errorCode The exposed error code
59075 * @return {(Error|RangeError)} The error
59076 * @private
59077 */
59078function error$2(ErrorCtor, message, prefix, statusCode, errorCode) {
59079 const err = new ErrorCtor(
59080 prefix ? `Invalid WebSocket frame: ${message}` : message
59081 );
59082
59083 Error.captureStackTrace(err, error$2);
59084 err.code = errorCode;
59085 err[kStatusCode$1] = statusCode;
59086 return err;
59087}
59088
59089const { randomFillSync } = require$$1__default$1;
59090
59091const PerMessageDeflate$2 = permessageDeflate;
59092const { EMPTY_BUFFER: EMPTY_BUFFER$1 } = constants;
59093const { isValidStatusCode } = validation.exports;
59094const { mask: applyMask, toBuffer: toBuffer$1 } = bufferUtil$1.exports;
59095
59096const mask = Buffer.alloc(4);
59097
59098/**
59099 * HyBi Sender implementation.
59100 */
59101class Sender$1 {
59102 /**
59103 * Creates a Sender instance.
59104 *
59105 * @param {net.Socket} socket The connection socket
59106 * @param {Object} [extensions] An object containing the negotiated extensions
59107 */
59108 constructor(socket, extensions) {
59109 this._extensions = extensions || {};
59110 this._socket = socket;
59111
59112 this._firstFragment = true;
59113 this._compress = false;
59114
59115 this._bufferedBytes = 0;
59116 this._deflating = false;
59117 this._queue = [];
59118 }
59119
59120 /**
59121 * Frames a piece of data according to the HyBi WebSocket protocol.
59122 *
59123 * @param {Buffer} data The data to frame
59124 * @param {Object} options Options object
59125 * @param {Number} options.opcode The opcode
59126 * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
59127 * modified
59128 * @param {Boolean} [options.fin=false] Specifies whether or not to set the
59129 * FIN bit
59130 * @param {Boolean} [options.mask=false] Specifies whether or not to mask
59131 * `data`
59132 * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
59133 * RSV1 bit
59134 * @return {Buffer[]} The framed data as a list of `Buffer` instances
59135 * @public
59136 */
59137 static frame(data, options) {
59138 const merge = options.mask && options.readOnly;
59139 let offset = options.mask ? 6 : 2;
59140 let payloadLength = data.length;
59141
59142 if (data.length >= 65536) {
59143 offset += 8;
59144 payloadLength = 127;
59145 } else if (data.length > 125) {
59146 offset += 2;
59147 payloadLength = 126;
59148 }
59149
59150 const target = Buffer.allocUnsafe(merge ? data.length + offset : offset);
59151
59152 target[0] = options.fin ? options.opcode | 0x80 : options.opcode;
59153 if (options.rsv1) target[0] |= 0x40;
59154
59155 target[1] = payloadLength;
59156
59157 if (payloadLength === 126) {
59158 target.writeUInt16BE(data.length, 2);
59159 } else if (payloadLength === 127) {
59160 target.writeUInt32BE(0, 2);
59161 target.writeUInt32BE(data.length, 6);
59162 }
59163
59164 if (!options.mask) return [target, data];
59165
59166 randomFillSync(mask, 0, 4);
59167
59168 target[1] |= 0x80;
59169 target[offset - 4] = mask[0];
59170 target[offset - 3] = mask[1];
59171 target[offset - 2] = mask[2];
59172 target[offset - 1] = mask[3];
59173
59174 if (merge) {
59175 applyMask(data, mask, target, offset, data.length);
59176 return [target];
59177 }
59178
59179 applyMask(data, mask, data, 0, data.length);
59180 return [target, data];
59181 }
59182
59183 /**
59184 * Sends a close message to the other peer.
59185 *
59186 * @param {Number} [code] The status code component of the body
59187 * @param {String} [data] The message component of the body
59188 * @param {Boolean} [mask=false] Specifies whether or not to mask the message
59189 * @param {Function} [cb] Callback
59190 * @public
59191 */
59192 close(code, data, mask, cb) {
59193 let buf;
59194
59195 if (code === undefined) {
59196 buf = EMPTY_BUFFER$1;
59197 } else if (typeof code !== 'number' || !isValidStatusCode(code)) {
59198 throw new TypeError('First argument must be a valid error code number');
59199 } else if (data === undefined || data === '') {
59200 buf = Buffer.allocUnsafe(2);
59201 buf.writeUInt16BE(code, 0);
59202 } else {
59203 const length = Buffer.byteLength(data);
59204
59205 if (length > 123) {
59206 throw new RangeError('The message must not be greater than 123 bytes');
59207 }
59208
59209 buf = Buffer.allocUnsafe(2 + length);
59210 buf.writeUInt16BE(code, 0);
59211 buf.write(data, 2);
59212 }
59213
59214 if (this._deflating) {
59215 this.enqueue([this.doClose, buf, mask, cb]);
59216 } else {
59217 this.doClose(buf, mask, cb);
59218 }
59219 }
59220
59221 /**
59222 * Frames and sends a close message.
59223 *
59224 * @param {Buffer} data The message to send
59225 * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
59226 * @param {Function} [cb] Callback
59227 * @private
59228 */
59229 doClose(data, mask, cb) {
59230 this.sendFrame(
59231 Sender$1.frame(data, {
59232 fin: true,
59233 rsv1: false,
59234 opcode: 0x08,
59235 mask,
59236 readOnly: false
59237 }),
59238 cb
59239 );
59240 }
59241
59242 /**
59243 * Sends a ping message to the other peer.
59244 *
59245 * @param {*} data The message to send
59246 * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
59247 * @param {Function} [cb] Callback
59248 * @public
59249 */
59250 ping(data, mask, cb) {
59251 const buf = toBuffer$1(data);
59252
59253 if (buf.length > 125) {
59254 throw new RangeError('The data size must not be greater than 125 bytes');
59255 }
59256
59257 if (this._deflating) {
59258 this.enqueue([this.doPing, buf, mask, toBuffer$1.readOnly, cb]);
59259 } else {
59260 this.doPing(buf, mask, toBuffer$1.readOnly, cb);
59261 }
59262 }
59263
59264 /**
59265 * Frames and sends a ping message.
59266 *
59267 * @param {Buffer} data The message to send
59268 * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
59269 * @param {Boolean} [readOnly=false] Specifies whether `data` can be modified
59270 * @param {Function} [cb] Callback
59271 * @private
59272 */
59273 doPing(data, mask, readOnly, cb) {
59274 this.sendFrame(
59275 Sender$1.frame(data, {
59276 fin: true,
59277 rsv1: false,
59278 opcode: 0x09,
59279 mask,
59280 readOnly
59281 }),
59282 cb
59283 );
59284 }
59285
59286 /**
59287 * Sends a pong message to the other peer.
59288 *
59289 * @param {*} data The message to send
59290 * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
59291 * @param {Function} [cb] Callback
59292 * @public
59293 */
59294 pong(data, mask, cb) {
59295 const buf = toBuffer$1(data);
59296
59297 if (buf.length > 125) {
59298 throw new RangeError('The data size must not be greater than 125 bytes');
59299 }
59300
59301 if (this._deflating) {
59302 this.enqueue([this.doPong, buf, mask, toBuffer$1.readOnly, cb]);
59303 } else {
59304 this.doPong(buf, mask, toBuffer$1.readOnly, cb);
59305 }
59306 }
59307
59308 /**
59309 * Frames and sends a pong message.
59310 *
59311 * @param {Buffer} data The message to send
59312 * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
59313 * @param {Boolean} [readOnly=false] Specifies whether `data` can be modified
59314 * @param {Function} [cb] Callback
59315 * @private
59316 */
59317 doPong(data, mask, readOnly, cb) {
59318 this.sendFrame(
59319 Sender$1.frame(data, {
59320 fin: true,
59321 rsv1: false,
59322 opcode: 0x0a,
59323 mask,
59324 readOnly
59325 }),
59326 cb
59327 );
59328 }
59329
59330 /**
59331 * Sends a data message to the other peer.
59332 *
59333 * @param {*} data The message to send
59334 * @param {Object} options Options object
59335 * @param {Boolean} [options.compress=false] Specifies whether or not to
59336 * compress `data`
59337 * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
59338 * or text
59339 * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
59340 * last one
59341 * @param {Boolean} [options.mask=false] Specifies whether or not to mask
59342 * `data`
59343 * @param {Function} [cb] Callback
59344 * @public
59345 */
59346 send(data, options, cb) {
59347 const buf = toBuffer$1(data);
59348 const perMessageDeflate = this._extensions[PerMessageDeflate$2.extensionName];
59349 let opcode = options.binary ? 2 : 1;
59350 let rsv1 = options.compress;
59351
59352 if (this._firstFragment) {
59353 this._firstFragment = false;
59354 if (rsv1 && perMessageDeflate) {
59355 rsv1 = buf.length >= perMessageDeflate._threshold;
59356 }
59357 this._compress = rsv1;
59358 } else {
59359 rsv1 = false;
59360 opcode = 0;
59361 }
59362
59363 if (options.fin) this._firstFragment = true;
59364
59365 if (perMessageDeflate) {
59366 const opts = {
59367 fin: options.fin,
59368 rsv1,
59369 opcode,
59370 mask: options.mask,
59371 readOnly: toBuffer$1.readOnly
59372 };
59373
59374 if (this._deflating) {
59375 this.enqueue([this.dispatch, buf, this._compress, opts, cb]);
59376 } else {
59377 this.dispatch(buf, this._compress, opts, cb);
59378 }
59379 } else {
59380 this.sendFrame(
59381 Sender$1.frame(buf, {
59382 fin: options.fin,
59383 rsv1: false,
59384 opcode,
59385 mask: options.mask,
59386 readOnly: toBuffer$1.readOnly
59387 }),
59388 cb
59389 );
59390 }
59391 }
59392
59393 /**
59394 * Dispatches a data message.
59395 *
59396 * @param {Buffer} data The message to send
59397 * @param {Boolean} [compress=false] Specifies whether or not to compress
59398 * `data`
59399 * @param {Object} options Options object
59400 * @param {Number} options.opcode The opcode
59401 * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
59402 * modified
59403 * @param {Boolean} [options.fin=false] Specifies whether or not to set the
59404 * FIN bit
59405 * @param {Boolean} [options.mask=false] Specifies whether or not to mask
59406 * `data`
59407 * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
59408 * RSV1 bit
59409 * @param {Function} [cb] Callback
59410 * @private
59411 */
59412 dispatch(data, compress, options, cb) {
59413 if (!compress) {
59414 this.sendFrame(Sender$1.frame(data, options), cb);
59415 return;
59416 }
59417
59418 const perMessageDeflate = this._extensions[PerMessageDeflate$2.extensionName];
59419
59420 this._bufferedBytes += data.length;
59421 this._deflating = true;
59422 perMessageDeflate.compress(data, options.fin, (_, buf) => {
59423 if (this._socket.destroyed) {
59424 const err = new Error(
59425 'The socket was closed while data was being compressed'
59426 );
59427
59428 if (typeof cb === 'function') cb(err);
59429
59430 for (let i = 0; i < this._queue.length; i++) {
59431 const callback = this._queue[i][4];
59432
59433 if (typeof callback === 'function') callback(err);
59434 }
59435
59436 return;
59437 }
59438
59439 this._bufferedBytes -= data.length;
59440 this._deflating = false;
59441 options.readOnly = false;
59442 this.sendFrame(Sender$1.frame(buf, options), cb);
59443 this.dequeue();
59444 });
59445 }
59446
59447 /**
59448 * Executes queued send operations.
59449 *
59450 * @private
59451 */
59452 dequeue() {
59453 while (!this._deflating && this._queue.length) {
59454 const params = this._queue.shift();
59455
59456 this._bufferedBytes -= params[1].length;
59457 Reflect.apply(params[0], this, params.slice(1));
59458 }
59459 }
59460
59461 /**
59462 * Enqueues a send operation.
59463 *
59464 * @param {Array} params Send operation parameters.
59465 * @private
59466 */
59467 enqueue(params) {
59468 this._bufferedBytes += params[1].length;
59469 this._queue.push(params);
59470 }
59471
59472 /**
59473 * Sends a frame.
59474 *
59475 * @param {Buffer[]} list The frame to send
59476 * @param {Function} [cb] Callback
59477 * @private
59478 */
59479 sendFrame(list, cb) {
59480 if (list.length === 2) {
59481 this._socket.cork();
59482 this._socket.write(list[0]);
59483 this._socket.write(list[1], cb);
59484 this._socket.uncork();
59485 } else {
59486 this._socket.write(list[0], cb);
59487 }
59488 }
59489}
59490
59491var sender = Sender$1;
59492
59493/**
59494 * Class representing an event.
59495 *
59496 * @private
59497 */
59498class Event {
59499 /**
59500 * Create a new `Event`.
59501 *
59502 * @param {String} type The name of the event
59503 * @param {Object} target A reference to the target to which the event was
59504 * dispatched
59505 */
59506 constructor(type, target) {
59507 this.target = target;
59508 this.type = type;
59509 }
59510}
59511
59512/**
59513 * Class representing a message event.
59514 *
59515 * @extends Event
59516 * @private
59517 */
59518class MessageEvent extends Event {
59519 /**
59520 * Create a new `MessageEvent`.
59521 *
59522 * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The received data
59523 * @param {WebSocket} target A reference to the target to which the event was
59524 * dispatched
59525 */
59526 constructor(data, target) {
59527 super('message', target);
59528
59529 this.data = data;
59530 }
59531}
59532
59533/**
59534 * Class representing a close event.
59535 *
59536 * @extends Event
59537 * @private
59538 */
59539class CloseEvent extends Event {
59540 /**
59541 * Create a new `CloseEvent`.
59542 *
59543 * @param {Number} code The status code explaining why the connection is being
59544 * closed
59545 * @param {String} reason A human-readable string explaining why the
59546 * connection is closing
59547 * @param {WebSocket} target A reference to the target to which the event was
59548 * dispatched
59549 */
59550 constructor(code, reason, target) {
59551 super('close', target);
59552
59553 this.wasClean = target._closeFrameReceived && target._closeFrameSent;
59554 this.reason = reason;
59555 this.code = code;
59556 }
59557}
59558
59559/**
59560 * Class representing an open event.
59561 *
59562 * @extends Event
59563 * @private
59564 */
59565class OpenEvent extends Event {
59566 /**
59567 * Create a new `OpenEvent`.
59568 *
59569 * @param {WebSocket} target A reference to the target to which the event was
59570 * dispatched
59571 */
59572 constructor(target) {
59573 super('open', target);
59574 }
59575}
59576
59577/**
59578 * Class representing an error event.
59579 *
59580 * @extends Event
59581 * @private
59582 */
59583class ErrorEvent extends Event {
59584 /**
59585 * Create a new `ErrorEvent`.
59586 *
59587 * @param {Object} error The error that generated this event
59588 * @param {WebSocket} target A reference to the target to which the event was
59589 * dispatched
59590 */
59591 constructor(error, target) {
59592 super('error', target);
59593
59594 this.message = error.message;
59595 this.error = error;
59596 }
59597}
59598
59599/**
59600 * This provides methods for emulating the `EventTarget` interface. It's not
59601 * meant to be used directly.
59602 *
59603 * @mixin
59604 */
59605const EventTarget = {
59606 /**
59607 * Register an event listener.
59608 *
59609 * @param {String} type A string representing the event type to listen for
59610 * @param {Function} listener The listener to add
59611 * @param {Object} [options] An options object specifies characteristics about
59612 * the event listener
59613 * @param {Boolean} [options.once=false] A `Boolean`` indicating that the
59614 * listener should be invoked at most once after being added. If `true`,
59615 * the listener would be automatically removed when invoked.
59616 * @public
59617 */
59618 addEventListener(type, listener, options) {
59619 if (typeof listener !== 'function') return;
59620
59621 function onMessage(data) {
59622 listener.call(this, new MessageEvent(data, this));
59623 }
59624
59625 function onClose(code, message) {
59626 listener.call(this, new CloseEvent(code, message, this));
59627 }
59628
59629 function onError(error) {
59630 listener.call(this, new ErrorEvent(error, this));
59631 }
59632
59633 function onOpen() {
59634 listener.call(this, new OpenEvent(this));
59635 }
59636
59637 const method = options && options.once ? 'once' : 'on';
59638
59639 if (type === 'message') {
59640 onMessage._listener = listener;
59641 this[method](type, onMessage);
59642 } else if (type === 'close') {
59643 onClose._listener = listener;
59644 this[method](type, onClose);
59645 } else if (type === 'error') {
59646 onError._listener = listener;
59647 this[method](type, onError);
59648 } else if (type === 'open') {
59649 onOpen._listener = listener;
59650 this[method](type, onOpen);
59651 } else {
59652 this[method](type, listener);
59653 }
59654 },
59655
59656 /**
59657 * Remove an event listener.
59658 *
59659 * @param {String} type A string representing the event type to remove
59660 * @param {Function} listener The listener to remove
59661 * @public
59662 */
59663 removeEventListener(type, listener) {
59664 const listeners = this.listeners(type);
59665
59666 for (let i = 0; i < listeners.length; i++) {
59667 if (listeners[i] === listener || listeners[i]._listener === listener) {
59668 this.removeListener(type, listeners[i]);
59669 }
59670 }
59671 }
59672};
59673
59674var eventTarget = EventTarget;
59675
59676//
59677// Allowed token characters:
59678//
59679// '!', '#', '$', '%', '&', ''', '*', '+', '-',
59680// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~'
59681//
59682// tokenChars[32] === 0 // ' '
59683// tokenChars[33] === 1 // '!'
59684// tokenChars[34] === 0 // '"'
59685// ...
59686//
59687// prettier-ignore
59688const tokenChars = [
59689 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15
59690 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31
59691 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47
59692 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63
59693 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79
59694 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95
59695 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111
59696 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127
59697];
59698
59699/**
59700 * Adds an offer to the map of extension offers or a parameter to the map of
59701 * parameters.
59702 *
59703 * @param {Object} dest The map of extension offers or parameters
59704 * @param {String} name The extension or parameter name
59705 * @param {(Object|Boolean|String)} elem The extension parameters or the
59706 * parameter value
59707 * @private
59708 */
59709function push(dest, name, elem) {
59710 if (dest[name] === undefined) dest[name] = [elem];
59711 else dest[name].push(elem);
59712}
59713
59714/**
59715 * Parses the `Sec-WebSocket-Extensions` header into an object.
59716 *
59717 * @param {String} header The field value of the header
59718 * @return {Object} The parsed object
59719 * @public
59720 */
59721function parse$8(header) {
59722 const offers = Object.create(null);
59723
59724 if (header === undefined || header === '') return offers;
59725
59726 let params = Object.create(null);
59727 let mustUnescape = false;
59728 let isEscaping = false;
59729 let inQuotes = false;
59730 let extensionName;
59731 let paramName;
59732 let start = -1;
59733 let end = -1;
59734 let i = 0;
59735
59736 for (; i < header.length; i++) {
59737 const code = header.charCodeAt(i);
59738
59739 if (extensionName === undefined) {
59740 if (end === -1 && tokenChars[code] === 1) {
59741 if (start === -1) start = i;
59742 } else if (code === 0x20 /* ' ' */ || code === 0x09 /* '\t' */) {
59743 if (end === -1 && start !== -1) end = i;
59744 } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) {
59745 if (start === -1) {
59746 throw new SyntaxError(`Unexpected character at index ${i}`);
59747 }
59748
59749 if (end === -1) end = i;
59750 const name = header.slice(start, end);
59751 if (code === 0x2c) {
59752 push(offers, name, params);
59753 params = Object.create(null);
59754 } else {
59755 extensionName = name;
59756 }
59757
59758 start = end = -1;
59759 } else {
59760 throw new SyntaxError(`Unexpected character at index ${i}`);
59761 }
59762 } else if (paramName === undefined) {
59763 if (end === -1 && tokenChars[code] === 1) {
59764 if (start === -1) start = i;
59765 } else if (code === 0x20 || code === 0x09) {
59766 if (end === -1 && start !== -1) end = i;
59767 } else if (code === 0x3b || code === 0x2c) {
59768 if (start === -1) {
59769 throw new SyntaxError(`Unexpected character at index ${i}`);
59770 }
59771
59772 if (end === -1) end = i;
59773 push(params, header.slice(start, end), true);
59774 if (code === 0x2c) {
59775 push(offers, extensionName, params);
59776 params = Object.create(null);
59777 extensionName = undefined;
59778 }
59779
59780 start = end = -1;
59781 } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) {
59782 paramName = header.slice(start, i);
59783 start = end = -1;
59784 } else {
59785 throw new SyntaxError(`Unexpected character at index ${i}`);
59786 }
59787 } else {
59788 //
59789 // The value of a quoted-string after unescaping must conform to the
59790 // token ABNF, so only token characters are valid.
59791 // Ref: https://tools.ietf.org/html/rfc6455#section-9.1
59792 //
59793 if (isEscaping) {
59794 if (tokenChars[code] !== 1) {
59795 throw new SyntaxError(`Unexpected character at index ${i}`);
59796 }
59797 if (start === -1) start = i;
59798 else if (!mustUnescape) mustUnescape = true;
59799 isEscaping = false;
59800 } else if (inQuotes) {
59801 if (tokenChars[code] === 1) {
59802 if (start === -1) start = i;
59803 } else if (code === 0x22 /* '"' */ && start !== -1) {
59804 inQuotes = false;
59805 end = i;
59806 } else if (code === 0x5c /* '\' */) {
59807 isEscaping = true;
59808 } else {
59809 throw new SyntaxError(`Unexpected character at index ${i}`);
59810 }
59811 } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) {
59812 inQuotes = true;
59813 } else if (end === -1 && tokenChars[code] === 1) {
59814 if (start === -1) start = i;
59815 } else if (start !== -1 && (code === 0x20 || code === 0x09)) {
59816 if (end === -1) end = i;
59817 } else if (code === 0x3b || code === 0x2c) {
59818 if (start === -1) {
59819 throw new SyntaxError(`Unexpected character at index ${i}`);
59820 }
59821
59822 if (end === -1) end = i;
59823 let value = header.slice(start, end);
59824 if (mustUnescape) {
59825 value = value.replace(/\\/g, '');
59826 mustUnescape = false;
59827 }
59828 push(params, paramName, value);
59829 if (code === 0x2c) {
59830 push(offers, extensionName, params);
59831 params = Object.create(null);
59832 extensionName = undefined;
59833 }
59834
59835 paramName = undefined;
59836 start = end = -1;
59837 } else {
59838 throw new SyntaxError(`Unexpected character at index ${i}`);
59839 }
59840 }
59841 }
59842
59843 if (start === -1 || inQuotes) {
59844 throw new SyntaxError('Unexpected end of input');
59845 }
59846
59847 if (end === -1) end = i;
59848 const token = header.slice(start, end);
59849 if (extensionName === undefined) {
59850 push(offers, token, params);
59851 } else {
59852 if (paramName === undefined) {
59853 push(params, token, true);
59854 } else if (mustUnescape) {
59855 push(params, paramName, token.replace(/\\/g, ''));
59856 } else {
59857 push(params, paramName, token);
59858 }
59859 push(offers, extensionName, params);
59860 }
59861
59862 return offers;
59863}
59864
59865/**
59866 * Builds the `Sec-WebSocket-Extensions` header field value.
59867 *
59868 * @param {Object} extensions The map of extensions and parameters to format
59869 * @return {String} A string representing the given object
59870 * @public
59871 */
59872function format$2(extensions) {
59873 return Object.keys(extensions)
59874 .map((extension) => {
59875 let configurations = extensions[extension];
59876 if (!Array.isArray(configurations)) configurations = [configurations];
59877 return configurations
59878 .map((params) => {
59879 return [extension]
59880 .concat(
59881 Object.keys(params).map((k) => {
59882 let values = params[k];
59883 if (!Array.isArray(values)) values = [values];
59884 return values
59885 .map((v) => (v === true ? k : `${k}=${v}`))
59886 .join('; ');
59887 })
59888 )
59889 .join('; ');
59890 })
59891 .join(', ');
59892 })
59893 .join(', ');
59894}
59895
59896var extension = { format: format$2, parse: parse$8 };
59897
59898const EventEmitter$1 = require$$0__default$6;
59899const https$2 = require$$1__default$2;
59900const http$2 = require$$0__default$8;
59901const net = require$$4__default$1;
59902const tls = require$$4__default$2;
59903const { randomBytes, createHash: createHash$1 } = require$$1__default$1;
59904const { URL: URL$2 } = require$$0__default$7;
59905
59906const PerMessageDeflate$1 = permessageDeflate;
59907const Receiver = receiver;
59908const Sender = sender;
59909const {
59910 BINARY_TYPES,
59911 EMPTY_BUFFER,
59912 GUID: GUID$1,
59913 kStatusCode,
59914 kWebSocket: kWebSocket$1,
59915 NOOP
59916} = constants;
59917const { addEventListener, removeEventListener } = eventTarget;
59918const { format: format$1, parse: parse$7 } = extension;
59919const { toBuffer } = bufferUtil$1.exports;
59920
59921const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];
59922const protocolVersions = [8, 13];
59923const closeTimeout = 30 * 1000;
59924
59925/**
59926 * Class representing a WebSocket.
59927 *
59928 * @extends EventEmitter
59929 */
59930class WebSocket$2 extends EventEmitter$1 {
59931 /**
59932 * Create a new `WebSocket`.
59933 *
59934 * @param {(String|url.URL)} address The URL to which to connect
59935 * @param {(String|String[])} [protocols] The subprotocols
59936 * @param {Object} [options] Connection options
59937 */
59938 constructor(address, protocols, options) {
59939 super();
59940
59941 this._binaryType = BINARY_TYPES[0];
59942 this._closeCode = 1006;
59943 this._closeFrameReceived = false;
59944 this._closeFrameSent = false;
59945 this._closeMessage = '';
59946 this._closeTimer = null;
59947 this._extensions = {};
59948 this._protocol = '';
59949 this._readyState = WebSocket$2.CONNECTING;
59950 this._receiver = null;
59951 this._sender = null;
59952 this._socket = null;
59953
59954 if (address !== null) {
59955 this._bufferedAmount = 0;
59956 this._isServer = false;
59957 this._redirects = 0;
59958
59959 if (Array.isArray(protocols)) {
59960 protocols = protocols.join(', ');
59961 } else if (typeof protocols === 'object' && protocols !== null) {
59962 options = protocols;
59963 protocols = undefined;
59964 }
59965
59966 initAsClient(this, address, protocols, options);
59967 } else {
59968 this._isServer = true;
59969 }
59970 }
59971
59972 /**
59973 * This deviates from the WHATWG interface since ws doesn't support the
59974 * required default "blob" type (instead we define a custom "nodebuffer"
59975 * type).
59976 *
59977 * @type {String}
59978 */
59979 get binaryType() {
59980 return this._binaryType;
59981 }
59982
59983 set binaryType(type) {
59984 if (!BINARY_TYPES.includes(type)) return;
59985
59986 this._binaryType = type;
59987
59988 //
59989 // Allow to change `binaryType` on the fly.
59990 //
59991 if (this._receiver) this._receiver._binaryType = type;
59992 }
59993
59994 /**
59995 * @type {Number}
59996 */
59997 get bufferedAmount() {
59998 if (!this._socket) return this._bufferedAmount;
59999
60000 return this._socket._writableState.length + this._sender._bufferedBytes;
60001 }
60002
60003 /**
60004 * @type {String}
60005 */
60006 get extensions() {
60007 return Object.keys(this._extensions).join();
60008 }
60009
60010 /**
60011 * @type {String}
60012 */
60013 get protocol() {
60014 return this._protocol;
60015 }
60016
60017 /**
60018 * @type {Number}
60019 */
60020 get readyState() {
60021 return this._readyState;
60022 }
60023
60024 /**
60025 * @type {String}
60026 */
60027 get url() {
60028 return this._url;
60029 }
60030
60031 /**
60032 * Set up the socket and the internal resources.
60033 *
60034 * @param {net.Socket} socket The network socket between the server and client
60035 * @param {Buffer} head The first packet of the upgraded stream
60036 * @param {Number} [maxPayload=0] The maximum allowed message size
60037 * @private
60038 */
60039 setSocket(socket, head, maxPayload) {
60040 const receiver = new Receiver(
60041 this.binaryType,
60042 this._extensions,
60043 this._isServer,
60044 maxPayload
60045 );
60046
60047 this._sender = new Sender(socket, this._extensions);
60048 this._receiver = receiver;
60049 this._socket = socket;
60050
60051 receiver[kWebSocket$1] = this;
60052 socket[kWebSocket$1] = this;
60053
60054 receiver.on('conclude', receiverOnConclude);
60055 receiver.on('drain', receiverOnDrain);
60056 receiver.on('error', receiverOnError);
60057 receiver.on('message', receiverOnMessage);
60058 receiver.on('ping', receiverOnPing);
60059 receiver.on('pong', receiverOnPong);
60060
60061 socket.setTimeout(0);
60062 socket.setNoDelay();
60063
60064 if (head.length > 0) socket.unshift(head);
60065
60066 socket.on('close', socketOnClose);
60067 socket.on('data', socketOnData);
60068 socket.on('end', socketOnEnd);
60069 socket.on('error', socketOnError$1);
60070
60071 this._readyState = WebSocket$2.OPEN;
60072 this.emit('open');
60073 }
60074
60075 /**
60076 * Emit the `'close'` event.
60077 *
60078 * @private
60079 */
60080 emitClose() {
60081 if (!this._socket) {
60082 this._readyState = WebSocket$2.CLOSED;
60083 this.emit('close', this._closeCode, this._closeMessage);
60084 return;
60085 }
60086
60087 if (this._extensions[PerMessageDeflate$1.extensionName]) {
60088 this._extensions[PerMessageDeflate$1.extensionName].cleanup();
60089 }
60090
60091 this._receiver.removeAllListeners();
60092 this._readyState = WebSocket$2.CLOSED;
60093 this.emit('close', this._closeCode, this._closeMessage);
60094 }
60095
60096 /**
60097 * Start a closing handshake.
60098 *
60099 * +----------+ +-----------+ +----------+
60100 * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
60101 * | +----------+ +-----------+ +----------+ |
60102 * +----------+ +-----------+ |
60103 * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
60104 * +----------+ +-----------+ |
60105 * | | | +---+ |
60106 * +------------------------+-->|fin| - - - -
60107 * | +---+ | +---+
60108 * - - - - -|fin|<---------------------+
60109 * +---+
60110 *
60111 * @param {Number} [code] Status code explaining why the connection is closing
60112 * @param {String} [data] A string explaining why the connection is closing
60113 * @public
60114 */
60115 close(code, data) {
60116 if (this.readyState === WebSocket$2.CLOSED) return;
60117 if (this.readyState === WebSocket$2.CONNECTING) {
60118 const msg = 'WebSocket was closed before the connection was established';
60119 return abortHandshake$1(this, this._req, msg);
60120 }
60121
60122 if (this.readyState === WebSocket$2.CLOSING) {
60123 if (
60124 this._closeFrameSent &&
60125 (this._closeFrameReceived || this._receiver._writableState.errorEmitted)
60126 ) {
60127 this._socket.end();
60128 }
60129
60130 return;
60131 }
60132
60133 this._readyState = WebSocket$2.CLOSING;
60134 this._sender.close(code, data, !this._isServer, (err) => {
60135 //
60136 // This error is handled by the `'error'` listener on the socket. We only
60137 // want to know if the close frame has been sent here.
60138 //
60139 if (err) return;
60140
60141 this._closeFrameSent = true;
60142
60143 if (
60144 this._closeFrameReceived ||
60145 this._receiver._writableState.errorEmitted
60146 ) {
60147 this._socket.end();
60148 }
60149 });
60150
60151 //
60152 // Specify a timeout for the closing handshake to complete.
60153 //
60154 this._closeTimer = setTimeout(
60155 this._socket.destroy.bind(this._socket),
60156 closeTimeout
60157 );
60158 }
60159
60160 /**
60161 * Send a ping.
60162 *
60163 * @param {*} [data] The data to send
60164 * @param {Boolean} [mask] Indicates whether or not to mask `data`
60165 * @param {Function} [cb] Callback which is executed when the ping is sent
60166 * @public
60167 */
60168 ping(data, mask, cb) {
60169 if (this.readyState === WebSocket$2.CONNECTING) {
60170 throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
60171 }
60172
60173 if (typeof data === 'function') {
60174 cb = data;
60175 data = mask = undefined;
60176 } else if (typeof mask === 'function') {
60177 cb = mask;
60178 mask = undefined;
60179 }
60180
60181 if (typeof data === 'number') data = data.toString();
60182
60183 if (this.readyState !== WebSocket$2.OPEN) {
60184 sendAfterClose(this, data, cb);
60185 return;
60186 }
60187
60188 if (mask === undefined) mask = !this._isServer;
60189 this._sender.ping(data || EMPTY_BUFFER, mask, cb);
60190 }
60191
60192 /**
60193 * Send a pong.
60194 *
60195 * @param {*} [data] The data to send
60196 * @param {Boolean} [mask] Indicates whether or not to mask `data`
60197 * @param {Function} [cb] Callback which is executed when the pong is sent
60198 * @public
60199 */
60200 pong(data, mask, cb) {
60201 if (this.readyState === WebSocket$2.CONNECTING) {
60202 throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
60203 }
60204
60205 if (typeof data === 'function') {
60206 cb = data;
60207 data = mask = undefined;
60208 } else if (typeof mask === 'function') {
60209 cb = mask;
60210 mask = undefined;
60211 }
60212
60213 if (typeof data === 'number') data = data.toString();
60214
60215 if (this.readyState !== WebSocket$2.OPEN) {
60216 sendAfterClose(this, data, cb);
60217 return;
60218 }
60219
60220 if (mask === undefined) mask = !this._isServer;
60221 this._sender.pong(data || EMPTY_BUFFER, mask, cb);
60222 }
60223
60224 /**
60225 * Send a data message.
60226 *
60227 * @param {*} data The message to send
60228 * @param {Object} [options] Options object
60229 * @param {Boolean} [options.compress] Specifies whether or not to compress
60230 * `data`
60231 * @param {Boolean} [options.binary] Specifies whether `data` is binary or
60232 * text
60233 * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
60234 * last one
60235 * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
60236 * @param {Function} [cb] Callback which is executed when data is written out
60237 * @public
60238 */
60239 send(data, options, cb) {
60240 if (this.readyState === WebSocket$2.CONNECTING) {
60241 throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
60242 }
60243
60244 if (typeof options === 'function') {
60245 cb = options;
60246 options = {};
60247 }
60248
60249 if (typeof data === 'number') data = data.toString();
60250
60251 if (this.readyState !== WebSocket$2.OPEN) {
60252 sendAfterClose(this, data, cb);
60253 return;
60254 }
60255
60256 const opts = {
60257 binary: typeof data !== 'string',
60258 mask: !this._isServer,
60259 compress: true,
60260 fin: true,
60261 ...options
60262 };
60263
60264 if (!this._extensions[PerMessageDeflate$1.extensionName]) {
60265 opts.compress = false;
60266 }
60267
60268 this._sender.send(data || EMPTY_BUFFER, opts, cb);
60269 }
60270
60271 /**
60272 * Forcibly close the connection.
60273 *
60274 * @public
60275 */
60276 terminate() {
60277 if (this.readyState === WebSocket$2.CLOSED) return;
60278 if (this.readyState === WebSocket$2.CONNECTING) {
60279 const msg = 'WebSocket was closed before the connection was established';
60280 return abortHandshake$1(this, this._req, msg);
60281 }
60282
60283 if (this._socket) {
60284 this._readyState = WebSocket$2.CLOSING;
60285 this._socket.destroy();
60286 }
60287 }
60288}
60289
60290readyStates.forEach((readyState, i) => {
60291 const descriptor = { enumerable: true, value: i };
60292
60293 Object.defineProperty(WebSocket$2.prototype, readyState, descriptor);
60294 Object.defineProperty(WebSocket$2, readyState, descriptor);
60295});
60296
60297[
60298 'binaryType',
60299 'bufferedAmount',
60300 'extensions',
60301 'protocol',
60302 'readyState',
60303 'url'
60304].forEach((property) => {
60305 Object.defineProperty(WebSocket$2.prototype, property, { enumerable: true });
60306});
60307
60308//
60309// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.
60310// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface
60311//
60312['open', 'error', 'close', 'message'].forEach((method) => {
60313 Object.defineProperty(WebSocket$2.prototype, `on${method}`, {
60314 configurable: true,
60315 enumerable: true,
60316 /**
60317 * Return the listener of the event.
60318 *
60319 * @return {(Function|undefined)} The event listener or `undefined`
60320 * @public
60321 */
60322 get() {
60323 const listeners = this.listeners(method);
60324 for (let i = 0; i < listeners.length; i++) {
60325 if (listeners[i]._listener) return listeners[i]._listener;
60326 }
60327
60328 return undefined;
60329 },
60330 /**
60331 * Add a listener for the event.
60332 *
60333 * @param {Function} listener The listener to add
60334 * @public
60335 */
60336 set(listener) {
60337 const listeners = this.listeners(method);
60338 for (let i = 0; i < listeners.length; i++) {
60339 //
60340 // Remove only the listeners added via `addEventListener`.
60341 //
60342 if (listeners[i]._listener) this.removeListener(method, listeners[i]);
60343 }
60344 this.addEventListener(method, listener);
60345 }
60346 });
60347});
60348
60349WebSocket$2.prototype.addEventListener = addEventListener;
60350WebSocket$2.prototype.removeEventListener = removeEventListener;
60351
60352var websocket = WebSocket$2;
60353
60354/**
60355 * Initialize a WebSocket client.
60356 *
60357 * @param {WebSocket} websocket The client to initialize
60358 * @param {(String|url.URL)} address The URL to which to connect
60359 * @param {String} [protocols] The subprotocols
60360 * @param {Object} [options] Connection options
60361 * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable
60362 * permessage-deflate
60363 * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the
60364 * handshake request
60365 * @param {Number} [options.protocolVersion=13] Value of the
60366 * `Sec-WebSocket-Version` header
60367 * @param {String} [options.origin] Value of the `Origin` or
60368 * `Sec-WebSocket-Origin` header
60369 * @param {Number} [options.maxPayload=104857600] The maximum allowed message
60370 * size
60371 * @param {Boolean} [options.followRedirects=false] Whether or not to follow
60372 * redirects
60373 * @param {Number} [options.maxRedirects=10] The maximum number of redirects
60374 * allowed
60375 * @private
60376 */
60377function initAsClient(websocket, address, protocols, options) {
60378 const opts = {
60379 protocolVersion: protocolVersions[1],
60380 maxPayload: 100 * 1024 * 1024,
60381 perMessageDeflate: true,
60382 followRedirects: false,
60383 maxRedirects: 10,
60384 ...options,
60385 createConnection: undefined,
60386 socketPath: undefined,
60387 hostname: undefined,
60388 protocol: undefined,
60389 timeout: undefined,
60390 method: undefined,
60391 host: undefined,
60392 path: undefined,
60393 port: undefined
60394 };
60395
60396 if (!protocolVersions.includes(opts.protocolVersion)) {
60397 throw new RangeError(
60398 `Unsupported protocol version: ${opts.protocolVersion} ` +
60399 `(supported versions: ${protocolVersions.join(', ')})`
60400 );
60401 }
60402
60403 let parsedUrl;
60404
60405 if (address instanceof URL$2) {
60406 parsedUrl = address;
60407 websocket._url = address.href;
60408 } else {
60409 parsedUrl = new URL$2(address);
60410 websocket._url = address;
60411 }
60412
60413 const isUnixSocket = parsedUrl.protocol === 'ws+unix:';
60414
60415 if (!parsedUrl.host && (!isUnixSocket || !parsedUrl.pathname)) {
60416 throw new Error(`Invalid URL: ${websocket.url}`);
60417 }
60418
60419 const isSecure =
60420 parsedUrl.protocol === 'wss:' || parsedUrl.protocol === 'https:';
60421 const defaultPort = isSecure ? 443 : 80;
60422 const key = randomBytes(16).toString('base64');
60423 const get = isSecure ? https$2.get : http$2.get;
60424 let perMessageDeflate;
60425
60426 opts.createConnection = isSecure ? tlsConnect : netConnect;
60427 opts.defaultPort = opts.defaultPort || defaultPort;
60428 opts.port = parsedUrl.port || defaultPort;
60429 opts.host = parsedUrl.hostname.startsWith('[')
60430 ? parsedUrl.hostname.slice(1, -1)
60431 : parsedUrl.hostname;
60432 opts.headers = {
60433 'Sec-WebSocket-Version': opts.protocolVersion,
60434 'Sec-WebSocket-Key': key,
60435 Connection: 'Upgrade',
60436 Upgrade: 'websocket',
60437 ...opts.headers
60438 };
60439 opts.path = parsedUrl.pathname + parsedUrl.search;
60440 opts.timeout = opts.handshakeTimeout;
60441
60442 if (opts.perMessageDeflate) {
60443 perMessageDeflate = new PerMessageDeflate$1(
60444 opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
60445 false,
60446 opts.maxPayload
60447 );
60448 opts.headers['Sec-WebSocket-Extensions'] = format$1({
60449 [PerMessageDeflate$1.extensionName]: perMessageDeflate.offer()
60450 });
60451 }
60452 if (protocols) {
60453 opts.headers['Sec-WebSocket-Protocol'] = protocols;
60454 }
60455 if (opts.origin) {
60456 if (opts.protocolVersion < 13) {
60457 opts.headers['Sec-WebSocket-Origin'] = opts.origin;
60458 } else {
60459 opts.headers.Origin = opts.origin;
60460 }
60461 }
60462 if (parsedUrl.username || parsedUrl.password) {
60463 opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
60464 }
60465
60466 if (isUnixSocket) {
60467 const parts = opts.path.split(':');
60468
60469 opts.socketPath = parts[0];
60470 opts.path = parts[1];
60471 }
60472
60473 let req = (websocket._req = get(opts));
60474
60475 if (opts.timeout) {
60476 req.on('timeout', () => {
60477 abortHandshake$1(websocket, req, 'Opening handshake has timed out');
60478 });
60479 }
60480
60481 req.on('error', (err) => {
60482 if (req === null || req.aborted) return;
60483
60484 req = websocket._req = null;
60485 websocket._readyState = WebSocket$2.CLOSING;
60486 websocket.emit('error', err);
60487 websocket.emitClose();
60488 });
60489
60490 req.on('response', (res) => {
60491 const location = res.headers.location;
60492 const statusCode = res.statusCode;
60493
60494 if (
60495 location &&
60496 opts.followRedirects &&
60497 statusCode >= 300 &&
60498 statusCode < 400
60499 ) {
60500 if (++websocket._redirects > opts.maxRedirects) {
60501 abortHandshake$1(websocket, req, 'Maximum redirects exceeded');
60502 return;
60503 }
60504
60505 req.abort();
60506
60507 const addr = new URL$2(location, address);
60508
60509 initAsClient(websocket, addr, protocols, options);
60510 } else if (!websocket.emit('unexpected-response', req, res)) {
60511 abortHandshake$1(
60512 websocket,
60513 req,
60514 `Unexpected server response: ${res.statusCode}`
60515 );
60516 }
60517 });
60518
60519 req.on('upgrade', (res, socket, head) => {
60520 websocket.emit('upgrade', res);
60521
60522 //
60523 // The user may have closed the connection from a listener of the `upgrade`
60524 // event.
60525 //
60526 if (websocket.readyState !== WebSocket$2.CONNECTING) return;
60527
60528 req = websocket._req = null;
60529
60530 const digest = createHash$1('sha1')
60531 .update(key + GUID$1)
60532 .digest('base64');
60533
60534 if (res.headers['sec-websocket-accept'] !== digest) {
60535 abortHandshake$1(websocket, socket, 'Invalid Sec-WebSocket-Accept header');
60536 return;
60537 }
60538
60539 const serverProt = res.headers['sec-websocket-protocol'];
60540 const protList = (protocols || '').split(/, */);
60541 let protError;
60542
60543 if (!protocols && serverProt) {
60544 protError = 'Server sent a subprotocol but none was requested';
60545 } else if (protocols && !serverProt) {
60546 protError = 'Server sent no subprotocol';
60547 } else if (serverProt && !protList.includes(serverProt)) {
60548 protError = 'Server sent an invalid subprotocol';
60549 }
60550
60551 if (protError) {
60552 abortHandshake$1(websocket, socket, protError);
60553 return;
60554 }
60555
60556 if (serverProt) websocket._protocol = serverProt;
60557
60558 const secWebSocketExtensions = res.headers['sec-websocket-extensions'];
60559
60560 if (secWebSocketExtensions !== undefined) {
60561 if (!perMessageDeflate) {
60562 const message =
60563 'Server sent a Sec-WebSocket-Extensions header but no extension ' +
60564 'was requested';
60565 abortHandshake$1(websocket, socket, message);
60566 return;
60567 }
60568
60569 let extensions;
60570
60571 try {
60572 extensions = parse$7(secWebSocketExtensions);
60573 } catch (err) {
60574 const message = 'Invalid Sec-WebSocket-Extensions header';
60575 abortHandshake$1(websocket, socket, message);
60576 return;
60577 }
60578
60579 const extensionNames = Object.keys(extensions);
60580
60581 if (extensionNames.length) {
60582 if (
60583 extensionNames.length !== 1 ||
60584 extensionNames[0] !== PerMessageDeflate$1.extensionName
60585 ) {
60586 const message =
60587 'Server indicated an extension that was not requested';
60588 abortHandshake$1(websocket, socket, message);
60589 return;
60590 }
60591
60592 try {
60593 perMessageDeflate.accept(extensions[PerMessageDeflate$1.extensionName]);
60594 } catch (err) {
60595 const message = 'Invalid Sec-WebSocket-Extensions header';
60596 abortHandshake$1(websocket, socket, message);
60597 return;
60598 }
60599
60600 websocket._extensions[PerMessageDeflate$1.extensionName] =
60601 perMessageDeflate;
60602 }
60603 }
60604
60605 websocket.setSocket(socket, head, opts.maxPayload);
60606 });
60607}
60608
60609/**
60610 * Create a `net.Socket` and initiate a connection.
60611 *
60612 * @param {Object} options Connection options
60613 * @return {net.Socket} The newly created socket used to start the connection
60614 * @private
60615 */
60616function netConnect(options) {
60617 options.path = options.socketPath;
60618 return net.connect(options);
60619}
60620
60621/**
60622 * Create a `tls.TLSSocket` and initiate a connection.
60623 *
60624 * @param {Object} options Connection options
60625 * @return {tls.TLSSocket} The newly created socket used to start the connection
60626 * @private
60627 */
60628function tlsConnect(options) {
60629 options.path = undefined;
60630
60631 if (!options.servername && options.servername !== '') {
60632 options.servername = net.isIP(options.host) ? '' : options.host;
60633 }
60634
60635 return tls.connect(options);
60636}
60637
60638/**
60639 * Abort the handshake and emit an error.
60640 *
60641 * @param {WebSocket} websocket The WebSocket instance
60642 * @param {(http.ClientRequest|net.Socket)} stream The request to abort or the
60643 * socket to destroy
60644 * @param {String} message The error message
60645 * @private
60646 */
60647function abortHandshake$1(websocket, stream, message) {
60648 websocket._readyState = WebSocket$2.CLOSING;
60649
60650 const err = new Error(message);
60651 Error.captureStackTrace(err, abortHandshake$1);
60652
60653 if (stream.setHeader) {
60654 stream.abort();
60655
60656 if (stream.socket && !stream.socket.destroyed) {
60657 //
60658 // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if
60659 // called after the request completed. See
60660 // https://github.com/websockets/ws/issues/1869.
60661 //
60662 stream.socket.destroy();
60663 }
60664
60665 stream.once('abort', websocket.emitClose.bind(websocket));
60666 websocket.emit('error', err);
60667 } else {
60668 stream.destroy(err);
60669 stream.once('error', websocket.emit.bind(websocket, 'error'));
60670 stream.once('close', websocket.emitClose.bind(websocket));
60671 }
60672}
60673
60674/**
60675 * Handle cases where the `ping()`, `pong()`, or `send()` methods are called
60676 * when the `readyState` attribute is `CLOSING` or `CLOSED`.
60677 *
60678 * @param {WebSocket} websocket The WebSocket instance
60679 * @param {*} [data] The data to send
60680 * @param {Function} [cb] Callback
60681 * @private
60682 */
60683function sendAfterClose(websocket, data, cb) {
60684 if (data) {
60685 const length = toBuffer(data).length;
60686
60687 //
60688 // The `_bufferedAmount` property is used only when the peer is a client and
60689 // the opening handshake fails. Under these circumstances, in fact, the
60690 // `setSocket()` method is not called, so the `_socket` and `_sender`
60691 // properties are set to `null`.
60692 //
60693 if (websocket._socket) websocket._sender._bufferedBytes += length;
60694 else websocket._bufferedAmount += length;
60695 }
60696
60697 if (cb) {
60698 const err = new Error(
60699 `WebSocket is not open: readyState ${websocket.readyState} ` +
60700 `(${readyStates[websocket.readyState]})`
60701 );
60702 cb(err);
60703 }
60704}
60705
60706/**
60707 * The listener of the `Receiver` `'conclude'` event.
60708 *
60709 * @param {Number} code The status code
60710 * @param {String} reason The reason for closing
60711 * @private
60712 */
60713function receiverOnConclude(code, reason) {
60714 const websocket = this[kWebSocket$1];
60715
60716 websocket._socket.removeListener('data', socketOnData);
60717 websocket._socket.resume();
60718
60719 websocket._closeFrameReceived = true;
60720 websocket._closeMessage = reason;
60721 websocket._closeCode = code;
60722
60723 if (code === 1005) websocket.close();
60724 else websocket.close(code, reason);
60725}
60726
60727/**
60728 * The listener of the `Receiver` `'drain'` event.
60729 *
60730 * @private
60731 */
60732function receiverOnDrain() {
60733 this[kWebSocket$1]._socket.resume();
60734}
60735
60736/**
60737 * The listener of the `Receiver` `'error'` event.
60738 *
60739 * @param {(RangeError|Error)} err The emitted error
60740 * @private
60741 */
60742function receiverOnError(err) {
60743 const websocket = this[kWebSocket$1];
60744
60745 websocket._socket.removeListener('data', socketOnData);
60746 websocket._socket.resume();
60747
60748 websocket.close(err[kStatusCode]);
60749 websocket.emit('error', err);
60750}
60751
60752/**
60753 * The listener of the `Receiver` `'finish'` event.
60754 *
60755 * @private
60756 */
60757function receiverOnFinish() {
60758 this[kWebSocket$1].emitClose();
60759}
60760
60761/**
60762 * The listener of the `Receiver` `'message'` event.
60763 *
60764 * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The message
60765 * @private
60766 */
60767function receiverOnMessage(data) {
60768 this[kWebSocket$1].emit('message', data);
60769}
60770
60771/**
60772 * The listener of the `Receiver` `'ping'` event.
60773 *
60774 * @param {Buffer} data The data included in the ping frame
60775 * @private
60776 */
60777function receiverOnPing(data) {
60778 const websocket = this[kWebSocket$1];
60779
60780 websocket.pong(data, !websocket._isServer, NOOP);
60781 websocket.emit('ping', data);
60782}
60783
60784/**
60785 * The listener of the `Receiver` `'pong'` event.
60786 *
60787 * @param {Buffer} data The data included in the pong frame
60788 * @private
60789 */
60790function receiverOnPong(data) {
60791 this[kWebSocket$1].emit('pong', data);
60792}
60793
60794/**
60795 * The listener of the `net.Socket` `'close'` event.
60796 *
60797 * @private
60798 */
60799function socketOnClose() {
60800 const websocket = this[kWebSocket$1];
60801
60802 this.removeListener('close', socketOnClose);
60803 this.removeListener('end', socketOnEnd);
60804
60805 websocket._readyState = WebSocket$2.CLOSING;
60806
60807 //
60808 // The close frame might not have been received or the `'end'` event emitted,
60809 // for example, if the socket was destroyed due to an error. Ensure that the
60810 // `receiver` stream is closed after writing any remaining buffered data to
60811 // it. If the readable side of the socket is in flowing mode then there is no
60812 // buffered data as everything has been already written and `readable.read()`
60813 // will return `null`. If instead, the socket is paused, any possible buffered
60814 // data will be read as a single chunk and emitted synchronously in a single
60815 // `'data'` event.
60816 //
60817 websocket._socket.read();
60818 websocket._receiver.end();
60819
60820 this.removeListener('data', socketOnData);
60821 this[kWebSocket$1] = undefined;
60822
60823 clearTimeout(websocket._closeTimer);
60824
60825 if (
60826 websocket._receiver._writableState.finished ||
60827 websocket._receiver._writableState.errorEmitted
60828 ) {
60829 websocket.emitClose();
60830 } else {
60831 websocket._receiver.on('error', receiverOnFinish);
60832 websocket._receiver.on('finish', receiverOnFinish);
60833 }
60834}
60835
60836/**
60837 * The listener of the `net.Socket` `'data'` event.
60838 *
60839 * @param {Buffer} chunk A chunk of data
60840 * @private
60841 */
60842function socketOnData(chunk) {
60843 if (!this[kWebSocket$1]._receiver.write(chunk)) {
60844 this.pause();
60845 }
60846}
60847
60848/**
60849 * The listener of the `net.Socket` `'end'` event.
60850 *
60851 * @private
60852 */
60853function socketOnEnd() {
60854 const websocket = this[kWebSocket$1];
60855
60856 websocket._readyState = WebSocket$2.CLOSING;
60857 websocket._receiver.end();
60858 this.end();
60859}
60860
60861/**
60862 * The listener of the `net.Socket` `'error'` event.
60863 *
60864 * @private
60865 */
60866function socketOnError$1() {
60867 const websocket = this[kWebSocket$1];
60868
60869 this.removeListener('error', socketOnError$1);
60870 this.on('error', NOOP);
60871
60872 if (websocket) {
60873 websocket._readyState = WebSocket$2.CLOSING;
60874 this.destroy();
60875 }
60876}
60877
60878const { Duplex } = require$$0__default$2;
60879
60880/**
60881 * Emits the `'close'` event on a stream.
60882 *
60883 * @param {stream.Duplex} The stream.
60884 * @private
60885 */
60886function emitClose$1(stream) {
60887 stream.emit('close');
60888}
60889
60890/**
60891 * The listener of the `'end'` event.
60892 *
60893 * @private
60894 */
60895function duplexOnEnd() {
60896 if (!this.destroyed && this._writableState.finished) {
60897 this.destroy();
60898 }
60899}
60900
60901/**
60902 * The listener of the `'error'` event.
60903 *
60904 * @param {Error} err The error
60905 * @private
60906 */
60907function duplexOnError(err) {
60908 this.removeListener('error', duplexOnError);
60909 this.destroy();
60910 if (this.listenerCount('error') === 0) {
60911 // Do not suppress the throwing behavior.
60912 this.emit('error', err);
60913 }
60914}
60915
60916/**
60917 * Wraps a `WebSocket` in a duplex stream.
60918 *
60919 * @param {WebSocket} ws The `WebSocket` to wrap
60920 * @param {Object} [options] The options for the `Duplex` constructor
60921 * @return {stream.Duplex} The duplex stream
60922 * @public
60923 */
60924function createWebSocketStream(ws, options) {
60925 let resumeOnReceiverDrain = true;
60926 let terminateOnDestroy = true;
60927
60928 function receiverOnDrain() {
60929 if (resumeOnReceiverDrain) ws._socket.resume();
60930 }
60931
60932 if (ws.readyState === ws.CONNECTING) {
60933 ws.once('open', function open() {
60934 ws._receiver.removeAllListeners('drain');
60935 ws._receiver.on('drain', receiverOnDrain);
60936 });
60937 } else {
60938 ws._receiver.removeAllListeners('drain');
60939 ws._receiver.on('drain', receiverOnDrain);
60940 }
60941
60942 const duplex = new Duplex({
60943 ...options,
60944 autoDestroy: false,
60945 emitClose: false,
60946 objectMode: false,
60947 writableObjectMode: false
60948 });
60949
60950 ws.on('message', function message(msg) {
60951 if (!duplex.push(msg)) {
60952 resumeOnReceiverDrain = false;
60953 ws._socket.pause();
60954 }
60955 });
60956
60957 ws.once('error', function error(err) {
60958 if (duplex.destroyed) return;
60959
60960 // Prevent `ws.terminate()` from being called by `duplex._destroy()`.
60961 //
60962 // - If the `'error'` event is emitted before the `'open'` event, then
60963 // `ws.terminate()` is a noop as no socket is assigned.
60964 // - Otherwise, the error is re-emitted by the listener of the `'error'`
60965 // event of the `Receiver` object. The listener already closes the
60966 // connection by calling `ws.close()`. This allows a close frame to be
60967 // sent to the other peer. If `ws.terminate()` is called right after this,
60968 // then the close frame might not be sent.
60969 terminateOnDestroy = false;
60970 duplex.destroy(err);
60971 });
60972
60973 ws.once('close', function close() {
60974 if (duplex.destroyed) return;
60975
60976 duplex.push(null);
60977 });
60978
60979 duplex._destroy = function (err, callback) {
60980 if (ws.readyState === ws.CLOSED) {
60981 callback(err);
60982 process.nextTick(emitClose$1, duplex);
60983 return;
60984 }
60985
60986 let called = false;
60987
60988 ws.once('error', function error(err) {
60989 called = true;
60990 callback(err);
60991 });
60992
60993 ws.once('close', function close() {
60994 if (!called) callback(err);
60995 process.nextTick(emitClose$1, duplex);
60996 });
60997
60998 if (terminateOnDestroy) ws.terminate();
60999 };
61000
61001 duplex._final = function (callback) {
61002 if (ws.readyState === ws.CONNECTING) {
61003 ws.once('open', function open() {
61004 duplex._final(callback);
61005 });
61006 return;
61007 }
61008
61009 // If the value of the `_socket` property is `null` it means that `ws` is a
61010 // client websocket and the handshake failed. In fact, when this happens, a
61011 // socket is never assigned to the websocket. Wait for the `'error'` event
61012 // that will be emitted by the websocket.
61013 if (ws._socket === null) return;
61014
61015 if (ws._socket._writableState.finished) {
61016 callback();
61017 if (duplex._readableState.endEmitted) duplex.destroy();
61018 } else {
61019 ws._socket.once('finish', function finish() {
61020 // `duplex` is not destroyed here because the `'end'` event will be
61021 // emitted on `duplex` after this `'finish'` event. The EOF signaling
61022 // `null` chunk is, in fact, pushed when the websocket emits `'close'`.
61023 callback();
61024 });
61025 ws.close();
61026 }
61027 };
61028
61029 duplex._read = function () {
61030 if (ws.readyState === ws.OPEN && !resumeOnReceiverDrain) {
61031 resumeOnReceiverDrain = true;
61032 if (!ws._receiver._writableState.needDrain) ws._socket.resume();
61033 }
61034 };
61035
61036 duplex._write = function (chunk, encoding, callback) {
61037 if (ws.readyState === ws.CONNECTING) {
61038 ws.once('open', function open() {
61039 duplex._write(chunk, encoding, callback);
61040 });
61041 return;
61042 }
61043
61044 ws.send(chunk, callback);
61045 };
61046
61047 duplex.on('end', duplexOnEnd);
61048 duplex.on('error', duplexOnError);
61049 return duplex;
61050}
61051
61052var stream$2 = createWebSocketStream;
61053
61054const EventEmitter = require$$0__default$6;
61055const { createHash } = require$$1__default$1;
61056const { createServer: createServer$1, STATUS_CODES } = require$$0__default$8;
61057
61058const PerMessageDeflate = permessageDeflate;
61059const WebSocket$1 = websocket;
61060const { format, parse: parse$6 } = extension;
61061const { GUID, kWebSocket } = constants;
61062
61063const keyRegex = /^[+/0-9A-Za-z]{22}==$/;
61064
61065/**
61066 * Class representing a WebSocket server.
61067 *
61068 * @extends EventEmitter
61069 */
61070class WebSocketServer extends EventEmitter {
61071 /**
61072 * Create a `WebSocketServer` instance.
61073 *
61074 * @param {Object} options Configuration options
61075 * @param {Number} [options.backlog=511] The maximum length of the queue of
61076 * pending connections
61077 * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
61078 * track clients
61079 * @param {Function} [options.handleProtocols] A hook to handle protocols
61080 * @param {String} [options.host] The hostname where to bind the server
61081 * @param {Number} [options.maxPayload=104857600] The maximum allowed message
61082 * size
61083 * @param {Boolean} [options.noServer=false] Enable no server mode
61084 * @param {String} [options.path] Accept only connections matching this path
61085 * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
61086 * permessage-deflate
61087 * @param {Number} [options.port] The port where to bind the server
61088 * @param {http.Server} [options.server] A pre-created HTTP/S server to use
61089 * @param {Function} [options.verifyClient] A hook to reject connections
61090 * @param {Function} [callback] A listener for the `listening` event
61091 */
61092 constructor(options, callback) {
61093 super();
61094
61095 options = {
61096 maxPayload: 100 * 1024 * 1024,
61097 perMessageDeflate: false,
61098 handleProtocols: null,
61099 clientTracking: true,
61100 verifyClient: null,
61101 noServer: false,
61102 backlog: null, // use default (511 as implemented in net.js)
61103 server: null,
61104 host: null,
61105 path: null,
61106 port: null,
61107 ...options
61108 };
61109
61110 if (options.port == null && !options.server && !options.noServer) {
61111 throw new TypeError(
61112 'One of the "port", "server", or "noServer" options must be specified'
61113 );
61114 }
61115
61116 if (options.port != null) {
61117 this._server = createServer$1((req, res) => {
61118 const body = STATUS_CODES[426];
61119
61120 res.writeHead(426, {
61121 'Content-Length': body.length,
61122 'Content-Type': 'text/plain'
61123 });
61124 res.end(body);
61125 });
61126 this._server.listen(
61127 options.port,
61128 options.host,
61129 options.backlog,
61130 callback
61131 );
61132 } else if (options.server) {
61133 this._server = options.server;
61134 }
61135
61136 if (this._server) {
61137 const emitConnection = this.emit.bind(this, 'connection');
61138
61139 this._removeListeners = addListeners(this._server, {
61140 listening: this.emit.bind(this, 'listening'),
61141 error: this.emit.bind(this, 'error'),
61142 upgrade: (req, socket, head) => {
61143 this.handleUpgrade(req, socket, head, emitConnection);
61144 }
61145 });
61146 }
61147
61148 if (options.perMessageDeflate === true) options.perMessageDeflate = {};
61149 if (options.clientTracking) this.clients = new Set();
61150 this.options = options;
61151 }
61152
61153 /**
61154 * Returns the bound address, the address family name, and port of the server
61155 * as reported by the operating system if listening on an IP socket.
61156 * If the server is listening on a pipe or UNIX domain socket, the name is
61157 * returned as a string.
61158 *
61159 * @return {(Object|String|null)} The address of the server
61160 * @public
61161 */
61162 address() {
61163 if (this.options.noServer) {
61164 throw new Error('The server is operating in "noServer" mode');
61165 }
61166
61167 if (!this._server) return null;
61168 return this._server.address();
61169 }
61170
61171 /**
61172 * Close the server.
61173 *
61174 * @param {Function} [cb] Callback
61175 * @public
61176 */
61177 close(cb) {
61178 if (cb) this.once('close', cb);
61179
61180 //
61181 // Terminate all associated clients.
61182 //
61183 if (this.clients) {
61184 for (const client of this.clients) client.terminate();
61185 }
61186
61187 const server = this._server;
61188
61189 if (server) {
61190 this._removeListeners();
61191 this._removeListeners = this._server = null;
61192
61193 //
61194 // Close the http server if it was internally created.
61195 //
61196 if (this.options.port != null) {
61197 server.close(() => this.emit('close'));
61198 return;
61199 }
61200 }
61201
61202 process.nextTick(emitClose, this);
61203 }
61204
61205 /**
61206 * See if a given request should be handled by this server instance.
61207 *
61208 * @param {http.IncomingMessage} req Request object to inspect
61209 * @return {Boolean} `true` if the request is valid, else `false`
61210 * @public
61211 */
61212 shouldHandle(req) {
61213 if (this.options.path) {
61214 const index = req.url.indexOf('?');
61215 const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
61216
61217 if (pathname !== this.options.path) return false;
61218 }
61219
61220 return true;
61221 }
61222
61223 /**
61224 * Handle a HTTP Upgrade request.
61225 *
61226 * @param {http.IncomingMessage} req The request object
61227 * @param {net.Socket} socket The network socket between the server and client
61228 * @param {Buffer} head The first packet of the upgraded stream
61229 * @param {Function} cb Callback
61230 * @public
61231 */
61232 handleUpgrade(req, socket, head, cb) {
61233 socket.on('error', socketOnError);
61234
61235 const key =
61236 req.headers['sec-websocket-key'] !== undefined
61237 ? req.headers['sec-websocket-key'].trim()
61238 : false;
61239 const version = +req.headers['sec-websocket-version'];
61240 const extensions = {};
61241
61242 if (
61243 req.method !== 'GET' ||
61244 req.headers.upgrade.toLowerCase() !== 'websocket' ||
61245 !key ||
61246 !keyRegex.test(key) ||
61247 (version !== 8 && version !== 13) ||
61248 !this.shouldHandle(req)
61249 ) {
61250 return abortHandshake(socket, 400);
61251 }
61252
61253 if (this.options.perMessageDeflate) {
61254 const perMessageDeflate = new PerMessageDeflate(
61255 this.options.perMessageDeflate,
61256 true,
61257 this.options.maxPayload
61258 );
61259
61260 try {
61261 const offers = parse$6(req.headers['sec-websocket-extensions']);
61262
61263 if (offers[PerMessageDeflate.extensionName]) {
61264 perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
61265 extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
61266 }
61267 } catch (err) {
61268 return abortHandshake(socket, 400);
61269 }
61270 }
61271
61272 //
61273 // Optionally call external client verification handler.
61274 //
61275 if (this.options.verifyClient) {
61276 const info = {
61277 origin:
61278 req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],
61279 secure: !!(req.socket.authorized || req.socket.encrypted),
61280 req
61281 };
61282
61283 if (this.options.verifyClient.length === 2) {
61284 this.options.verifyClient(info, (verified, code, message, headers) => {
61285 if (!verified) {
61286 return abortHandshake(socket, code || 401, message, headers);
61287 }
61288
61289 this.completeUpgrade(key, extensions, req, socket, head, cb);
61290 });
61291 return;
61292 }
61293
61294 if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
61295 }
61296
61297 this.completeUpgrade(key, extensions, req, socket, head, cb);
61298 }
61299
61300 /**
61301 * Upgrade the connection to WebSocket.
61302 *
61303 * @param {String} key The value of the `Sec-WebSocket-Key` header
61304 * @param {Object} extensions The accepted extensions
61305 * @param {http.IncomingMessage} req The request object
61306 * @param {net.Socket} socket The network socket between the server and client
61307 * @param {Buffer} head The first packet of the upgraded stream
61308 * @param {Function} cb Callback
61309 * @throws {Error} If called more than once with the same socket
61310 * @private
61311 */
61312 completeUpgrade(key, extensions, req, socket, head, cb) {
61313 //
61314 // Destroy the socket if the client has already sent a FIN packet.
61315 //
61316 if (!socket.readable || !socket.writable) return socket.destroy();
61317
61318 if (socket[kWebSocket]) {
61319 throw new Error(
61320 'server.handleUpgrade() was called more than once with the same ' +
61321 'socket, possibly due to a misconfiguration'
61322 );
61323 }
61324
61325 const digest = createHash('sha1')
61326 .update(key + GUID)
61327 .digest('base64');
61328
61329 const headers = [
61330 'HTTP/1.1 101 Switching Protocols',
61331 'Upgrade: websocket',
61332 'Connection: Upgrade',
61333 `Sec-WebSocket-Accept: ${digest}`
61334 ];
61335
61336 const ws = new WebSocket$1(null);
61337 let protocol = req.headers['sec-websocket-protocol'];
61338
61339 if (protocol) {
61340 protocol = protocol.split(',').map(trim);
61341
61342 //
61343 // Optionally call external protocol selection handler.
61344 //
61345 if (this.options.handleProtocols) {
61346 protocol = this.options.handleProtocols(protocol, req);
61347 } else {
61348 protocol = protocol[0];
61349 }
61350
61351 if (protocol) {
61352 headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
61353 ws._protocol = protocol;
61354 }
61355 }
61356
61357 if (extensions[PerMessageDeflate.extensionName]) {
61358 const params = extensions[PerMessageDeflate.extensionName].params;
61359 const value = format({
61360 [PerMessageDeflate.extensionName]: [params]
61361 });
61362 headers.push(`Sec-WebSocket-Extensions: ${value}`);
61363 ws._extensions = extensions;
61364 }
61365
61366 //
61367 // Allow external modification/inspection of handshake headers.
61368 //
61369 this.emit('headers', headers, req);
61370
61371 socket.write(headers.concat('\r\n').join('\r\n'));
61372 socket.removeListener('error', socketOnError);
61373
61374 ws.setSocket(socket, head, this.options.maxPayload);
61375
61376 if (this.clients) {
61377 this.clients.add(ws);
61378 ws.on('close', () => this.clients.delete(ws));
61379 }
61380
61381 cb(ws, req);
61382 }
61383}
61384
61385var websocketServer = WebSocketServer;
61386
61387/**
61388 * Add event listeners on an `EventEmitter` using a map of <event, listener>
61389 * pairs.
61390 *
61391 * @param {EventEmitter} server The event emitter
61392 * @param {Object.<String, Function>} map The listeners to add
61393 * @return {Function} A function that will remove the added listeners when
61394 * called
61395 * @private
61396 */
61397function addListeners(server, map) {
61398 for (const event of Object.keys(map)) server.on(event, map[event]);
61399
61400 return function removeListeners() {
61401 for (const event of Object.keys(map)) {
61402 server.removeListener(event, map[event]);
61403 }
61404 };
61405}
61406
61407/**
61408 * Emit a `'close'` event on an `EventEmitter`.
61409 *
61410 * @param {EventEmitter} server The event emitter
61411 * @private
61412 */
61413function emitClose(server) {
61414 server.emit('close');
61415}
61416
61417/**
61418 * Handle premature socket errors.
61419 *
61420 * @private
61421 */
61422function socketOnError() {
61423 this.destroy();
61424}
61425
61426/**
61427 * Close the connection when preconditions are not fulfilled.
61428 *
61429 * @param {net.Socket} socket The socket of the upgrade request
61430 * @param {Number} code The HTTP response status code
61431 * @param {String} [message] The HTTP response body
61432 * @param {Object} [headers] Additional HTTP response headers
61433 * @private
61434 */
61435function abortHandshake(socket, code, message, headers) {
61436 if (socket.writable) {
61437 message = message || STATUS_CODES[code];
61438 headers = {
61439 Connection: 'close',
61440 'Content-Type': 'text/html',
61441 'Content-Length': Buffer.byteLength(message),
61442 ...headers
61443 };
61444
61445 socket.write(
61446 `HTTP/1.1 ${code} ${STATUS_CODES[code]}\r\n` +
61447 Object.keys(headers)
61448 .map((h) => `${h}: ${headers[h]}`)
61449 .join('\r\n') +
61450 '\r\n\r\n' +
61451 message
61452 );
61453 }
61454
61455 socket.removeListener('error', socketOnError);
61456 socket.destroy();
61457}
61458
61459/**
61460 * Remove whitespace characters from both ends of a string.
61461 *
61462 * @param {String} str The string
61463 * @return {String} A new string representing `str` stripped of whitespace
61464 * characters from both its beginning and end
61465 * @private
61466 */
61467function trim(str) {
61468 return str.trim();
61469}
61470
61471const WebSocket = websocket;
61472
61473WebSocket.createWebSocketStream = stream$2;
61474WebSocket.Server = websocketServer;
61475WebSocket.Receiver = receiver;
61476WebSocket.Sender = sender;
61477
61478var ws = WebSocket;
61479
61480const HMR_HEADER = 'vite-hmr';
61481function createWebSocketServer(server, config, httpsOptions) {
61482 let wss;
61483 let httpsServer = undefined;
61484 const hmr = typeof config.server.hmr === 'object' && config.server.hmr;
61485 const wsServer = (hmr && hmr.server) || server;
61486 if (wsServer) {
61487 wss = new ws.Server({ noServer: true });
61488 wsServer.on('upgrade', (req, socket, head) => {
61489 if (req.headers['sec-websocket-protocol'] === HMR_HEADER) {
61490 wss.handleUpgrade(req, socket, head, (ws) => {
61491 wss.emit('connection', ws, req);
61492 });
61493 }
61494 });
61495 }
61496 else {
61497 const websocketServerOptions = {};
61498 const port = (hmr && hmr.port) || 24678;
61499 if (httpsOptions) {
61500 // if we're serving the middlewares over https, the ws library doesn't support automatically creating an https server, so we need to do it ourselves
61501 // create an inline https server and mount the websocket server to it
61502 httpsServer = require$$1$4.createServer(httpsOptions, (req, res) => {
61503 const statusCode = 426;
61504 const body = require$$0$d.STATUS_CODES[statusCode];
61505 if (!body)
61506 throw new Error(`No body text found for the ${statusCode} status code`);
61507 res.writeHead(statusCode, {
61508 'Content-Length': body.length,
61509 'Content-Type': 'text/plain'
61510 });
61511 res.end(body);
61512 });
61513 httpsServer.listen(port);
61514 websocketServerOptions.server = httpsServer;
61515 }
61516 else {
61517 // we don't need to serve over https, just let ws handle its own server
61518 websocketServerOptions.port = port;
61519 }
61520 // vite dev server in middleware mode
61521 wss = new ws.Server(websocketServerOptions);
61522 }
61523 wss.on('connection', (socket) => {
61524 socket.send(JSON.stringify({ type: 'connected' }));
61525 if (bufferedError) {
61526 socket.send(JSON.stringify(bufferedError));
61527 bufferedError = null;
61528 }
61529 });
61530 wss.on('error', (e) => {
61531 if (e.code !== 'EADDRINUSE') {
61532 config.logger.error(source.red(`WebSocket server error:\n${e.stack || e.message}`));
61533 }
61534 });
61535 // On page reloads, if a file fails to compile and returns 500, the server
61536 // sends the error payload before the client connection is established.
61537 // If we have no open clients, buffer the error and send it to the next
61538 // connected client.
61539 let bufferedError = null;
61540 return {
61541 send(payload) {
61542 if (payload.type === 'error' && !wss.clients.size) {
61543 bufferedError = payload;
61544 return;
61545 }
61546 const stringified = JSON.stringify(payload);
61547 wss.clients.forEach((client) => {
61548 if (client.readyState === ws.OPEN) {
61549 client.send(stringified);
61550 }
61551 });
61552 },
61553 close() {
61554 return new Promise((resolve, reject) => {
61555 wss.close((err) => {
61556 if (err) {
61557 reject(err);
61558 }
61559 else {
61560 if (httpsServer) {
61561 httpsServer.close((err) => {
61562 if (err) {
61563 reject(err);
61564 }
61565 else {
61566 resolve();
61567 }
61568 });
61569 }
61570 else {
61571 resolve();
61572 }
61573 }
61574 });
61575 });
61576 }
61577 };
61578}
61579
61580// this middleware is only active when (config.base !== '/')
61581function baseMiddleware({ config }) {
61582 const base = config.base;
61583 // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
61584 return function viteBaseMiddleware(req, res, next) {
61585 var _a;
61586 const url = req.url;
61587 const parsed = require$$0$b.parse(url);
61588 const path = parsed.pathname || '/';
61589 if (path.startsWith(base)) {
61590 // rewrite url to remove base.. this ensures that other middleware does
61591 // not need to consider base being prepended or not
61592 req.url = url.replace(base, '/');
61593 return next();
61594 }
61595 // skip redirect and error fallback on middleware mode, #4057
61596 if (config.server.middlewareMode) {
61597 return next();
61598 }
61599 if (path === '/' || path === '/index.html') {
61600 // redirect root visit to based url
61601 res.writeHead(302, {
61602 Location: base
61603 });
61604 res.end();
61605 return;
61606 }
61607 else if ((_a = req.headers.accept) === null || _a === void 0 ? void 0 : _a.includes('text/html')) {
61608 // non-based page visit
61609 res.statusCode = 404;
61610 res.end(`The server is configured with a public base URL of ${base} - ` +
61611 `did you mean to visit ${base}${url.slice(1)} instead?`);
61612 return;
61613 }
61614 next();
61615 };
61616}
61617
61618var httpProxy$2 = {exports: {}};
61619
61620var eventemitter3 = {exports: {}};
61621
61622(function (module) {
61623
61624var has = Object.prototype.hasOwnProperty
61625 , prefix = '~';
61626
61627/**
61628 * Constructor to create a storage for our `EE` objects.
61629 * An `Events` instance is a plain object whose properties are event names.
61630 *
61631 * @constructor
61632 * @private
61633 */
61634function Events() {}
61635
61636//
61637// We try to not inherit from `Object.prototype`. In some engines creating an
61638// instance in this way is faster than calling `Object.create(null)` directly.
61639// If `Object.create(null)` is not supported we prefix the event names with a
61640// character to make sure that the built-in object properties are not
61641// overridden or used as an attack vector.
61642//
61643if (Object.create) {
61644 Events.prototype = Object.create(null);
61645
61646 //
61647 // This hack is needed because the `__proto__` property is still inherited in
61648 // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
61649 //
61650 if (!new Events().__proto__) prefix = false;
61651}
61652
61653/**
61654 * Representation of a single event listener.
61655 *
61656 * @param {Function} fn The listener function.
61657 * @param {*} context The context to invoke the listener with.
61658 * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
61659 * @constructor
61660 * @private
61661 */
61662function EE(fn, context, once) {
61663 this.fn = fn;
61664 this.context = context;
61665 this.once = once || false;
61666}
61667
61668/**
61669 * Add a listener for a given event.
61670 *
61671 * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
61672 * @param {(String|Symbol)} event The event name.
61673 * @param {Function} fn The listener function.
61674 * @param {*} context The context to invoke the listener with.
61675 * @param {Boolean} once Specify if the listener is a one-time listener.
61676 * @returns {EventEmitter}
61677 * @private
61678 */
61679function addListener(emitter, event, fn, context, once) {
61680 if (typeof fn !== 'function') {
61681 throw new TypeError('The listener must be a function');
61682 }
61683
61684 var listener = new EE(fn, context || emitter, once)
61685 , evt = prefix ? prefix + event : event;
61686
61687 if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
61688 else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
61689 else emitter._events[evt] = [emitter._events[evt], listener];
61690
61691 return emitter;
61692}
61693
61694/**
61695 * Clear event by name.
61696 *
61697 * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
61698 * @param {(String|Symbol)} evt The Event name.
61699 * @private
61700 */
61701function clearEvent(emitter, evt) {
61702 if (--emitter._eventsCount === 0) emitter._events = new Events();
61703 else delete emitter._events[evt];
61704}
61705
61706/**
61707 * Minimal `EventEmitter` interface that is molded against the Node.js
61708 * `EventEmitter` interface.
61709 *
61710 * @constructor
61711 * @public
61712 */
61713function EventEmitter() {
61714 this._events = new Events();
61715 this._eventsCount = 0;
61716}
61717
61718/**
61719 * Return an array listing the events for which the emitter has registered
61720 * listeners.
61721 *
61722 * @returns {Array}
61723 * @public
61724 */
61725EventEmitter.prototype.eventNames = function eventNames() {
61726 var names = []
61727 , events
61728 , name;
61729
61730 if (this._eventsCount === 0) return names;
61731
61732 for (name in (events = this._events)) {
61733 if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
61734 }
61735
61736 if (Object.getOwnPropertySymbols) {
61737 return names.concat(Object.getOwnPropertySymbols(events));
61738 }
61739
61740 return names;
61741};
61742
61743/**
61744 * Return the listeners registered for a given event.
61745 *
61746 * @param {(String|Symbol)} event The event name.
61747 * @returns {Array} The registered listeners.
61748 * @public
61749 */
61750EventEmitter.prototype.listeners = function listeners(event) {
61751 var evt = prefix ? prefix + event : event
61752 , handlers = this._events[evt];
61753
61754 if (!handlers) return [];
61755 if (handlers.fn) return [handlers.fn];
61756
61757 for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
61758 ee[i] = handlers[i].fn;
61759 }
61760
61761 return ee;
61762};
61763
61764/**
61765 * Return the number of listeners listening to a given event.
61766 *
61767 * @param {(String|Symbol)} event The event name.
61768 * @returns {Number} The number of listeners.
61769 * @public
61770 */
61771EventEmitter.prototype.listenerCount = function listenerCount(event) {
61772 var evt = prefix ? prefix + event : event
61773 , listeners = this._events[evt];
61774
61775 if (!listeners) return 0;
61776 if (listeners.fn) return 1;
61777 return listeners.length;
61778};
61779
61780/**
61781 * Calls each of the listeners registered for a given event.
61782 *
61783 * @param {(String|Symbol)} event The event name.
61784 * @returns {Boolean} `true` if the event had listeners, else `false`.
61785 * @public
61786 */
61787EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
61788 var evt = prefix ? prefix + event : event;
61789
61790 if (!this._events[evt]) return false;
61791
61792 var listeners = this._events[evt]
61793 , len = arguments.length
61794 , args
61795 , i;
61796
61797 if (listeners.fn) {
61798 if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
61799
61800 switch (len) {
61801 case 1: return listeners.fn.call(listeners.context), true;
61802 case 2: return listeners.fn.call(listeners.context, a1), true;
61803 case 3: return listeners.fn.call(listeners.context, a1, a2), true;
61804 case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
61805 case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
61806 case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
61807 }
61808
61809 for (i = 1, args = new Array(len -1); i < len; i++) {
61810 args[i - 1] = arguments[i];
61811 }
61812
61813 listeners.fn.apply(listeners.context, args);
61814 } else {
61815 var length = listeners.length
61816 , j;
61817
61818 for (i = 0; i < length; i++) {
61819 if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
61820
61821 switch (len) {
61822 case 1: listeners[i].fn.call(listeners[i].context); break;
61823 case 2: listeners[i].fn.call(listeners[i].context, a1); break;
61824 case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
61825 case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
61826 default:
61827 if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
61828 args[j - 1] = arguments[j];
61829 }
61830
61831 listeners[i].fn.apply(listeners[i].context, args);
61832 }
61833 }
61834 }
61835
61836 return true;
61837};
61838
61839/**
61840 * Add a listener for a given event.
61841 *
61842 * @param {(String|Symbol)} event The event name.
61843 * @param {Function} fn The listener function.
61844 * @param {*} [context=this] The context to invoke the listener with.
61845 * @returns {EventEmitter} `this`.
61846 * @public
61847 */
61848EventEmitter.prototype.on = function on(event, fn, context) {
61849 return addListener(this, event, fn, context, false);
61850};
61851
61852/**
61853 * Add a one-time listener for a given event.
61854 *
61855 * @param {(String|Symbol)} event The event name.
61856 * @param {Function} fn The listener function.
61857 * @param {*} [context=this] The context to invoke the listener with.
61858 * @returns {EventEmitter} `this`.
61859 * @public
61860 */
61861EventEmitter.prototype.once = function once(event, fn, context) {
61862 return addListener(this, event, fn, context, true);
61863};
61864
61865/**
61866 * Remove the listeners of a given event.
61867 *
61868 * @param {(String|Symbol)} event The event name.
61869 * @param {Function} fn Only remove the listeners that match this function.
61870 * @param {*} context Only remove the listeners that have this context.
61871 * @param {Boolean} once Only remove one-time listeners.
61872 * @returns {EventEmitter} `this`.
61873 * @public
61874 */
61875EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
61876 var evt = prefix ? prefix + event : event;
61877
61878 if (!this._events[evt]) return this;
61879 if (!fn) {
61880 clearEvent(this, evt);
61881 return this;
61882 }
61883
61884 var listeners = this._events[evt];
61885
61886 if (listeners.fn) {
61887 if (
61888 listeners.fn === fn &&
61889 (!once || listeners.once) &&
61890 (!context || listeners.context === context)
61891 ) {
61892 clearEvent(this, evt);
61893 }
61894 } else {
61895 for (var i = 0, events = [], length = listeners.length; i < length; i++) {
61896 if (
61897 listeners[i].fn !== fn ||
61898 (once && !listeners[i].once) ||
61899 (context && listeners[i].context !== context)
61900 ) {
61901 events.push(listeners[i]);
61902 }
61903 }
61904
61905 //
61906 // Reset the array, or remove it completely if we have no more listeners.
61907 //
61908 if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
61909 else clearEvent(this, evt);
61910 }
61911
61912 return this;
61913};
61914
61915/**
61916 * Remove all listeners, or those of the specified event.
61917 *
61918 * @param {(String|Symbol)} [event] The event name.
61919 * @returns {EventEmitter} `this`.
61920 * @public
61921 */
61922EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
61923 var evt;
61924
61925 if (event) {
61926 evt = prefix ? prefix + event : event;
61927 if (this._events[evt]) clearEvent(this, evt);
61928 } else {
61929 this._events = new Events();
61930 this._eventsCount = 0;
61931 }
61932
61933 return this;
61934};
61935
61936//
61937// Alias methods names because people roll like that.
61938//
61939EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
61940EventEmitter.prototype.addListener = EventEmitter.prototype.on;
61941
61942//
61943// Expose the prefix.
61944//
61945EventEmitter.prefixed = prefix;
61946
61947//
61948// Allow `EventEmitter` to be imported as module namespace.
61949//
61950EventEmitter.EventEmitter = EventEmitter;
61951
61952//
61953// Expose the module.
61954//
61955{
61956 module.exports = EventEmitter;
61957}
61958}(eventemitter3));
61959
61960var common$4 = {};
61961
61962/**
61963 * Check if we're required to add a port number.
61964 *
61965 * @see https://url.spec.whatwg.org/#default-port
61966 * @param {Number|String} port Port number we need to check
61967 * @param {String} protocol Protocol we need to check against.
61968 * @returns {Boolean} Is it a default port for the given protocol
61969 * @api private
61970 */
61971var requiresPort = function required(port, protocol) {
61972 protocol = protocol.split(':')[0];
61973 port = +port;
61974
61975 if (!port) return false;
61976
61977 switch (protocol) {
61978 case 'http':
61979 case 'ws':
61980 return port !== 80;
61981
61982 case 'https':
61983 case 'wss':
61984 return port !== 443;
61985
61986 case 'ftp':
61987 return port !== 21;
61988
61989 case 'gopher':
61990 return port !== 70;
61991
61992 case 'file':
61993 return false;
61994 }
61995
61996 return port !== 0;
61997};
61998
61999(function (exports) {
62000var common = exports,
62001 url = require$$0__default$7,
62002 extend = require$$0__default$3._extend,
62003 required = requiresPort;
62004
62005var upgradeHeader = /(^|,)\s*upgrade\s*($|,)/i,
62006 isSSL = /^https|wss/;
62007
62008/**
62009 * Simple Regex for testing if protocol is https
62010 */
62011common.isSSL = isSSL;
62012/**
62013 * Copies the right headers from `options` and `req` to
62014 * `outgoing` which is then used to fire the proxied
62015 * request.
62016 *
62017 * Examples:
62018 *
62019 * common.setupOutgoing(outgoing, options, req)
62020 * // => { host: ..., hostname: ...}
62021 *
62022 * @param {Object} Outgoing Base object to be filled with required properties
62023 * @param {Object} Options Config object passed to the proxy
62024 * @param {ClientRequest} Req Request Object
62025 * @param {String} Forward String to select forward or target
62026
62027 * @return {Object} Outgoing Object with all required properties set
62028 *
62029 * @api private
62030 */
62031
62032common.setupOutgoing = function(outgoing, options, req, forward) {
62033 outgoing.port = options[forward || 'target'].port ||
62034 (isSSL.test(options[forward || 'target'].protocol) ? 443 : 80);
62035
62036 ['host', 'hostname', 'socketPath', 'pfx', 'key',
62037 'passphrase', 'cert', 'ca', 'ciphers', 'secureProtocol'].forEach(
62038 function(e) { outgoing[e] = options[forward || 'target'][e]; }
62039 );
62040
62041 outgoing.method = options.method || req.method;
62042 outgoing.headers = extend({}, req.headers);
62043
62044 if (options.headers){
62045 extend(outgoing.headers, options.headers);
62046 }
62047
62048 if (options.auth) {
62049 outgoing.auth = options.auth;
62050 }
62051
62052 if (options.ca) {
62053 outgoing.ca = options.ca;
62054 }
62055
62056 if (isSSL.test(options[forward || 'target'].protocol)) {
62057 outgoing.rejectUnauthorized = (typeof options.secure === "undefined") ? true : options.secure;
62058 }
62059
62060
62061 outgoing.agent = options.agent || false;
62062 outgoing.localAddress = options.localAddress;
62063
62064 //
62065 // Remark: If we are false and not upgrading, set the connection: close. This is the right thing to do
62066 // as node core doesn't handle this COMPLETELY properly yet.
62067 //
62068 if (!outgoing.agent) {
62069 outgoing.headers = outgoing.headers || {};
62070 if (typeof outgoing.headers.connection !== 'string'
62071 || !upgradeHeader.test(outgoing.headers.connection)
62072 ) { outgoing.headers.connection = 'close'; }
62073 }
62074
62075
62076 // the final path is target path + relative path requested by user:
62077 var target = options[forward || 'target'];
62078 var targetPath = target && options.prependPath !== false
62079 ? (target.path || '')
62080 : '';
62081
62082 //
62083 // Remark: Can we somehow not use url.parse as a perf optimization?
62084 //
62085 var outgoingPath = !options.toProxy
62086 ? (url.parse(req.url).path || '')
62087 : req.url;
62088
62089 //
62090 // Remark: ignorePath will just straight up ignore whatever the request's
62091 // path is. This can be labeled as FOOT-GUN material if you do not know what
62092 // you are doing and are using conflicting options.
62093 //
62094 outgoingPath = !options.ignorePath ? outgoingPath : '';
62095
62096 outgoing.path = common.urlJoin(targetPath, outgoingPath);
62097
62098 if (options.changeOrigin) {
62099 outgoing.headers.host =
62100 required(outgoing.port, options[forward || 'target'].protocol) && !hasPort(outgoing.host)
62101 ? outgoing.host + ':' + outgoing.port
62102 : outgoing.host;
62103 }
62104 return outgoing;
62105};
62106
62107/**
62108 * Set the proper configuration for sockets,
62109 * set no delay and set keep alive, also set
62110 * the timeout to 0.
62111 *
62112 * Examples:
62113 *
62114 * common.setupSocket(socket)
62115 * // => Socket
62116 *
62117 * @param {Socket} Socket instance to setup
62118
62119 * @return {Socket} Return the configured socket.
62120 *
62121 * @api private
62122 */
62123
62124common.setupSocket = function(socket) {
62125 socket.setTimeout(0);
62126 socket.setNoDelay(true);
62127
62128 socket.setKeepAlive(true, 0);
62129
62130 return socket;
62131};
62132
62133/**
62134 * Get the port number from the host. Or guess it based on the connection type.
62135 *
62136 * @param {Request} req Incoming HTTP request.
62137 *
62138 * @return {String} The port number.
62139 *
62140 * @api private
62141 */
62142common.getPort = function(req) {
62143 var res = req.headers.host ? req.headers.host.match(/:(\d+)/) : '';
62144
62145 return res ?
62146 res[1] :
62147 common.hasEncryptedConnection(req) ? '443' : '80';
62148};
62149
62150/**
62151 * Check if the request has an encrypted connection.
62152 *
62153 * @param {Request} req Incoming HTTP request.
62154 *
62155 * @return {Boolean} Whether the connection is encrypted or not.
62156 *
62157 * @api private
62158 */
62159common.hasEncryptedConnection = function(req) {
62160 return Boolean(req.connection.encrypted || req.connection.pair);
62161};
62162
62163/**
62164 * OS-agnostic join (doesn't break on URLs like path.join does on Windows)>
62165 *
62166 * @return {String} The generated path.
62167 *
62168 * @api private
62169 */
62170
62171common.urlJoin = function() {
62172 //
62173 // We do not want to mess with the query string. All we want to touch is the path.
62174 //
62175 var args = Array.prototype.slice.call(arguments),
62176 lastIndex = args.length - 1,
62177 last = args[lastIndex],
62178 lastSegs = last.split('?'),
62179 retSegs;
62180
62181 args[lastIndex] = lastSegs.shift();
62182
62183 //
62184 // Join all strings, but remove empty strings so we don't get extra slashes from
62185 // joining e.g. ['', 'am']
62186 //
62187 retSegs = [
62188 args.filter(Boolean).join('/')
62189 .replace(/\/+/g, '/')
62190 .replace('http:/', 'http://')
62191 .replace('https:/', 'https://')
62192 ];
62193
62194 // Only join the query string if it exists so we don't have trailing a '?'
62195 // on every request
62196
62197 // Handle case where there could be multiple ? in the URL.
62198 retSegs.push.apply(retSegs, lastSegs);
62199
62200 return retSegs.join('?')
62201};
62202
62203/**
62204 * Rewrites or removes the domain of a cookie header
62205 *
62206 * @param {String|Array} Header
62207 * @param {Object} Config, mapping of domain to rewritten domain.
62208 * '*' key to match any domain, null value to remove the domain.
62209 *
62210 * @api private
62211 */
62212common.rewriteCookieProperty = function rewriteCookieProperty(header, config, property) {
62213 if (Array.isArray(header)) {
62214 return header.map(function (headerElement) {
62215 return rewriteCookieProperty(headerElement, config, property);
62216 });
62217 }
62218 return header.replace(new RegExp("(;\\s*" + property + "=)([^;]+)", 'i'), function(match, prefix, previousValue) {
62219 var newValue;
62220 if (previousValue in config) {
62221 newValue = config[previousValue];
62222 } else if ('*' in config) {
62223 newValue = config['*'];
62224 } else {
62225 //no match, return previous value
62226 return match;
62227 }
62228 if (newValue) {
62229 //replace value
62230 return prefix + newValue;
62231 } else {
62232 //remove value
62233 return '';
62234 }
62235 });
62236};
62237
62238/**
62239 * Check the host and see if it potentially has a port in it (keep it simple)
62240 *
62241 * @returns {Boolean} Whether we have one or not
62242 *
62243 * @api private
62244 */
62245function hasPort(host) {
62246 return !!~host.indexOf(':');
62247}}(common$4));
62248
62249var url$2 = require$$0__default$7,
62250 common$3 = common$4;
62251
62252
62253var redirectRegex = /^201|30(1|2|7|8)$/;
62254
62255/*!
62256 * Array of passes.
62257 *
62258 * A `pass` is just a function that is executed on `req, res, options`
62259 * so that you can easily add new checks while still keeping the base
62260 * flexible.
62261 */
62262
62263var webOutgoing = { // <--
62264
62265 /**
62266 * If is a HTTP 1.0 request, remove chunk headers
62267 *
62268 * @param {ClientRequest} Req Request object
62269 * @param {IncomingMessage} Res Response object
62270 * @param {proxyResponse} Res Response object from the proxy request
62271 *
62272 * @api private
62273 */
62274 removeChunked: function removeChunked(req, res, proxyRes) {
62275 if (req.httpVersion === '1.0') {
62276 delete proxyRes.headers['transfer-encoding'];
62277 }
62278 },
62279
62280 /**
62281 * If is a HTTP 1.0 request, set the correct connection header
62282 * or if connection header not present, then use `keep-alive`
62283 *
62284 * @param {ClientRequest} Req Request object
62285 * @param {IncomingMessage} Res Response object
62286 * @param {proxyResponse} Res Response object from the proxy request
62287 *
62288 * @api private
62289 */
62290 setConnection: function setConnection(req, res, proxyRes) {
62291 if (req.httpVersion === '1.0') {
62292 proxyRes.headers.connection = req.headers.connection || 'close';
62293 } else if (req.httpVersion !== '2.0' && !proxyRes.headers.connection) {
62294 proxyRes.headers.connection = req.headers.connection || 'keep-alive';
62295 }
62296 },
62297
62298 setRedirectHostRewrite: function setRedirectHostRewrite(req, res, proxyRes, options) {
62299 if ((options.hostRewrite || options.autoRewrite || options.protocolRewrite)
62300 && proxyRes.headers['location']
62301 && redirectRegex.test(proxyRes.statusCode)) {
62302 var target = url$2.parse(options.target);
62303 var u = url$2.parse(proxyRes.headers['location']);
62304
62305 // make sure the redirected host matches the target host before rewriting
62306 if (target.host != u.host) {
62307 return;
62308 }
62309
62310 if (options.hostRewrite) {
62311 u.host = options.hostRewrite;
62312 } else if (options.autoRewrite) {
62313 u.host = req.headers['host'];
62314 }
62315 if (options.protocolRewrite) {
62316 u.protocol = options.protocolRewrite;
62317 }
62318
62319 proxyRes.headers['location'] = u.format();
62320 }
62321 },
62322 /**
62323 * Copy headers from proxyResponse to response
62324 * set each header in response object.
62325 *
62326 * @param {ClientRequest} Req Request object
62327 * @param {IncomingMessage} Res Response object
62328 * @param {proxyResponse} Res Response object from the proxy request
62329 * @param {Object} Options options.cookieDomainRewrite: Config to rewrite cookie domain
62330 *
62331 * @api private
62332 */
62333 writeHeaders: function writeHeaders(req, res, proxyRes, options) {
62334 var rewriteCookieDomainConfig = options.cookieDomainRewrite,
62335 rewriteCookiePathConfig = options.cookiePathRewrite,
62336 preserveHeaderKeyCase = options.preserveHeaderKeyCase,
62337 rawHeaderKeyMap,
62338 setHeader = function(key, header) {
62339 if (header == undefined) return;
62340 if (rewriteCookieDomainConfig && key.toLowerCase() === 'set-cookie') {
62341 header = common$3.rewriteCookieProperty(header, rewriteCookieDomainConfig, 'domain');
62342 }
62343 if (rewriteCookiePathConfig && key.toLowerCase() === 'set-cookie') {
62344 header = common$3.rewriteCookieProperty(header, rewriteCookiePathConfig, 'path');
62345 }
62346 res.setHeader(String(key).trim(), header);
62347 };
62348
62349 if (typeof rewriteCookieDomainConfig === 'string') { //also test for ''
62350 rewriteCookieDomainConfig = { '*': rewriteCookieDomainConfig };
62351 }
62352
62353 if (typeof rewriteCookiePathConfig === 'string') { //also test for ''
62354 rewriteCookiePathConfig = { '*': rewriteCookiePathConfig };
62355 }
62356
62357 // message.rawHeaders is added in: v0.11.6
62358 // https://nodejs.org/api/http.html#http_message_rawheaders
62359 if (preserveHeaderKeyCase && proxyRes.rawHeaders != undefined) {
62360 rawHeaderKeyMap = {};
62361 for (var i = 0; i < proxyRes.rawHeaders.length; i += 2) {
62362 var key = proxyRes.rawHeaders[i];
62363 rawHeaderKeyMap[key.toLowerCase()] = key;
62364 }
62365 }
62366
62367 Object.keys(proxyRes.headers).forEach(function(key) {
62368 var header = proxyRes.headers[key];
62369 if (preserveHeaderKeyCase && rawHeaderKeyMap) {
62370 key = rawHeaderKeyMap[key] || key;
62371 }
62372 setHeader(key, header);
62373 });
62374 },
62375
62376 /**
62377 * Set the statusCode from the proxyResponse
62378 *
62379 * @param {ClientRequest} Req Request object
62380 * @param {IncomingMessage} Res Response object
62381 * @param {proxyResponse} Res Response object from the proxy request
62382 *
62383 * @api private
62384 */
62385 writeStatusCode: function writeStatusCode(req, res, proxyRes) {
62386 // From Node.js docs: response.writeHead(statusCode[, statusMessage][, headers])
62387 if(proxyRes.statusMessage) {
62388 res.statusCode = proxyRes.statusCode;
62389 res.statusMessage = proxyRes.statusMessage;
62390 } else {
62391 res.statusCode = proxyRes.statusCode;
62392 }
62393 }
62394
62395};
62396
62397var followRedirects$1 = {exports: {}};
62398
62399var src = {exports: {}};
62400
62401var browser = {exports: {}};
62402
62403/**
62404 * Helpers.
62405 */
62406
62407var s = 1000;
62408var m = s * 60;
62409var h = m * 60;
62410var d = h * 24;
62411var w = d * 7;
62412var y = d * 365.25;
62413
62414/**
62415 * Parse or format the given `val`.
62416 *
62417 * Options:
62418 *
62419 * - `long` verbose formatting [false]
62420 *
62421 * @param {String|Number} val
62422 * @param {Object} [options]
62423 * @throws {Error} throw an error if val is not a non-empty string or a number
62424 * @return {String|Number}
62425 * @api public
62426 */
62427
62428var ms = function(val, options) {
62429 options = options || {};
62430 var type = typeof val;
62431 if (type === 'string' && val.length > 0) {
62432 return parse$5(val);
62433 } else if (type === 'number' && isFinite(val)) {
62434 return options.long ? fmtLong(val) : fmtShort(val);
62435 }
62436 throw new Error(
62437 'val is not a non-empty string or a valid number. val=' +
62438 JSON.stringify(val)
62439 );
62440};
62441
62442/**
62443 * Parse the given `str` and return milliseconds.
62444 *
62445 * @param {String} str
62446 * @return {Number}
62447 * @api private
62448 */
62449
62450function parse$5(str) {
62451 str = String(str);
62452 if (str.length > 100) {
62453 return;
62454 }
62455 var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
62456 str
62457 );
62458 if (!match) {
62459 return;
62460 }
62461 var n = parseFloat(match[1]);
62462 var type = (match[2] || 'ms').toLowerCase();
62463 switch (type) {
62464 case 'years':
62465 case 'year':
62466 case 'yrs':
62467 case 'yr':
62468 case 'y':
62469 return n * y;
62470 case 'weeks':
62471 case 'week':
62472 case 'w':
62473 return n * w;
62474 case 'days':
62475 case 'day':
62476 case 'd':
62477 return n * d;
62478 case 'hours':
62479 case 'hour':
62480 case 'hrs':
62481 case 'hr':
62482 case 'h':
62483 return n * h;
62484 case 'minutes':
62485 case 'minute':
62486 case 'mins':
62487 case 'min':
62488 case 'm':
62489 return n * m;
62490 case 'seconds':
62491 case 'second':
62492 case 'secs':
62493 case 'sec':
62494 case 's':
62495 return n * s;
62496 case 'milliseconds':
62497 case 'millisecond':
62498 case 'msecs':
62499 case 'msec':
62500 case 'ms':
62501 return n;
62502 default:
62503 return undefined;
62504 }
62505}
62506
62507/**
62508 * Short format for `ms`.
62509 *
62510 * @param {Number} ms
62511 * @return {String}
62512 * @api private
62513 */
62514
62515function fmtShort(ms) {
62516 var msAbs = Math.abs(ms);
62517 if (msAbs >= d) {
62518 return Math.round(ms / d) + 'd';
62519 }
62520 if (msAbs >= h) {
62521 return Math.round(ms / h) + 'h';
62522 }
62523 if (msAbs >= m) {
62524 return Math.round(ms / m) + 'm';
62525 }
62526 if (msAbs >= s) {
62527 return Math.round(ms / s) + 's';
62528 }
62529 return ms + 'ms';
62530}
62531
62532/**
62533 * Long format for `ms`.
62534 *
62535 * @param {Number} ms
62536 * @return {String}
62537 * @api private
62538 */
62539
62540function fmtLong(ms) {
62541 var msAbs = Math.abs(ms);
62542 if (msAbs >= d) {
62543 return plural(ms, msAbs, d, 'day');
62544 }
62545 if (msAbs >= h) {
62546 return plural(ms, msAbs, h, 'hour');
62547 }
62548 if (msAbs >= m) {
62549 return plural(ms, msAbs, m, 'minute');
62550 }
62551 if (msAbs >= s) {
62552 return plural(ms, msAbs, s, 'second');
62553 }
62554 return ms + ' ms';
62555}
62556
62557/**
62558 * Pluralization helper.
62559 */
62560
62561function plural(ms, msAbs, n, name) {
62562 var isPlural = msAbs >= n * 1.5;
62563 return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
62564}
62565
62566/**
62567 * This is the common logic for both the Node.js and web browser
62568 * implementations of `debug()`.
62569 */
62570
62571function setup(env) {
62572 createDebug.debug = createDebug;
62573 createDebug.default = createDebug;
62574 createDebug.coerce = coerce;
62575 createDebug.disable = disable;
62576 createDebug.enable = enable;
62577 createDebug.enabled = enabled;
62578 createDebug.humanize = ms;
62579 createDebug.destroy = destroy;
62580
62581 Object.keys(env).forEach(key => {
62582 createDebug[key] = env[key];
62583 });
62584
62585 /**
62586 * The currently active debug mode names, and names to skip.
62587 */
62588
62589 createDebug.names = [];
62590 createDebug.skips = [];
62591
62592 /**
62593 * Map of special "%n" handling functions, for the debug "format" argument.
62594 *
62595 * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
62596 */
62597 createDebug.formatters = {};
62598
62599 /**
62600 * Selects a color for a debug namespace
62601 * @param {String} namespace The namespace string for the for the debug instance to be colored
62602 * @return {Number|String} An ANSI color code for the given namespace
62603 * @api private
62604 */
62605 function selectColor(namespace) {
62606 let hash = 0;
62607
62608 for (let i = 0; i < namespace.length; i++) {
62609 hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
62610 hash |= 0; // Convert to 32bit integer
62611 }
62612
62613 return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
62614 }
62615 createDebug.selectColor = selectColor;
62616
62617 /**
62618 * Create a debugger with the given `namespace`.
62619 *
62620 * @param {String} namespace
62621 * @return {Function}
62622 * @api public
62623 */
62624 function createDebug(namespace) {
62625 let prevTime;
62626 let enableOverride = null;
62627
62628 function debug(...args) {
62629 // Disabled?
62630 if (!debug.enabled) {
62631 return;
62632 }
62633
62634 const self = debug;
62635
62636 // Set `diff` timestamp
62637 const curr = Number(new Date());
62638 const ms = curr - (prevTime || curr);
62639 self.diff = ms;
62640 self.prev = prevTime;
62641 self.curr = curr;
62642 prevTime = curr;
62643
62644 args[0] = createDebug.coerce(args[0]);
62645
62646 if (typeof args[0] !== 'string') {
62647 // Anything else let's inspect with %O
62648 args.unshift('%O');
62649 }
62650
62651 // Apply any `formatters` transformations
62652 let index = 0;
62653 args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
62654 // If we encounter an escaped % then don't increase the array index
62655 if (match === '%%') {
62656 return '%';
62657 }
62658 index++;
62659 const formatter = createDebug.formatters[format];
62660 if (typeof formatter === 'function') {
62661 const val = args[index];
62662 match = formatter.call(self, val);
62663
62664 // Now we need to remove `args[index]` since it's inlined in the `format`
62665 args.splice(index, 1);
62666 index--;
62667 }
62668 return match;
62669 });
62670
62671 // Apply env-specific formatting (colors, etc.)
62672 createDebug.formatArgs.call(self, args);
62673
62674 const logFn = self.log || createDebug.log;
62675 logFn.apply(self, args);
62676 }
62677
62678 debug.namespace = namespace;
62679 debug.useColors = createDebug.useColors();
62680 debug.color = createDebug.selectColor(namespace);
62681 debug.extend = extend;
62682 debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
62683
62684 Object.defineProperty(debug, 'enabled', {
62685 enumerable: true,
62686 configurable: false,
62687 get: () => enableOverride === null ? createDebug.enabled(namespace) : enableOverride,
62688 set: v => {
62689 enableOverride = v;
62690 }
62691 });
62692
62693 // Env-specific initialization logic for debug instances
62694 if (typeof createDebug.init === 'function') {
62695 createDebug.init(debug);
62696 }
62697
62698 return debug;
62699 }
62700
62701 function extend(namespace, delimiter) {
62702 const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
62703 newDebug.log = this.log;
62704 return newDebug;
62705 }
62706
62707 /**
62708 * Enables a debug mode by namespaces. This can include modes
62709 * separated by a colon and wildcards.
62710 *
62711 * @param {String} namespaces
62712 * @api public
62713 */
62714 function enable(namespaces) {
62715 createDebug.save(namespaces);
62716
62717 createDebug.names = [];
62718 createDebug.skips = [];
62719
62720 let i;
62721 const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
62722 const len = split.length;
62723
62724 for (i = 0; i < len; i++) {
62725 if (!split[i]) {
62726 // ignore empty strings
62727 continue;
62728 }
62729
62730 namespaces = split[i].replace(/\*/g, '.*?');
62731
62732 if (namespaces[0] === '-') {
62733 createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
62734 } else {
62735 createDebug.names.push(new RegExp('^' + namespaces + '$'));
62736 }
62737 }
62738 }
62739
62740 /**
62741 * Disable debug output.
62742 *
62743 * @return {String} namespaces
62744 * @api public
62745 */
62746 function disable() {
62747 const namespaces = [
62748 ...createDebug.names.map(toNamespace),
62749 ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
62750 ].join(',');
62751 createDebug.enable('');
62752 return namespaces;
62753 }
62754
62755 /**
62756 * Returns true if the given mode name is enabled, false otherwise.
62757 *
62758 * @param {String} name
62759 * @return {Boolean}
62760 * @api public
62761 */
62762 function enabled(name) {
62763 if (name[name.length - 1] === '*') {
62764 return true;
62765 }
62766
62767 let i;
62768 let len;
62769
62770 for (i = 0, len = createDebug.skips.length; i < len; i++) {
62771 if (createDebug.skips[i].test(name)) {
62772 return false;
62773 }
62774 }
62775
62776 for (i = 0, len = createDebug.names.length; i < len; i++) {
62777 if (createDebug.names[i].test(name)) {
62778 return true;
62779 }
62780 }
62781
62782 return false;
62783 }
62784
62785 /**
62786 * Convert regexp to namespace
62787 *
62788 * @param {RegExp} regxep
62789 * @return {String} namespace
62790 * @api private
62791 */
62792 function toNamespace(regexp) {
62793 return regexp.toString()
62794 .substring(2, regexp.toString().length - 2)
62795 .replace(/\.\*\?$/, '*');
62796 }
62797
62798 /**
62799 * Coerce `val`.
62800 *
62801 * @param {Mixed} val
62802 * @return {Mixed}
62803 * @api private
62804 */
62805 function coerce(val) {
62806 if (val instanceof Error) {
62807 return val.stack || val.message;
62808 }
62809 return val;
62810 }
62811
62812 /**
62813 * XXX DO NOT USE. This is a temporary stub function.
62814 * XXX It WILL be removed in the next major release.
62815 */
62816 function destroy() {
62817 console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
62818 }
62819
62820 createDebug.enable(createDebug.load());
62821
62822 return createDebug;
62823}
62824
62825var common$2 = setup;
62826
62827/* eslint-env browser */
62828
62829(function (module, exports) {
62830/**
62831 * This is the web browser implementation of `debug()`.
62832 */
62833
62834exports.formatArgs = formatArgs;
62835exports.save = save;
62836exports.load = load;
62837exports.useColors = useColors;
62838exports.storage = localstorage();
62839exports.destroy = (() => {
62840 let warned = false;
62841
62842 return () => {
62843 if (!warned) {
62844 warned = true;
62845 console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
62846 }
62847 };
62848})();
62849
62850/**
62851 * Colors.
62852 */
62853
62854exports.colors = [
62855 '#0000CC',
62856 '#0000FF',
62857 '#0033CC',
62858 '#0033FF',
62859 '#0066CC',
62860 '#0066FF',
62861 '#0099CC',
62862 '#0099FF',
62863 '#00CC00',
62864 '#00CC33',
62865 '#00CC66',
62866 '#00CC99',
62867 '#00CCCC',
62868 '#00CCFF',
62869 '#3300CC',
62870 '#3300FF',
62871 '#3333CC',
62872 '#3333FF',
62873 '#3366CC',
62874 '#3366FF',
62875 '#3399CC',
62876 '#3399FF',
62877 '#33CC00',
62878 '#33CC33',
62879 '#33CC66',
62880 '#33CC99',
62881 '#33CCCC',
62882 '#33CCFF',
62883 '#6600CC',
62884 '#6600FF',
62885 '#6633CC',
62886 '#6633FF',
62887 '#66CC00',
62888 '#66CC33',
62889 '#9900CC',
62890 '#9900FF',
62891 '#9933CC',
62892 '#9933FF',
62893 '#99CC00',
62894 '#99CC33',
62895 '#CC0000',
62896 '#CC0033',
62897 '#CC0066',
62898 '#CC0099',
62899 '#CC00CC',
62900 '#CC00FF',
62901 '#CC3300',
62902 '#CC3333',
62903 '#CC3366',
62904 '#CC3399',
62905 '#CC33CC',
62906 '#CC33FF',
62907 '#CC6600',
62908 '#CC6633',
62909 '#CC9900',
62910 '#CC9933',
62911 '#CCCC00',
62912 '#CCCC33',
62913 '#FF0000',
62914 '#FF0033',
62915 '#FF0066',
62916 '#FF0099',
62917 '#FF00CC',
62918 '#FF00FF',
62919 '#FF3300',
62920 '#FF3333',
62921 '#FF3366',
62922 '#FF3399',
62923 '#FF33CC',
62924 '#FF33FF',
62925 '#FF6600',
62926 '#FF6633',
62927 '#FF9900',
62928 '#FF9933',
62929 '#FFCC00',
62930 '#FFCC33'
62931];
62932
62933/**
62934 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
62935 * and the Firebug extension (any Firefox version) are known
62936 * to support "%c" CSS customizations.
62937 *
62938 * TODO: add a `localStorage` variable to explicitly enable/disable colors
62939 */
62940
62941// eslint-disable-next-line complexity
62942function useColors() {
62943 // NB: In an Electron preload script, document will be defined but not fully
62944 // initialized. Since we know we're in Chrome, we'll just detect this case
62945 // explicitly
62946 if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
62947 return true;
62948 }
62949
62950 // Internet Explorer and Edge do not support colors.
62951 if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
62952 return false;
62953 }
62954
62955 // Is webkit? http://stackoverflow.com/a/16459606/376773
62956 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
62957 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
62958 // Is firebug? http://stackoverflow.com/a/398120/376773
62959 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
62960 // Is firefox >= v31?
62961 // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
62962 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
62963 // Double check webkit in userAgent just in case we are in a worker
62964 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
62965}
62966
62967/**
62968 * Colorize log arguments if enabled.
62969 *
62970 * @api public
62971 */
62972
62973function formatArgs(args) {
62974 args[0] = (this.useColors ? '%c' : '') +
62975 this.namespace +
62976 (this.useColors ? ' %c' : ' ') +
62977 args[0] +
62978 (this.useColors ? '%c ' : ' ') +
62979 '+' + module.exports.humanize(this.diff);
62980
62981 if (!this.useColors) {
62982 return;
62983 }
62984
62985 const c = 'color: ' + this.color;
62986 args.splice(1, 0, c, 'color: inherit');
62987
62988 // The final "%c" is somewhat tricky, because there could be other
62989 // arguments passed either before or after the %c, so we need to
62990 // figure out the correct index to insert the CSS into
62991 let index = 0;
62992 let lastC = 0;
62993 args[0].replace(/%[a-zA-Z%]/g, match => {
62994 if (match === '%%') {
62995 return;
62996 }
62997 index++;
62998 if (match === '%c') {
62999 // We only are interested in the *last* %c
63000 // (the user may have provided their own)
63001 lastC = index;
63002 }
63003 });
63004
63005 args.splice(lastC, 0, c);
63006}
63007
63008/**
63009 * Invokes `console.debug()` when available.
63010 * No-op when `console.debug` is not a "function".
63011 * If `console.debug` is not available, falls back
63012 * to `console.log`.
63013 *
63014 * @api public
63015 */
63016exports.log = console.debug || console.log || (() => {});
63017
63018/**
63019 * Save `namespaces`.
63020 *
63021 * @param {String} namespaces
63022 * @api private
63023 */
63024function save(namespaces) {
63025 try {
63026 if (namespaces) {
63027 exports.storage.setItem('debug', namespaces);
63028 } else {
63029 exports.storage.removeItem('debug');
63030 }
63031 } catch (error) {
63032 // Swallow
63033 // XXX (@Qix-) should we be logging these?
63034 }
63035}
63036
63037/**
63038 * Load `namespaces`.
63039 *
63040 * @return {String} returns the previously persisted debug modes
63041 * @api private
63042 */
63043function load() {
63044 let r;
63045 try {
63046 r = exports.storage.getItem('debug');
63047 } catch (error) {
63048 // Swallow
63049 // XXX (@Qix-) should we be logging these?
63050 }
63051
63052 // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
63053 if (!r && typeof process !== 'undefined' && 'env' in process) {
63054 r = process.env.DEBUG;
63055 }
63056
63057 return r;
63058}
63059
63060/**
63061 * Localstorage attempts to return the localstorage.
63062 *
63063 * This is necessary because safari throws
63064 * when a user disables cookies/localstorage
63065 * and you attempt to access it.
63066 *
63067 * @return {LocalStorage}
63068 * @api private
63069 */
63070
63071function localstorage() {
63072 try {
63073 // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
63074 // The Browser also has localStorage in the global context.
63075 return localStorage;
63076 } catch (error) {
63077 // Swallow
63078 // XXX (@Qix-) should we be logging these?
63079 }
63080}
63081
63082module.exports = common$2(exports);
63083
63084const {formatters} = module.exports;
63085
63086/**
63087 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
63088 */
63089
63090formatters.j = function (v) {
63091 try {
63092 return JSON.stringify(v);
63093 } catch (error) {
63094 return '[UnexpectedJSONParseError]: ' + error.message;
63095 }
63096};
63097}(browser, browser.exports));
63098
63099var node = {exports: {}};
63100
63101/**
63102 * Module dependencies.
63103 */
63104
63105(function (module, exports) {
63106const tty = require$$0__default;
63107const util = require$$0__default$3;
63108
63109/**
63110 * This is the Node.js implementation of `debug()`.
63111 */
63112
63113exports.init = init;
63114exports.log = log;
63115exports.formatArgs = formatArgs;
63116exports.save = save;
63117exports.load = load;
63118exports.useColors = useColors;
63119exports.destroy = util.deprecate(
63120 () => {},
63121 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'
63122);
63123
63124/**
63125 * Colors.
63126 */
63127
63128exports.colors = [6, 2, 3, 4, 5, 1];
63129
63130try {
63131 // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
63132 // eslint-disable-next-line import/no-extraneous-dependencies
63133 const supportsColor = supportsColor_1$1;
63134
63135 if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
63136 exports.colors = [
63137 20,
63138 21,
63139 26,
63140 27,
63141 32,
63142 33,
63143 38,
63144 39,
63145 40,
63146 41,
63147 42,
63148 43,
63149 44,
63150 45,
63151 56,
63152 57,
63153 62,
63154 63,
63155 68,
63156 69,
63157 74,
63158 75,
63159 76,
63160 77,
63161 78,
63162 79,
63163 80,
63164 81,
63165 92,
63166 93,
63167 98,
63168 99,
63169 112,
63170 113,
63171 128,
63172 129,
63173 134,
63174 135,
63175 148,
63176 149,
63177 160,
63178 161,
63179 162,
63180 163,
63181 164,
63182 165,
63183 166,
63184 167,
63185 168,
63186 169,
63187 170,
63188 171,
63189 172,
63190 173,
63191 178,
63192 179,
63193 184,
63194 185,
63195 196,
63196 197,
63197 198,
63198 199,
63199 200,
63200 201,
63201 202,
63202 203,
63203 204,
63204 205,
63205 206,
63206 207,
63207 208,
63208 209,
63209 214,
63210 215,
63211 220,
63212 221
63213 ];
63214 }
63215} catch (error) {
63216 // Swallow - we only care if `supports-color` is available; it doesn't have to be.
63217}
63218
63219/**
63220 * Build up the default `inspectOpts` object from the environment variables.
63221 *
63222 * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
63223 */
63224
63225exports.inspectOpts = Object.keys(process.env).filter(key => {
63226 return /^debug_/i.test(key);
63227}).reduce((obj, key) => {
63228 // Camel-case
63229 const prop = key
63230 .substring(6)
63231 .toLowerCase()
63232 .replace(/_([a-z])/g, (_, k) => {
63233 return k.toUpperCase();
63234 });
63235
63236 // Coerce string value into JS value
63237 let val = process.env[key];
63238 if (/^(yes|on|true|enabled)$/i.test(val)) {
63239 val = true;
63240 } else if (/^(no|off|false|disabled)$/i.test(val)) {
63241 val = false;
63242 } else if (val === 'null') {
63243 val = null;
63244 } else {
63245 val = Number(val);
63246 }
63247
63248 obj[prop] = val;
63249 return obj;
63250}, {});
63251
63252/**
63253 * Is stdout a TTY? Colored output is enabled when `true`.
63254 */
63255
63256function useColors() {
63257 return 'colors' in exports.inspectOpts ?
63258 Boolean(exports.inspectOpts.colors) :
63259 tty.isatty(process.stderr.fd);
63260}
63261
63262/**
63263 * Adds ANSI color escape codes if enabled.
63264 *
63265 * @api public
63266 */
63267
63268function formatArgs(args) {
63269 const {namespace: name, useColors} = this;
63270
63271 if (useColors) {
63272 const c = this.color;
63273 const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
63274 const prefix = ` ${colorCode};1m${name} \u001B[0m`;
63275
63276 args[0] = prefix + args[0].split('\n').join('\n' + prefix);
63277 args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
63278 } else {
63279 args[0] = getDate() + name + ' ' + args[0];
63280 }
63281}
63282
63283function getDate() {
63284 if (exports.inspectOpts.hideDate) {
63285 return '';
63286 }
63287 return new Date().toISOString() + ' ';
63288}
63289
63290/**
63291 * Invokes `util.format()` with the specified arguments and writes to stderr.
63292 */
63293
63294function log(...args) {
63295 return process.stderr.write(util.format(...args) + '\n');
63296}
63297
63298/**
63299 * Save `namespaces`.
63300 *
63301 * @param {String} namespaces
63302 * @api private
63303 */
63304function save(namespaces) {
63305 if (namespaces) {
63306 process.env.DEBUG = namespaces;
63307 } else {
63308 // If you set a process.env field to null or undefined, it gets cast to the
63309 // string 'null' or 'undefined'. Just delete instead.
63310 delete process.env.DEBUG;
63311 }
63312}
63313
63314/**
63315 * Load `namespaces`.
63316 *
63317 * @return {String} returns the previously persisted debug modes
63318 * @api private
63319 */
63320
63321function load() {
63322 return process.env.DEBUG;
63323}
63324
63325/**
63326 * Init logic for `debug` instances.
63327 *
63328 * Create a new `inspectOpts` object in case `useColors` is set
63329 * differently for a particular `debug` instance.
63330 */
63331
63332function init(debug) {
63333 debug.inspectOpts = {};
63334
63335 const keys = Object.keys(exports.inspectOpts);
63336 for (let i = 0; i < keys.length; i++) {
63337 debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
63338 }
63339}
63340
63341module.exports = common$2(exports);
63342
63343const {formatters} = module.exports;
63344
63345/**
63346 * Map %o to `util.inspect()`, all on a single line.
63347 */
63348
63349formatters.o = function (v) {
63350 this.inspectOpts.colors = this.useColors;
63351 return util.inspect(v, this.inspectOpts)
63352 .split('\n')
63353 .map(str => str.trim())
63354 .join(' ');
63355};
63356
63357/**
63358 * Map %O to `util.inspect()`, allowing multiple lines if needed.
63359 */
63360
63361formatters.O = function (v) {
63362 this.inspectOpts.colors = this.useColors;
63363 return util.inspect(v, this.inspectOpts);
63364};
63365}(node, node.exports));
63366
63367/**
63368 * Detect Electron renderer / nwjs process, which is node, but we should
63369 * treat as a browser.
63370 */
63371
63372if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
63373 src.exports = browser.exports;
63374} else {
63375 src.exports = node.exports;
63376}
63377
63378var debug$4;
63379
63380var debug_1 = function () {
63381 if (!debug$4) {
63382 try {
63383 /* eslint global-require: off */
63384 debug$4 = src.exports("follow-redirects");
63385 }
63386 catch (error) {
63387 debug$4 = function () { /* */ };
63388 }
63389 }
63390 debug$4.apply(null, arguments);
63391};
63392
63393var url$1 = require$$0__default$7;
63394var URL$1 = url$1.URL;
63395var http$1 = require$$0__default$8;
63396var https$1 = require$$1__default$2;
63397var Writable = require$$0__default$2.Writable;
63398var assert$1 = require$$6__default;
63399var debug$3 = debug_1;
63400
63401// Create handlers that pass events from native requests
63402var events = ["abort", "aborted", "connect", "error", "socket", "timeout"];
63403var eventHandlers = Object.create(null);
63404events.forEach(function (event) {
63405 eventHandlers[event] = function (arg1, arg2, arg3) {
63406 this._redirectable.emit(event, arg1, arg2, arg3);
63407 };
63408});
63409
63410// Error types with codes
63411var RedirectionError = createErrorType(
63412 "ERR_FR_REDIRECTION_FAILURE",
63413 ""
63414);
63415var TooManyRedirectsError = createErrorType(
63416 "ERR_FR_TOO_MANY_REDIRECTS",
63417 "Maximum number of redirects exceeded"
63418);
63419var MaxBodyLengthExceededError = createErrorType(
63420 "ERR_FR_MAX_BODY_LENGTH_EXCEEDED",
63421 "Request body larger than maxBodyLength limit"
63422);
63423var WriteAfterEndError = createErrorType(
63424 "ERR_STREAM_WRITE_AFTER_END",
63425 "write after end"
63426);
63427
63428// An HTTP(S) request that can be redirected
63429function RedirectableRequest(options, responseCallback) {
63430 // Initialize the request
63431 Writable.call(this);
63432 this._sanitizeOptions(options);
63433 this._options = options;
63434 this._ended = false;
63435 this._ending = false;
63436 this._redirectCount = 0;
63437 this._redirects = [];
63438 this._requestBodyLength = 0;
63439 this._requestBodyBuffers = [];
63440
63441 // Attach a callback if passed
63442 if (responseCallback) {
63443 this.on("response", responseCallback);
63444 }
63445
63446 // React to responses of native requests
63447 var self = this;
63448 this._onNativeResponse = function (response) {
63449 self._processResponse(response);
63450 };
63451
63452 // Perform the first request
63453 this._performRequest();
63454}
63455RedirectableRequest.prototype = Object.create(Writable.prototype);
63456
63457RedirectableRequest.prototype.abort = function () {
63458 abortRequest(this._currentRequest);
63459 this.emit("abort");
63460};
63461
63462// Writes buffered data to the current native request
63463RedirectableRequest.prototype.write = function (data, encoding, callback) {
63464 // Writing is not allowed if end has been called
63465 if (this._ending) {
63466 throw new WriteAfterEndError();
63467 }
63468
63469 // Validate input and shift parameters if necessary
63470 if (!(typeof data === "string" || typeof data === "object" && ("length" in data))) {
63471 throw new TypeError("data should be a string, Buffer or Uint8Array");
63472 }
63473 if (typeof encoding === "function") {
63474 callback = encoding;
63475 encoding = null;
63476 }
63477
63478 // Ignore empty buffers, since writing them doesn't invoke the callback
63479 // https://github.com/nodejs/node/issues/22066
63480 if (data.length === 0) {
63481 if (callback) {
63482 callback();
63483 }
63484 return;
63485 }
63486 // Only write when we don't exceed the maximum body length
63487 if (this._requestBodyLength + data.length <= this._options.maxBodyLength) {
63488 this._requestBodyLength += data.length;
63489 this._requestBodyBuffers.push({ data: data, encoding: encoding });
63490 this._currentRequest.write(data, encoding, callback);
63491 }
63492 // Error when we exceed the maximum body length
63493 else {
63494 this.emit("error", new MaxBodyLengthExceededError());
63495 this.abort();
63496 }
63497};
63498
63499// Ends the current native request
63500RedirectableRequest.prototype.end = function (data, encoding, callback) {
63501 // Shift parameters if necessary
63502 if (typeof data === "function") {
63503 callback = data;
63504 data = encoding = null;
63505 }
63506 else if (typeof encoding === "function") {
63507 callback = encoding;
63508 encoding = null;
63509 }
63510
63511 // Write data if needed and end
63512 if (!data) {
63513 this._ended = this._ending = true;
63514 this._currentRequest.end(null, null, callback);
63515 }
63516 else {
63517 var self = this;
63518 var currentRequest = this._currentRequest;
63519 this.write(data, encoding, function () {
63520 self._ended = true;
63521 currentRequest.end(null, null, callback);
63522 });
63523 this._ending = true;
63524 }
63525};
63526
63527// Sets a header value on the current native request
63528RedirectableRequest.prototype.setHeader = function (name, value) {
63529 this._options.headers[name] = value;
63530 this._currentRequest.setHeader(name, value);
63531};
63532
63533// Clears a header value on the current native request
63534RedirectableRequest.prototype.removeHeader = function (name) {
63535 delete this._options.headers[name];
63536 this._currentRequest.removeHeader(name);
63537};
63538
63539// Global timeout for all underlying requests
63540RedirectableRequest.prototype.setTimeout = function (msecs, callback) {
63541 var self = this;
63542 if (callback) {
63543 this.on("timeout", callback);
63544 }
63545
63546 function destroyOnTimeout(socket) {
63547 socket.setTimeout(msecs);
63548 socket.removeListener("timeout", socket.destroy);
63549 socket.addListener("timeout", socket.destroy);
63550 }
63551
63552 // Sets up a timer to trigger a timeout event
63553 function startTimer(socket) {
63554 if (self._timeout) {
63555 clearTimeout(self._timeout);
63556 }
63557 self._timeout = setTimeout(function () {
63558 self.emit("timeout");
63559 clearTimer();
63560 }, msecs);
63561 destroyOnTimeout(socket);
63562 }
63563
63564 // Prevent a timeout from triggering
63565 function clearTimer() {
63566 clearTimeout(this._timeout);
63567 if (callback) {
63568 self.removeListener("timeout", callback);
63569 }
63570 if (!this.socket) {
63571 self._currentRequest.removeListener("socket", startTimer);
63572 }
63573 }
63574
63575 // Start the timer when the socket is opened
63576 if (this.socket) {
63577 startTimer(this.socket);
63578 }
63579 else {
63580 this._currentRequest.once("socket", startTimer);
63581 }
63582
63583 this.on("socket", destroyOnTimeout);
63584 this.once("response", clearTimer);
63585 this.once("error", clearTimer);
63586
63587 return this;
63588};
63589
63590// Proxy all other public ClientRequest methods
63591[
63592 "flushHeaders", "getHeader",
63593 "setNoDelay", "setSocketKeepAlive",
63594].forEach(function (method) {
63595 RedirectableRequest.prototype[method] = function (a, b) {
63596 return this._currentRequest[method](a, b);
63597 };
63598});
63599
63600// Proxy all public ClientRequest properties
63601["aborted", "connection", "socket"].forEach(function (property) {
63602 Object.defineProperty(RedirectableRequest.prototype, property, {
63603 get: function () { return this._currentRequest[property]; },
63604 });
63605});
63606
63607RedirectableRequest.prototype._sanitizeOptions = function (options) {
63608 // Ensure headers are always present
63609 if (!options.headers) {
63610 options.headers = {};
63611 }
63612
63613 // Since http.request treats host as an alias of hostname,
63614 // but the url module interprets host as hostname plus port,
63615 // eliminate the host property to avoid confusion.
63616 if (options.host) {
63617 // Use hostname if set, because it has precedence
63618 if (!options.hostname) {
63619 options.hostname = options.host;
63620 }
63621 delete options.host;
63622 }
63623
63624 // Complete the URL object when necessary
63625 if (!options.pathname && options.path) {
63626 var searchPos = options.path.indexOf("?");
63627 if (searchPos < 0) {
63628 options.pathname = options.path;
63629 }
63630 else {
63631 options.pathname = options.path.substring(0, searchPos);
63632 options.search = options.path.substring(searchPos);
63633 }
63634 }
63635};
63636
63637
63638// Executes the next native request (initial or redirect)
63639RedirectableRequest.prototype._performRequest = function () {
63640 // Load the native protocol
63641 var protocol = this._options.protocol;
63642 var nativeProtocol = this._options.nativeProtocols[protocol];
63643 if (!nativeProtocol) {
63644 this.emit("error", new TypeError("Unsupported protocol " + protocol));
63645 return;
63646 }
63647
63648 // If specified, use the agent corresponding to the protocol
63649 // (HTTP and HTTPS use different types of agents)
63650 if (this._options.agents) {
63651 var scheme = protocol.substr(0, protocol.length - 1);
63652 this._options.agent = this._options.agents[scheme];
63653 }
63654
63655 // Create the native request
63656 var request = this._currentRequest =
63657 nativeProtocol.request(this._options, this._onNativeResponse);
63658 this._currentUrl = url$1.format(this._options);
63659
63660 // Set up event handlers
63661 request._redirectable = this;
63662 for (var e = 0; e < events.length; e++) {
63663 request.on(events[e], eventHandlers[events[e]]);
63664 }
63665
63666 // End a redirected request
63667 // (The first request must be ended explicitly with RedirectableRequest#end)
63668 if (this._isRedirect) {
63669 // Write the request entity and end.
63670 var i = 0;
63671 var self = this;
63672 var buffers = this._requestBodyBuffers;
63673 (function writeNext(error) {
63674 // Only write if this request has not been redirected yet
63675 /* istanbul ignore else */
63676 if (request === self._currentRequest) {
63677 // Report any write errors
63678 /* istanbul ignore if */
63679 if (error) {
63680 self.emit("error", error);
63681 }
63682 // Write the next buffer if there are still left
63683 else if (i < buffers.length) {
63684 var buffer = buffers[i++];
63685 /* istanbul ignore else */
63686 if (!request.finished) {
63687 request.write(buffer.data, buffer.encoding, writeNext);
63688 }
63689 }
63690 // End the request if `end` has been called on us
63691 else if (self._ended) {
63692 request.end();
63693 }
63694 }
63695 }());
63696 }
63697};
63698
63699// Processes a response from the current native request
63700RedirectableRequest.prototype._processResponse = function (response) {
63701 // Store the redirected response
63702 var statusCode = response.statusCode;
63703 if (this._options.trackRedirects) {
63704 this._redirects.push({
63705 url: this._currentUrl,
63706 headers: response.headers,
63707 statusCode: statusCode,
63708 });
63709 }
63710
63711 // RFC7231§6.4: The 3xx (Redirection) class of status code indicates
63712 // that further action needs to be taken by the user agent in order to
63713 // fulfill the request. If a Location header field is provided,
63714 // the user agent MAY automatically redirect its request to the URI
63715 // referenced by the Location field value,
63716 // even if the specific status code is not understood.
63717 var location = response.headers.location;
63718 if (location && this._options.followRedirects !== false &&
63719 statusCode >= 300 && statusCode < 400) {
63720 // Abort the current request
63721 abortRequest(this._currentRequest);
63722 // Discard the remainder of the response to avoid waiting for data
63723 response.destroy();
63724
63725 // RFC7231§6.4: A client SHOULD detect and intervene
63726 // in cyclical redirections (i.e., "infinite" redirection loops).
63727 if (++this._redirectCount > this._options.maxRedirects) {
63728 this.emit("error", new TooManyRedirectsError());
63729 return;
63730 }
63731
63732 // RFC7231§6.4: Automatic redirection needs to done with
63733 // care for methods not known to be safe, […]
63734 // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change
63735 // the request method from POST to GET for the subsequent request.
63736 if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" ||
63737 // RFC7231§6.4.4: The 303 (See Other) status code indicates that
63738 // the server is redirecting the user agent to a different resource […]
63739 // A user agent can perform a retrieval request targeting that URI
63740 // (a GET or HEAD request if using HTTP) […]
63741 (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) {
63742 this._options.method = "GET";
63743 // Drop a possible entity and headers related to it
63744 this._requestBodyBuffers = [];
63745 removeMatchingHeaders(/^content-/i, this._options.headers);
63746 }
63747
63748 // Drop the Host header, as the redirect might lead to a different host
63749 var previousHostName = removeMatchingHeaders(/^host$/i, this._options.headers) ||
63750 url$1.parse(this._currentUrl).hostname;
63751
63752 // Create the redirected request
63753 var redirectUrl = url$1.resolve(this._currentUrl, location);
63754 debug$3("redirecting to", redirectUrl);
63755 this._isRedirect = true;
63756 var redirectUrlParts = url$1.parse(redirectUrl);
63757 Object.assign(this._options, redirectUrlParts);
63758
63759 // Drop the Authorization header if redirecting to another host
63760 if (redirectUrlParts.hostname !== previousHostName) {
63761 removeMatchingHeaders(/^authorization$/i, this._options.headers);
63762 }
63763
63764 // Evaluate the beforeRedirect callback
63765 if (typeof this._options.beforeRedirect === "function") {
63766 var responseDetails = { headers: response.headers };
63767 try {
63768 this._options.beforeRedirect.call(null, this._options, responseDetails);
63769 }
63770 catch (err) {
63771 this.emit("error", err);
63772 return;
63773 }
63774 this._sanitizeOptions(this._options);
63775 }
63776
63777 // Perform the redirected request
63778 try {
63779 this._performRequest();
63780 }
63781 catch (cause) {
63782 var error = new RedirectionError("Redirected request failed: " + cause.message);
63783 error.cause = cause;
63784 this.emit("error", error);
63785 }
63786 }
63787 else {
63788 // The response is not a redirect; return it as-is
63789 response.responseUrl = this._currentUrl;
63790 response.redirects = this._redirects;
63791 this.emit("response", response);
63792
63793 // Clean up
63794 this._requestBodyBuffers = [];
63795 }
63796};
63797
63798// Wraps the key/value object of protocols with redirect functionality
63799function wrap(protocols) {
63800 // Default settings
63801 var exports = {
63802 maxRedirects: 21,
63803 maxBodyLength: 10 * 1024 * 1024,
63804 };
63805
63806 // Wrap each protocol
63807 var nativeProtocols = {};
63808 Object.keys(protocols).forEach(function (scheme) {
63809 var protocol = scheme + ":";
63810 var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];
63811 var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol);
63812
63813 // Executes a request, following redirects
63814 function request(input, options, callback) {
63815 // Parse parameters
63816 if (typeof input === "string") {
63817 var urlStr = input;
63818 try {
63819 input = urlToOptions(new URL$1(urlStr));
63820 }
63821 catch (err) {
63822 /* istanbul ignore next */
63823 input = url$1.parse(urlStr);
63824 }
63825 }
63826 else if (URL$1 && (input instanceof URL$1)) {
63827 input = urlToOptions(input);
63828 }
63829 else {
63830 callback = options;
63831 options = input;
63832 input = { protocol: protocol };
63833 }
63834 if (typeof options === "function") {
63835 callback = options;
63836 options = null;
63837 }
63838
63839 // Set defaults
63840 options = Object.assign({
63841 maxRedirects: exports.maxRedirects,
63842 maxBodyLength: exports.maxBodyLength,
63843 }, input, options);
63844 options.nativeProtocols = nativeProtocols;
63845
63846 assert$1.equal(options.protocol, protocol, "protocol mismatch");
63847 debug$3("options", options);
63848 return new RedirectableRequest(options, callback);
63849 }
63850
63851 // Executes a GET request, following redirects
63852 function get(input, options, callback) {
63853 var wrappedRequest = wrappedProtocol.request(input, options, callback);
63854 wrappedRequest.end();
63855 return wrappedRequest;
63856 }
63857
63858 // Expose the properties on the wrapped protocol
63859 Object.defineProperties(wrappedProtocol, {
63860 request: { value: request, configurable: true, enumerable: true, writable: true },
63861 get: { value: get, configurable: true, enumerable: true, writable: true },
63862 });
63863 });
63864 return exports;
63865}
63866
63867/* istanbul ignore next */
63868function noop$2() { /* empty */ }
63869
63870// from https://github.com/nodejs/node/blob/master/lib/internal/url.js
63871function urlToOptions(urlObject) {
63872 var options = {
63873 protocol: urlObject.protocol,
63874 hostname: urlObject.hostname.startsWith("[") ?
63875 /* istanbul ignore next */
63876 urlObject.hostname.slice(1, -1) :
63877 urlObject.hostname,
63878 hash: urlObject.hash,
63879 search: urlObject.search,
63880 pathname: urlObject.pathname,
63881 path: urlObject.pathname + urlObject.search,
63882 href: urlObject.href,
63883 };
63884 if (urlObject.port !== "") {
63885 options.port = Number(urlObject.port);
63886 }
63887 return options;
63888}
63889
63890function removeMatchingHeaders(regex, headers) {
63891 var lastValue;
63892 for (var header in headers) {
63893 if (regex.test(header)) {
63894 lastValue = headers[header];
63895 delete headers[header];
63896 }
63897 }
63898 return lastValue;
63899}
63900
63901function createErrorType(code, defaultMessage) {
63902 function CustomError(message) {
63903 Error.captureStackTrace(this, this.constructor);
63904 this.message = message || defaultMessage;
63905 }
63906 CustomError.prototype = new Error();
63907 CustomError.prototype.constructor = CustomError;
63908 CustomError.prototype.name = "Error [" + code + "]";
63909 CustomError.prototype.code = code;
63910 return CustomError;
63911}
63912
63913function abortRequest(request) {
63914 for (var e = 0; e < events.length; e++) {
63915 request.removeListener(events[e], eventHandlers[events[e]]);
63916 }
63917 request.on("error", noop$2);
63918 request.abort();
63919}
63920
63921// Exports
63922followRedirects$1.exports = wrap({ http: http$1, https: https$1 });
63923followRedirects$1.exports.wrap = wrap;
63924
63925var httpNative = require$$0__default$8,
63926 httpsNative = require$$1__default$2,
63927 web_o = webOutgoing,
63928 common$1 = common$4,
63929 followRedirects = followRedirects$1.exports;
63930
63931web_o = Object.keys(web_o).map(function(pass) {
63932 return web_o[pass];
63933});
63934
63935var nativeAgents = { http: httpNative, https: httpsNative };
63936
63937/*!
63938 * Array of passes.
63939 *
63940 * A `pass` is just a function that is executed on `req, res, options`
63941 * so that you can easily add new checks while still keeping the base
63942 * flexible.
63943 */
63944
63945
63946var webIncoming = {
63947
63948 /**
63949 * Sets `content-length` to '0' if request is of DELETE type.
63950 *
63951 * @param {ClientRequest} Req Request object
63952 * @param {IncomingMessage} Res Response object
63953 * @param {Object} Options Config object passed to the proxy
63954 *
63955 * @api private
63956 */
63957
63958 deleteLength: function deleteLength(req, res, options) {
63959 if((req.method === 'DELETE' || req.method === 'OPTIONS')
63960 && !req.headers['content-length']) {
63961 req.headers['content-length'] = '0';
63962 delete req.headers['transfer-encoding'];
63963 }
63964 },
63965
63966 /**
63967 * Sets timeout in request socket if it was specified in options.
63968 *
63969 * @param {ClientRequest} Req Request object
63970 * @param {IncomingMessage} Res Response object
63971 * @param {Object} Options Config object passed to the proxy
63972 *
63973 * @api private
63974 */
63975
63976 timeout: function timeout(req, res, options) {
63977 if(options.timeout) {
63978 req.socket.setTimeout(options.timeout);
63979 }
63980 },
63981
63982 /**
63983 * Sets `x-forwarded-*` headers if specified in config.
63984 *
63985 * @param {ClientRequest} Req Request object
63986 * @param {IncomingMessage} Res Response object
63987 * @param {Object} Options Config object passed to the proxy
63988 *
63989 * @api private
63990 */
63991
63992 XHeaders: function XHeaders(req, res, options) {
63993 if(!options.xfwd) return;
63994
63995 var encrypted = req.isSpdy || common$1.hasEncryptedConnection(req);
63996 var values = {
63997 for : req.connection.remoteAddress || req.socket.remoteAddress,
63998 port : common$1.getPort(req),
63999 proto: encrypted ? 'https' : 'http'
64000 };
64001
64002 ['for', 'port', 'proto'].forEach(function(header) {
64003 req.headers['x-forwarded-' + header] =
64004 (req.headers['x-forwarded-' + header] || '') +
64005 (req.headers['x-forwarded-' + header] ? ',' : '') +
64006 values[header];
64007 });
64008
64009 req.headers['x-forwarded-host'] = req.headers['x-forwarded-host'] || req.headers['host'] || '';
64010 },
64011
64012 /**
64013 * Does the actual proxying. If `forward` is enabled fires up
64014 * a ForwardStream, same happens for ProxyStream. The request
64015 * just dies otherwise.
64016 *
64017 * @param {ClientRequest} Req Request object
64018 * @param {IncomingMessage} Res Response object
64019 * @param {Object} Options Config object passed to the proxy
64020 *
64021 * @api private
64022 */
64023
64024 stream: function stream(req, res, options, _, server, clb) {
64025
64026 // And we begin!
64027 server.emit('start', req, res, options.target || options.forward);
64028
64029 var agents = options.followRedirects ? followRedirects : nativeAgents;
64030 var http = agents.http;
64031 var https = agents.https;
64032
64033 if(options.forward) {
64034 // If forward enable, so just pipe the request
64035 var forwardReq = (options.forward.protocol === 'https:' ? https : http).request(
64036 common$1.setupOutgoing(options.ssl || {}, options, req, 'forward')
64037 );
64038
64039 // error handler (e.g. ECONNRESET, ECONNREFUSED)
64040 // Handle errors on incoming request as well as it makes sense to
64041 var forwardError = createErrorHandler(forwardReq, options.forward);
64042 req.on('error', forwardError);
64043 forwardReq.on('error', forwardError);
64044
64045 (options.buffer || req).pipe(forwardReq);
64046 if(!options.target) { return res.end(); }
64047 }
64048
64049 // Request initalization
64050 var proxyReq = (options.target.protocol === 'https:' ? https : http).request(
64051 common$1.setupOutgoing(options.ssl || {}, options, req)
64052 );
64053
64054 // Enable developers to modify the proxyReq before headers are sent
64055 proxyReq.on('socket', function(socket) {
64056 if(server && !proxyReq.getHeader('expect')) {
64057 server.emit('proxyReq', proxyReq, req, res, options);
64058 }
64059 });
64060
64061 // allow outgoing socket to timeout so that we could
64062 // show an error page at the initial request
64063 if(options.proxyTimeout) {
64064 proxyReq.setTimeout(options.proxyTimeout, function() {
64065 proxyReq.abort();
64066 });
64067 }
64068
64069 // Ensure we abort proxy if request is aborted
64070 req.on('aborted', function () {
64071 proxyReq.abort();
64072 });
64073
64074 // handle errors in proxy and incoming request, just like for forward proxy
64075 var proxyError = createErrorHandler(proxyReq, options.target);
64076 req.on('error', proxyError);
64077 proxyReq.on('error', proxyError);
64078
64079 function createErrorHandler(proxyReq, url) {
64080 return function proxyError(err) {
64081 if (req.socket.destroyed && err.code === 'ECONNRESET') {
64082 server.emit('econnreset', err, req, res, url);
64083 return proxyReq.abort();
64084 }
64085
64086 if (clb) {
64087 clb(err, req, res, url);
64088 } else {
64089 server.emit('error', err, req, res, url);
64090 }
64091 }
64092 }
64093
64094 (options.buffer || req).pipe(proxyReq);
64095
64096 proxyReq.on('response', function(proxyRes) {
64097 if(server) { server.emit('proxyRes', proxyRes, req, res); }
64098
64099 if(!res.headersSent && !options.selfHandleResponse) {
64100 for(var i=0; i < web_o.length; i++) {
64101 if(web_o[i](req, res, proxyRes, options)) { break; }
64102 }
64103 }
64104
64105 if (!res.finished) {
64106 // Allow us to listen when the proxy has completed
64107 proxyRes.on('end', function () {
64108 if (server) server.emit('end', req, res, proxyRes);
64109 });
64110 // We pipe to the response unless its expected to be handled by the user
64111 if (!options.selfHandleResponse) proxyRes.pipe(res);
64112 } else {
64113 if (server) server.emit('end', req, res, proxyRes);
64114 }
64115 });
64116 }
64117
64118};
64119
64120var http = require$$0__default$8,
64121 https = require$$1__default$2,
64122 common = common$4;
64123
64124/*!
64125 * Array of passes.
64126 *
64127 * A `pass` is just a function that is executed on `req, socket, options`
64128 * so that you can easily add new checks while still keeping the base
64129 * flexible.
64130 */
64131
64132/*
64133 * Websockets Passes
64134 *
64135 */
64136
64137
64138var wsIncoming = {
64139 /**
64140 * WebSocket requests must have the `GET` method and
64141 * the `upgrade:websocket` header
64142 *
64143 * @param {ClientRequest} Req Request object
64144 * @param {Socket} Websocket
64145 *
64146 * @api private
64147 */
64148
64149 checkMethodAndHeader : function checkMethodAndHeader(req, socket) {
64150 if (req.method !== 'GET' || !req.headers.upgrade) {
64151 socket.destroy();
64152 return true;
64153 }
64154
64155 if (req.headers.upgrade.toLowerCase() !== 'websocket') {
64156 socket.destroy();
64157 return true;
64158 }
64159 },
64160
64161 /**
64162 * Sets `x-forwarded-*` headers if specified in config.
64163 *
64164 * @param {ClientRequest} Req Request object
64165 * @param {Socket} Websocket
64166 * @param {Object} Options Config object passed to the proxy
64167 *
64168 * @api private
64169 */
64170
64171 XHeaders : function XHeaders(req, socket, options) {
64172 if(!options.xfwd) return;
64173
64174 var values = {
64175 for : req.connection.remoteAddress || req.socket.remoteAddress,
64176 port : common.getPort(req),
64177 proto: common.hasEncryptedConnection(req) ? 'wss' : 'ws'
64178 };
64179
64180 ['for', 'port', 'proto'].forEach(function(header) {
64181 req.headers['x-forwarded-' + header] =
64182 (req.headers['x-forwarded-' + header] || '') +
64183 (req.headers['x-forwarded-' + header] ? ',' : '') +
64184 values[header];
64185 });
64186 },
64187
64188 /**
64189 * Does the actual proxying. Make the request and upgrade it
64190 * send the Switching Protocols request and pipe the sockets.
64191 *
64192 * @param {ClientRequest} Req Request object
64193 * @param {Socket} Websocket
64194 * @param {Object} Options Config object passed to the proxy
64195 *
64196 * @api private
64197 */
64198 stream : function stream(req, socket, options, head, server, clb) {
64199
64200 var createHttpHeader = function(line, headers) {
64201 return Object.keys(headers).reduce(function (head, key) {
64202 var value = headers[key];
64203
64204 if (!Array.isArray(value)) {
64205 head.push(key + ': ' + value);
64206 return head;
64207 }
64208
64209 for (var i = 0; i < value.length; i++) {
64210 head.push(key + ': ' + value[i]);
64211 }
64212 return head;
64213 }, [line])
64214 .join('\r\n') + '\r\n\r\n';
64215 };
64216
64217 common.setupSocket(socket);
64218
64219 if (head && head.length) socket.unshift(head);
64220
64221
64222 var proxyReq = (common.isSSL.test(options.target.protocol) ? https : http).request(
64223 common.setupOutgoing(options.ssl || {}, options, req)
64224 );
64225
64226 // Enable developers to modify the proxyReq before headers are sent
64227 if (server) { server.emit('proxyReqWs', proxyReq, req, socket, options, head); }
64228
64229 // Error Handler
64230 proxyReq.on('error', onOutgoingError);
64231 proxyReq.on('response', function (res) {
64232 // if upgrade event isn't going to happen, close the socket
64233 if (!res.upgrade) {
64234 socket.write(createHttpHeader('HTTP/' + res.httpVersion + ' ' + res.statusCode + ' ' + res.statusMessage, res.headers));
64235 res.pipe(socket);
64236 }
64237 });
64238
64239 proxyReq.on('upgrade', function(proxyRes, proxySocket, proxyHead) {
64240 proxySocket.on('error', onOutgoingError);
64241
64242 // Allow us to listen when the websocket has completed
64243 proxySocket.on('end', function () {
64244 server.emit('close', proxyRes, proxySocket, proxyHead);
64245 });
64246
64247 // The pipe below will end proxySocket if socket closes cleanly, but not
64248 // if it errors (eg, vanishes from the net and starts returning
64249 // EHOSTUNREACH). We need to do that explicitly.
64250 socket.on('error', function () {
64251 proxySocket.end();
64252 });
64253
64254 common.setupSocket(proxySocket);
64255
64256 if (proxyHead && proxyHead.length) proxySocket.unshift(proxyHead);
64257
64258 //
64259 // Remark: Handle writing the headers to the socket when switching protocols
64260 // Also handles when a header is an array
64261 //
64262 socket.write(createHttpHeader('HTTP/1.1 101 Switching Protocols', proxyRes.headers));
64263
64264 proxySocket.pipe(socket).pipe(proxySocket);
64265
64266 server.emit('open', proxySocket);
64267 server.emit('proxySocket', proxySocket); //DEPRECATED.
64268 });
64269
64270 return proxyReq.end(); // XXX: CHECK IF THIS IS THIS CORRECT
64271
64272 function onOutgoingError(err) {
64273 if (clb) {
64274 clb(err, req, socket);
64275 } else {
64276 server.emit('error', err, req, socket);
64277 }
64278 socket.end();
64279 }
64280 }
64281};
64282
64283(function (module) {
64284var httpProxy = module.exports,
64285 extend = require$$0__default$3._extend,
64286 parse_url = require$$0__default$7.parse,
64287 EE3 = eventemitter3.exports,
64288 http = require$$0__default$8,
64289 https = require$$1__default$2,
64290 web = webIncoming,
64291 ws = wsIncoming;
64292
64293httpProxy.Server = ProxyServer;
64294
64295/**
64296 * Returns a function that creates the loader for
64297 * either `ws` or `web`'s passes.
64298 *
64299 * Examples:
64300 *
64301 * httpProxy.createRightProxy('ws')
64302 * // => [Function]
64303 *
64304 * @param {String} Type Either 'ws' or 'web'
64305
64306 * @return {Function} Loader Function that when called returns an iterator for the right passes
64307 *
64308 * @api private
64309 */
64310
64311function createRightProxy(type) {
64312
64313 return function(options) {
64314 return function(req, res /*, [head], [opts] */) {
64315 var passes = (type === 'ws') ? this.wsPasses : this.webPasses,
64316 args = [].slice.call(arguments),
64317 cntr = args.length - 1,
64318 head, cbl;
64319
64320 /* optional args parse begin */
64321 if(typeof args[cntr] === 'function') {
64322 cbl = args[cntr];
64323
64324 cntr--;
64325 }
64326
64327 var requestOptions = options;
64328 if(
64329 !(args[cntr] instanceof Buffer) &&
64330 args[cntr] !== res
64331 ) {
64332 //Copy global options
64333 requestOptions = extend({}, options);
64334 //Overwrite with request options
64335 extend(requestOptions, args[cntr]);
64336
64337 cntr--;
64338 }
64339
64340 if(args[cntr] instanceof Buffer) {
64341 head = args[cntr];
64342 }
64343
64344 /* optional args parse end */
64345
64346 ['target', 'forward'].forEach(function(e) {
64347 if (typeof requestOptions[e] === 'string')
64348 requestOptions[e] = parse_url(requestOptions[e]);
64349 });
64350
64351 if (!requestOptions.target && !requestOptions.forward) {
64352 return this.emit('error', new Error('Must provide a proper URL as target'));
64353 }
64354
64355 for(var i=0; i < passes.length; i++) {
64356 /**
64357 * Call of passes functions
64358 * pass(req, res, options, head)
64359 *
64360 * In WebSockets case the `res` variable
64361 * refer to the connection socket
64362 * pass(req, socket, options, head)
64363 */
64364 if(passes[i](req, res, requestOptions, head, this, cbl)) { // passes can return a truthy value to halt the loop
64365 break;
64366 }
64367 }
64368 };
64369 };
64370}
64371httpProxy.createRightProxy = createRightProxy;
64372
64373function ProxyServer(options) {
64374 EE3.call(this);
64375
64376 options = options || {};
64377 options.prependPath = options.prependPath === false ? false : true;
64378
64379 this.web = this.proxyRequest = createRightProxy('web')(options);
64380 this.ws = this.proxyWebsocketRequest = createRightProxy('ws')(options);
64381 this.options = options;
64382
64383 this.webPasses = Object.keys(web).map(function(pass) {
64384 return web[pass];
64385 });
64386
64387 this.wsPasses = Object.keys(ws).map(function(pass) {
64388 return ws[pass];
64389 });
64390
64391 this.on('error', this.onError, this);
64392
64393}
64394
64395require$$0__default$3.inherits(ProxyServer, EE3);
64396
64397ProxyServer.prototype.onError = function (err) {
64398 //
64399 // Remark: Replicate node core behavior using EE3
64400 // so we force people to handle their own errors
64401 //
64402 if(this.listeners('error').length === 1) {
64403 throw err;
64404 }
64405};
64406
64407ProxyServer.prototype.listen = function(port, hostname) {
64408 var self = this,
64409 closure = function(req, res) { self.web(req, res); };
64410
64411 this._server = this.options.ssl ?
64412 https.createServer(this.options.ssl, closure) :
64413 http.createServer(closure);
64414
64415 if(this.options.ws) {
64416 this._server.on('upgrade', function(req, socket, head) { self.ws(req, socket, head); });
64417 }
64418
64419 this._server.listen(port, hostname);
64420
64421 return this;
64422};
64423
64424ProxyServer.prototype.close = function(callback) {
64425 var self = this;
64426 if (this._server) {
64427 this._server.close(done);
64428 }
64429
64430 // Wrap callback to nullify server after all open connections are closed.
64431 function done() {
64432 self._server = null;
64433 if (callback) {
64434 callback.apply(null, arguments);
64435 }
64436 }};
64437
64438ProxyServer.prototype.before = function(type, passName, callback) {
64439 if (type !== 'ws' && type !== 'web') {
64440 throw new Error('type must be `web` or `ws`');
64441 }
64442 var passes = (type === 'ws') ? this.wsPasses : this.webPasses,
64443 i = false;
64444
64445 passes.forEach(function(v, idx) {
64446 if(v.name === passName) i = idx;
64447 });
64448
64449 if(i === false) throw new Error('No such pass');
64450
64451 passes.splice(i, 0, callback);
64452};
64453ProxyServer.prototype.after = function(type, passName, callback) {
64454 if (type !== 'ws' && type !== 'web') {
64455 throw new Error('type must be `web` or `ws`');
64456 }
64457 var passes = (type === 'ws') ? this.wsPasses : this.webPasses,
64458 i = false;
64459
64460 passes.forEach(function(v, idx) {
64461 if(v.name === passName) i = idx;
64462 });
64463
64464 if(i === false) throw new Error('No such pass');
64465
64466 passes.splice(i++, 0, callback);
64467};
64468}(httpProxy$2));
64469
64470// Use explicit /index.js to help browserify negociation in require '/lib/http-proxy' (!)
64471var ProxyServer = httpProxy$2.exports.Server;
64472
64473
64474/**
64475 * Creates the proxy server.
64476 *
64477 * Examples:
64478 *
64479 * httpProxy.createProxyServer({ .. }, 8000)
64480 * // => '{ web: [Function], ws: [Function] ... }'
64481 *
64482 * @param {Object} Options Config object passed to the proxy
64483 *
64484 * @return {Object} Proxy Proxy object with handlers for `ws` and `web` requests
64485 *
64486 * @api public
64487 */
64488
64489
64490function createProxyServer(options) {
64491 /*
64492 * `options` is needed and it must have the following layout:
64493 *
64494 * {
64495 * target : <url string to be parsed with the url module>
64496 * forward: <url string to be parsed with the url module>
64497 * agent : <object to be passed to http(s).request>
64498 * ssl : <object to be passed to https.createServer()>
64499 * ws : <true/false, if you want to proxy websockets>
64500 * xfwd : <true/false, adds x-forward headers>
64501 * secure : <true/false, verify SSL certificate>
64502 * toProxy: <true/false, explicitly specify if we are proxying to another proxy>
64503 * prependPath: <true/false, Default: true - specify whether you want to prepend the target's path to the proxy path>
64504 * ignorePath: <true/false, Default: false - specify whether you want to ignore the proxy path of the incoming request>
64505 * localAddress : <Local interface string to bind for outgoing connections>
64506 * changeOrigin: <true/false, Default: false - changes the origin of the host header to the target URL>
64507 * preserveHeaderKeyCase: <true/false, Default: false - specify whether you want to keep letter case of response header key >
64508 * auth : Basic authentication i.e. 'user:password' to compute an Authorization header.
64509 * hostRewrite: rewrites the location hostname on (201/301/302/307/308) redirects, Default: null.
64510 * autoRewrite: rewrites the location host/port on (201/301/302/307/308) redirects based on requested host/port. Default: false.
64511 * protocolRewrite: rewrites the location protocol on (201/301/302/307/308) redirects to 'http' or 'https'. Default: null.
64512 * }
64513 *
64514 * NOTE: `options.ws` and `options.ssl` are optional.
64515 * `options.target and `options.forward` cannot be
64516 * both missing
64517 * }
64518 */
64519
64520 return new ProxyServer(options);
64521}
64522
64523
64524ProxyServer.createProxyServer = createProxyServer;
64525ProxyServer.createServer = createProxyServer;
64526ProxyServer.createProxy = createProxyServer;
64527
64528
64529
64530
64531/**
64532 * Export the proxy "Server" as the main export.
64533 */
64534var httpProxy$1 = ProxyServer;
64535
64536/*!
64537 * Caron dimonio, con occhi di bragia
64538 * loro accennando, tutte le raccoglie;
64539 * batte col remo qualunque s’adagia
64540 *
64541 * Charon the demon, with the eyes of glede,
64542 * Beckoning to them, collects them all together,
64543 * Beats with his oar whoever lags behind
64544 *
64545 * Dante - The Divine Comedy (Canto III)
64546 */
64547
64548var httpProxy = httpProxy$1;
64549
64550const debug$2 = createDebugger('vite:proxy');
64551function proxyMiddleware(httpServer, config) {
64552 const options = config.server.proxy;
64553 // lazy require only when proxy is used
64554 const proxies = {};
64555 Object.keys(options).forEach((context) => {
64556 let opts = options[context];
64557 if (typeof opts === 'string') {
64558 opts = { target: opts, changeOrigin: true };
64559 }
64560 const proxy = httpProxy.createProxyServer(opts);
64561 proxy.on('error', (err) => {
64562 config.logger.error(`${source.red(`http proxy error:`)}\n${err.stack}`, {
64563 timestamp: true
64564 });
64565 });
64566 if (opts.configure) {
64567 opts.configure(proxy, opts);
64568 }
64569 // clone before saving because http-proxy mutates the options
64570 proxies[context] = [proxy, { ...opts }];
64571 });
64572 if (httpServer) {
64573 httpServer.on('upgrade', (req, socket, head) => {
64574 var _a;
64575 const url = req.url;
64576 for (const context in proxies) {
64577 if (url.startsWith(context)) {
64578 const [proxy, opts] = proxies[context];
64579 if ((opts.ws || ((_a = opts.target) === null || _a === void 0 ? void 0 : _a.toString().startsWith('ws:'))) &&
64580 req.headers['sec-websocket-protocol'] !== HMR_HEADER) {
64581 if (opts.rewrite) {
64582 req.url = opts.rewrite(url);
64583 }
64584 proxy.ws(req, socket, head);
64585 }
64586 }
64587 }
64588 });
64589 }
64590 // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
64591 return function viteProxyMiddleware(req, res, next) {
64592 const url = req.url;
64593 for (const context in proxies) {
64594 if ((context.startsWith('^') && new RegExp(context).test(url)) ||
64595 url.startsWith(context)) {
64596 const [proxy, opts] = proxies[context];
64597 const options = {};
64598 if (opts.bypass) {
64599 const bypassResult = opts.bypass(req, res, opts);
64600 if (typeof bypassResult === 'string') {
64601 req.url = bypassResult;
64602 debug$2(`bypass: ${req.url} -> ${bypassResult}`);
64603 return next();
64604 }
64605 else if (typeof bypassResult === 'object') {
64606 Object.assign(options, bypassResult);
64607 debug$2(`bypass: ${req.url} use modified options: %O`, options);
64608 return next();
64609 }
64610 else if (bypassResult === false) {
64611 debug$2(`bypass: ${req.url} -> 404`);
64612 return res.end(404);
64613 }
64614 }
64615 debug$2(`${req.url} -> ${opts.target || opts.forward}`);
64616 if (opts.rewrite) {
64617 req.url = opts.rewrite(req.url);
64618 }
64619 proxy.web(req, res, options);
64620 return;
64621 }
64622 }
64623 next();
64624 };
64625}
64626
64627/*!
64628 * etag
64629 * Copyright(c) 2014-2016 Douglas Christopher Wilson
64630 * MIT Licensed
64631 */
64632
64633/**
64634 * Module exports.
64635 * @public
64636 */
64637
64638var etag_1 = etag;
64639
64640/**
64641 * Module dependencies.
64642 * @private
64643 */
64644
64645var crypto = require$$1__default$1;
64646var Stats = fs__default.Stats;
64647
64648/**
64649 * Module variables.
64650 * @private
64651 */
64652
64653var toString = Object.prototype.toString;
64654
64655/**
64656 * Generate an entity tag.
64657 *
64658 * @param {Buffer|string} entity
64659 * @return {string}
64660 * @private
64661 */
64662
64663function entitytag (entity) {
64664 if (entity.length === 0) {
64665 // fast-path empty
64666 return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"'
64667 }
64668
64669 // compute hash of entity
64670 var hash = crypto
64671 .createHash('sha1')
64672 .update(entity, 'utf8')
64673 .digest('base64')
64674 .substring(0, 27);
64675
64676 // compute length of entity
64677 var len = typeof entity === 'string'
64678 ? Buffer.byteLength(entity, 'utf8')
64679 : entity.length;
64680
64681 return '"' + len.toString(16) + '-' + hash + '"'
64682}
64683
64684/**
64685 * Create a simple ETag.
64686 *
64687 * @param {string|Buffer|Stats} entity
64688 * @param {object} [options]
64689 * @param {boolean} [options.weak]
64690 * @return {String}
64691 * @public
64692 */
64693
64694function etag (entity, options) {
64695 if (entity == null) {
64696 throw new TypeError('argument entity is required')
64697 }
64698
64699 // support fs.Stats object
64700 var isStats = isstats(entity);
64701 var weak = options && typeof options.weak === 'boolean'
64702 ? options.weak
64703 : isStats;
64704
64705 // validate argument
64706 if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) {
64707 throw new TypeError('argument entity must be string, Buffer, or fs.Stats')
64708 }
64709
64710 // generate entity tag
64711 var tag = isStats
64712 ? stattag(entity)
64713 : entitytag(entity);
64714
64715 return weak
64716 ? 'W/' + tag
64717 : tag
64718}
64719
64720/**
64721 * Determine if object is a Stats object.
64722 *
64723 * @param {object} obj
64724 * @return {boolean}
64725 * @api private
64726 */
64727
64728function isstats (obj) {
64729 // genuine fs.Stats
64730 if (typeof Stats === 'function' && obj instanceof Stats) {
64731 return true
64732 }
64733
64734 // quack quack
64735 return obj && typeof obj === 'object' &&
64736 'ctime' in obj && toString.call(obj.ctime) === '[object Date]' &&
64737 'mtime' in obj && toString.call(obj.mtime) === '[object Date]' &&
64738 'ino' in obj && typeof obj.ino === 'number' &&
64739 'size' in obj && typeof obj.size === 'number'
64740}
64741
64742/**
64743 * Generate a tag for a stat.
64744 *
64745 * @param {object} stat
64746 * @return {string}
64747 * @private
64748 */
64749
64750function stattag (stat) {
64751 var mtime = stat.mtime.getTime().toString(16);
64752 var size = stat.size.toString(16);
64753
64754 return '"' + size + '-' + mtime + '"'
64755}
64756
64757const isDebug$3 = process.env.DEBUG;
64758const alias$1 = {
64759 js: 'application/javascript',
64760 css: 'text/css',
64761 html: 'text/html',
64762 json: 'application/json'
64763};
64764function send$1(req, res, content, type, etag = etag_1(content, { weak: true }), cacheControl = 'no-cache', map) {
64765 if (req.headers['if-none-match'] === etag) {
64766 res.statusCode = 304;
64767 return res.end();
64768 }
64769 res.setHeader('Content-Type', alias$1[type] || type);
64770 res.setHeader('Cache-Control', cacheControl);
64771 res.setHeader('Etag', etag);
64772 // inject source map reference
64773 if (map && map.mappings) {
64774 if (isDebug$3) {
64775 content += `\n/*${JSON.stringify(map, null, 2).replace(/\*\//g, '*\\/')}*/\n`;
64776 }
64777 content += genSourceMapString(map);
64778 }
64779 res.statusCode = 200;
64780 return res.end(content);
64781}
64782function genSourceMapString(map) {
64783 if (typeof map !== 'string') {
64784 map = JSON.stringify(map);
64785 }
64786 return `\n//# sourceMappingURL=data:application/json;base64,${Buffer.from(map).toString('base64')}`;
64787}
64788
64789var convertSourceMap = {};
64790
64791var safeBuffer = {exports: {}};
64792
64793/* eslint-disable node/no-deprecated-api */
64794
64795(function (module, exports) {
64796var buffer = require$$0__default$9;
64797var Buffer = buffer.Buffer;
64798
64799// alternative to using Object.keys for old browsers
64800function copyProps (src, dst) {
64801 for (var key in src) {
64802 dst[key] = src[key];
64803 }
64804}
64805if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
64806 module.exports = buffer;
64807} else {
64808 // Copy properties from require('buffer')
64809 copyProps(buffer, exports);
64810 exports.Buffer = SafeBuffer;
64811}
64812
64813function SafeBuffer (arg, encodingOrOffset, length) {
64814 return Buffer(arg, encodingOrOffset, length)
64815}
64816
64817// Copy static methods from Buffer
64818copyProps(Buffer, SafeBuffer);
64819
64820SafeBuffer.from = function (arg, encodingOrOffset, length) {
64821 if (typeof arg === 'number') {
64822 throw new TypeError('Argument must not be a number')
64823 }
64824 return Buffer(arg, encodingOrOffset, length)
64825};
64826
64827SafeBuffer.alloc = function (size, fill, encoding) {
64828 if (typeof size !== 'number') {
64829 throw new TypeError('Argument must be a number')
64830 }
64831 var buf = Buffer(size);
64832 if (fill !== undefined) {
64833 if (typeof encoding === 'string') {
64834 buf.fill(fill, encoding);
64835 } else {
64836 buf.fill(fill);
64837 }
64838 } else {
64839 buf.fill(0);
64840 }
64841 return buf
64842};
64843
64844SafeBuffer.allocUnsafe = function (size) {
64845 if (typeof size !== 'number') {
64846 throw new TypeError('Argument must be a number')
64847 }
64848 return Buffer(size)
64849};
64850
64851SafeBuffer.allocUnsafeSlow = function (size) {
64852 if (typeof size !== 'number') {
64853 throw new TypeError('Argument must be a number')
64854 }
64855 return buffer.SlowBuffer(size)
64856};
64857}(safeBuffer, safeBuffer.exports));
64858
64859(function (exports) {
64860var fs = fs__default;
64861var path = path__default;
64862var SafeBuffer = safeBuffer.exports;
64863
64864Object.defineProperty(exports, 'commentRegex', {
64865 get: function getCommentRegex () {
64866 return /^\s*\/(?:\/|\*)[@#]\s+sourceMappingURL=data:(?:application|text)\/json;(?:charset[:=]\S+?;)?base64,(?:.*)$/mg;
64867 }
64868});
64869
64870Object.defineProperty(exports, 'mapFileCommentRegex', {
64871 get: function getMapFileCommentRegex () {
64872 // Matches sourceMappingURL in either // or /* comment styles.
64873 return /(?:\/\/[@#][ \t]+sourceMappingURL=([^\s'"`]+?)[ \t]*$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^\*]+?)[ \t]*(?:\*\/){1}[ \t]*$)/mg;
64874 }
64875});
64876
64877
64878function decodeBase64(base64) {
64879 return (SafeBuffer.Buffer.from(base64, 'base64') || "").toString();
64880}
64881
64882function stripComment(sm) {
64883 return sm.split(',').pop();
64884}
64885
64886function readFromFileMap(sm, dir) {
64887 // NOTE: this will only work on the server since it attempts to read the map file
64888
64889 var r = exports.mapFileCommentRegex.exec(sm);
64890
64891 // for some odd reason //# .. captures in 1 and /* .. */ in 2
64892 var filename = r[1] || r[2];
64893 var filepath = path.resolve(dir, filename);
64894
64895 try {
64896 return fs.readFileSync(filepath, 'utf8');
64897 } catch (e) {
64898 throw new Error('An error occurred while trying to read the map file at ' + filepath + '\n' + e);
64899 }
64900}
64901
64902function Converter (sm, opts) {
64903 opts = opts || {};
64904
64905 if (opts.isFileComment) sm = readFromFileMap(sm, opts.commentFileDir);
64906 if (opts.hasComment) sm = stripComment(sm);
64907 if (opts.isEncoded) sm = decodeBase64(sm);
64908 if (opts.isJSON || opts.isEncoded) sm = JSON.parse(sm);
64909
64910 this.sourcemap = sm;
64911}
64912
64913Converter.prototype.toJSON = function (space) {
64914 return JSON.stringify(this.sourcemap, null, space);
64915};
64916
64917Converter.prototype.toBase64 = function () {
64918 var json = this.toJSON();
64919 return (SafeBuffer.Buffer.from(json, 'utf8') || "").toString('base64');
64920};
64921
64922Converter.prototype.toComment = function (options) {
64923 var base64 = this.toBase64();
64924 var data = 'sourceMappingURL=data:application/json;charset=utf-8;base64,' + base64;
64925 return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data;
64926};
64927
64928// returns copy instead of original
64929Converter.prototype.toObject = function () {
64930 return JSON.parse(this.toJSON());
64931};
64932
64933Converter.prototype.addProperty = function (key, value) {
64934 if (this.sourcemap.hasOwnProperty(key)) throw new Error('property "' + key + '" already exists on the sourcemap, use set property instead');
64935 return this.setProperty(key, value);
64936};
64937
64938Converter.prototype.setProperty = function (key, value) {
64939 this.sourcemap[key] = value;
64940 return this;
64941};
64942
64943Converter.prototype.getProperty = function (key) {
64944 return this.sourcemap[key];
64945};
64946
64947exports.fromObject = function (obj) {
64948 return new Converter(obj);
64949};
64950
64951exports.fromJSON = function (json) {
64952 return new Converter(json, { isJSON: true });
64953};
64954
64955exports.fromBase64 = function (base64) {
64956 return new Converter(base64, { isEncoded: true });
64957};
64958
64959exports.fromComment = function (comment) {
64960 comment = comment
64961 .replace(/^\/\*/g, '//')
64962 .replace(/\*\/$/g, '');
64963
64964 return new Converter(comment, { isEncoded: true, hasComment: true });
64965};
64966
64967exports.fromMapFileComment = function (comment, dir) {
64968 return new Converter(comment, { commentFileDir: dir, isFileComment: true, isJSON: true });
64969};
64970
64971// Finds last sourcemap comment in file or returns null if none was found
64972exports.fromSource = function (content) {
64973 var m = content.match(exports.commentRegex);
64974 return m ? exports.fromComment(m.pop()) : null;
64975};
64976
64977// Finds last sourcemap comment in file or returns null if none was found
64978exports.fromMapFileSource = function (content, dir) {
64979 var m = content.match(exports.mapFileCommentRegex);
64980 return m ? exports.fromMapFileComment(m.pop(), dir) : null;
64981};
64982
64983exports.removeComments = function (src) {
64984 return src.replace(exports.commentRegex, '');
64985};
64986
64987exports.removeMapFileComments = function (src) {
64988 return src.replace(exports.mapFileCommentRegex, '');
64989};
64990
64991exports.generateMapFileComment = function (file, options) {
64992 var data = 'sourceMappingURL=' + file;
64993 return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data;
64994};
64995}(convertSourceMap));
64996
64997/**
64998 *
64999 * @param {Node} param
65000 * @returns {string[]}
65001 */
65002function extract_names(param) {
65003 return extract_identifiers(param).map(node => node.name);
65004}
65005
65006/**
65007 *
65008 * @param {Node} param
65009 * @param {Identifier[]} nodes
65010 * @returns {Identifier[]}
65011 */
65012function extract_identifiers(param, nodes = []) {
65013 switch (param.type) {
65014 case 'Identifier':
65015 nodes.push(param);
65016 break;
65017
65018 case 'MemberExpression':
65019 let object = param;
65020 while (object.type === 'MemberExpression') {
65021 object = /** @type {any} */ (object.object);
65022 }
65023 nodes.push(/** @type {any} */ (object));
65024 break;
65025
65026 case 'ObjectPattern':
65027 /**
65028 *
65029 * @param {Property | RestElement} prop
65030 */
65031 const handle_prop = (prop) => {
65032 if (prop.type === 'RestElement') {
65033 extract_identifiers(prop.argument, nodes);
65034 } else {
65035 extract_identifiers(prop.value, nodes);
65036 }
65037 };
65038
65039 param.properties.forEach(handle_prop);
65040 break;
65041
65042 case 'ArrayPattern':
65043 /**
65044 *
65045 * @param {Node} element
65046 */
65047 const handle_element = (element) => {
65048 if (element) extract_identifiers(element, nodes);
65049 };
65050
65051 param.elements.forEach(handle_element);
65052 break;
65053
65054 case 'RestElement':
65055 extract_identifiers(param.argument, nodes);
65056 break;
65057
65058 case 'AssignmentPattern':
65059 extract_identifiers(param.left, nodes);
65060 break;
65061 }
65062
65063 return nodes;
65064}
65065
65066const ssrModuleExportsKey = `__vite_ssr_exports__`;
65067const ssrImportKey = `__vite_ssr_import__`;
65068const ssrDynamicImportKey = `__vite_ssr_dynamic_import__`;
65069const ssrExportAllKey = `__vite_ssr_exportAll__`;
65070const ssrImportMetaKey = `__vite_ssr_import_meta__`;
65071async function ssrTransform(code, inMap, url) {
65072 const s = new MagicString(code);
65073 const ast = parser.parse(code, {
65074 sourceType: 'module',
65075 ecmaVersion: 2021,
65076 locations: true
65077 });
65078 let uid = 0;
65079 const deps = new Set();
65080 const idToImportMap = new Map();
65081 const declaredConst = new Set();
65082 function defineImport(node, source) {
65083 deps.add(source);
65084 const importId = `__vite_ssr_import_${uid++}__`;
65085 s.appendLeft(node.start, `const ${importId} = ${ssrImportKey}(${JSON.stringify(source)})\n`);
65086 return importId;
65087 }
65088 function defineExport(name, local = name) {
65089 s.append(`\nObject.defineProperty(${ssrModuleExportsKey}, "${name}", ` +
65090 `{ enumerable: true, configurable: true, get(){ return ${local} }})`);
65091 }
65092 // 1. check all import statements and record id -> importName map
65093 for (const node of ast.body) {
65094 // import foo from 'foo' --> foo -> __import_foo__.default
65095 // import { baz } from 'foo' --> baz -> __import_foo__.baz
65096 // import * as ok from 'foo' --> ok -> __import_foo__
65097 if (node.type === 'ImportDeclaration') {
65098 const importId = defineImport(node, node.source.value);
65099 for (const spec of node.specifiers) {
65100 if (spec.type === 'ImportSpecifier') {
65101 idToImportMap.set(spec.local.name, `${importId}.${spec.imported.name}`);
65102 }
65103 else if (spec.type === 'ImportDefaultSpecifier') {
65104 idToImportMap.set(spec.local.name, `${importId}.default`);
65105 }
65106 else {
65107 // namespace specifier
65108 idToImportMap.set(spec.local.name, importId);
65109 }
65110 }
65111 s.remove(node.start, node.end);
65112 }
65113 }
65114 // 2. check all export statements and define exports
65115 for (const node of ast.body) {
65116 // named exports
65117 if (node.type === 'ExportNamedDeclaration') {
65118 if (node.declaration) {
65119 if (node.declaration.type === 'FunctionDeclaration' ||
65120 node.declaration.type === 'ClassDeclaration') {
65121 // export function foo() {}
65122 defineExport(node.declaration.id.name);
65123 }
65124 else {
65125 // export const foo = 1, bar = 2
65126 for (const declaration of node.declaration.declarations) {
65127 const names = extract_names(declaration.id);
65128 for (const name of names) {
65129 defineExport(name);
65130 }
65131 }
65132 }
65133 s.remove(node.start, node.declaration.start);
65134 }
65135 else if (node.source) {
65136 // export { foo, bar } from './foo'
65137 const importId = defineImport(node, node.source.value);
65138 for (const spec of node.specifiers) {
65139 defineExport(spec.exported.name, `${importId}.${spec.local.name}`);
65140 }
65141 s.remove(node.start, node.end);
65142 }
65143 else {
65144 // export { foo, bar }
65145 for (const spec of node.specifiers) {
65146 const local = spec.local.name;
65147 const binding = idToImportMap.get(local);
65148 defineExport(spec.exported.name, binding || local);
65149 }
65150 s.remove(node.start, node.end);
65151 }
65152 }
65153 // default export
65154 if (node.type === 'ExportDefaultDeclaration') {
65155 if ('id' in node.declaration && node.declaration.id) {
65156 // named hoistable/class exports
65157 // export default function foo() {}
65158 // export default class A {}
65159 const { name } = node.declaration.id;
65160 s.remove(node.start, node.start + 15 /* 'export default '.length */);
65161 s.append(`\nObject.defineProperty(${ssrModuleExportsKey}, "default", ` +
65162 `{ enumerable: true, value: ${name} })`);
65163 }
65164 else {
65165 // anonymous default exports
65166 s.overwrite(node.start, node.start + 14 /* 'export default'.length */, `${ssrModuleExportsKey}.default =`);
65167 }
65168 }
65169 // export * from './foo'
65170 if (node.type === 'ExportAllDeclaration') {
65171 if (node.exported) {
65172 const importId = defineImport(node, node.source.value);
65173 defineExport(node.exported.name, `${importId}`);
65174 s.remove(node.start, node.end);
65175 }
65176 else {
65177 const importId = defineImport(node, node.source.value);
65178 s.remove(node.start, node.end);
65179 s.append(`\n${ssrExportAllKey}(${importId})`);
65180 }
65181 }
65182 }
65183 // 3. convert references to import bindings & import.meta references
65184 walk(ast, {
65185 onIdentifier(id, parent, parentStack) {
65186 const binding = idToImportMap.get(id.name);
65187 if (!binding) {
65188 return;
65189 }
65190 if (isStaticProperty(parent) && parent.shorthand) {
65191 // let binding used in a property shorthand
65192 // { foo } -> { foo: __import_x__.foo }
65193 // skip for destructuring patterns
65194 if (!parent.inPattern ||
65195 isInDestructuringAssignment(parent, parentStack)) {
65196 s.appendLeft(id.end, `: ${binding}`);
65197 }
65198 }
65199 else if (parent.type === 'ClassDeclaration' &&
65200 id === parent.superClass) {
65201 if (!declaredConst.has(id.name)) {
65202 declaredConst.add(id.name);
65203 // locate the top-most node containing the class declaration
65204 const topNode = parentStack[1];
65205 s.prependRight(topNode.start, `const ${id.name} = ${binding};\n`);
65206 }
65207 }
65208 else {
65209 s.overwrite(id.start, id.end, binding);
65210 }
65211 },
65212 onImportMeta(node) {
65213 s.overwrite(node.start, node.end, ssrImportMetaKey);
65214 },
65215 onDynamicImport(node) {
65216 s.overwrite(node.start, node.start + 6, ssrDynamicImportKey);
65217 }
65218 });
65219 let map = s.generateMap({ hires: true });
65220 if (inMap && inMap.mappings && inMap.sources.length > 0) {
65221 map = combineSourcemaps(url, [
65222 {
65223 ...map,
65224 sources: inMap.sources,
65225 sourcesContent: inMap.sourcesContent
65226 },
65227 inMap
65228 ]);
65229 }
65230 else {
65231 map.sources = [url];
65232 map.sourcesContent = [code];
65233 }
65234 return {
65235 code: s.toString(),
65236 map,
65237 deps: [...deps]
65238 };
65239}
65240/**
65241 * Same logic from \@vue/compiler-core & \@vue/compiler-sfc
65242 * Except this is using acorn AST
65243 */
65244function walk(root, { onIdentifier, onImportMeta, onDynamicImport }) {
65245 const parentStack = [];
65246 const scope = Object.create(null);
65247 const scopeMap = new WeakMap();
65248 const setScope = (node, name) => {
65249 let scopeIds = scopeMap.get(node);
65250 if (scopeIds && scopeIds.has(name)) {
65251 return;
65252 }
65253 if (name in scope) {
65254 scope[name]++;
65255 }
65256 else {
65257 scope[name] = 1;
65258 }
65259 if (!scopeIds) {
65260 scopeIds = new Set();
65261 scopeMap.set(node, scopeIds);
65262 }
65263 scopeIds.add(name);
65264 };
65265 walk$1(root, {
65266 enter(node, parent) {
65267 if (node.type === 'ImportDeclaration') {
65268 return this.skip();
65269 }
65270 parent && parentStack.push(parent);
65271 if (node.type === 'MetaProperty' && node.meta.name === 'import') {
65272 onImportMeta(node);
65273 }
65274 else if (node.type === 'ImportExpression') {
65275 onDynamicImport(node);
65276 }
65277 if (node.type === 'Identifier') {
65278 if (!scope[node.name] && isRefIdentifier(node, parent, parentStack)) {
65279 onIdentifier(node, parent, parentStack);
65280 }
65281 }
65282 else if (isFunction(node)) {
65283 // walk function expressions and add its arguments to known identifiers
65284 // so that we don't prefix them
65285 node.params.forEach((p) => walk$1(p, {
65286 enter(child, parent) {
65287 if (child.type === 'Identifier' &&
65288 // do not record as scope variable if is a destructuring key
65289 !isStaticPropertyKey(child, parent) &&
65290 // do not record if this is a default value
65291 // assignment of a destructuring variable
65292 !(parent &&
65293 parent.type === 'AssignmentPattern' &&
65294 parent.right === child)) {
65295 setScope(node, child.name);
65296 }
65297 }
65298 }));
65299 }
65300 else if (node.type === 'Property' && parent.type === 'ObjectPattern') {
65301 node.inPattern = true;
65302 }
65303 else if (node.type === 'VariableDeclarator') {
65304 const parentFunction = findParentFunction(parentStack);
65305 if (parentFunction) {
65306 if (node.id.type === 'ObjectPattern') {
65307 node.id.properties.forEach((property) => {
65308 if (property.type === 'RestElement') {
65309 setScope(parentFunction, property.argument.name);
65310 }
65311 else {
65312 setScope(parentFunction, property.value.name);
65313 }
65314 });
65315 }
65316 else {
65317 setScope(parentFunction, node.id.name);
65318 }
65319 }
65320 }
65321 },
65322 leave(node, parent) {
65323 parent && parentStack.pop();
65324 const scopeIds = scopeMap.get(node);
65325 if (scopeIds) {
65326 scopeIds.forEach((id) => {
65327 scope[id]--;
65328 if (scope[id] === 0) {
65329 delete scope[id];
65330 }
65331 });
65332 }
65333 }
65334 });
65335}
65336function isRefIdentifier(id, parent, parentStack) {
65337 // declaration id
65338 if (parent.type === 'CatchClause' ||
65339 ((parent.type === 'VariableDeclarator' ||
65340 parent.type === 'ClassDeclaration') &&
65341 parent.id === id)) {
65342 return false;
65343 }
65344 if (isFunction(parent)) {
65345 // function declaration/expression id
65346 if (parent.id === id) {
65347 return false;
65348 }
65349 // params list
65350 if (parent.params.includes(id)) {
65351 return false;
65352 }
65353 }
65354 // class method name
65355 if (parent.type === 'MethodDefinition') {
65356 return false;
65357 }
65358 // property key
65359 // this also covers object destructuring pattern
65360 if (isStaticPropertyKey(id, parent) || parent.inPattern) {
65361 return false;
65362 }
65363 // non-assignment array destructuring pattern
65364 if (parent.type === 'ArrayPattern' &&
65365 !isInDestructuringAssignment(parent, parentStack)) {
65366 return false;
65367 }
65368 // member expression property
65369 if (parent.type === 'MemberExpression' &&
65370 parent.property === id &&
65371 !parent.computed) {
65372 return false;
65373 }
65374 if (parent.type === 'ExportSpecifier') {
65375 return false;
65376 }
65377 // is a special keyword but parsed as identifier
65378 if (id.name === 'arguments') {
65379 return false;
65380 }
65381 return true;
65382}
65383const isStaticProperty = (node) => node && node.type === 'Property' && !node.computed;
65384const isStaticPropertyKey = (node, parent) => isStaticProperty(parent) && parent.key === node;
65385function isFunction(node) {
65386 return /Function(?:Expression|Declaration)$|Method$/.test(node.type);
65387}
65388function findParentFunction(parentStack) {
65389 for (let i = parentStack.length - 1; i >= 0; i--) {
65390 const node = parentStack[i];
65391 if (isFunction(node)) {
65392 return node;
65393 }
65394 }
65395}
65396function isInDestructuringAssignment(parent, parentStack) {
65397 if (parent &&
65398 (parent.type === 'Property' || parent.type === 'ArrayPattern')) {
65399 let i = parentStack.length;
65400 while (i--) {
65401 const p = parentStack[i];
65402 if (p.type === 'AssignmentExpression') {
65403 return true;
65404 }
65405 else if (p.type !== 'Property' && !p.type.endsWith('Pattern')) {
65406 break;
65407 }
65408 }
65409 }
65410 return false;
65411}
65412
65413async function injectSourcesContent(map, file) {
65414 const sourceRoot = await fs$w.promises.realpath(path__default.resolve(path__default.dirname(file), map.sourceRoot || ''));
65415 map.sourcesContent = [];
65416 await Promise.all(map.sources.filter(Boolean).map(async (sourcePath, i) => {
65417 map.sourcesContent[i] = await fs$w.promises.readFile(path__default.resolve(sourceRoot, decodeURI(sourcePath)), 'utf-8');
65418 }));
65419}
65420
65421/**
65422 * @typedef ParsedURL
65423 * @type {import('.').ParsedURL}
65424 */
65425
65426/**
65427 * @typedef Request
65428 * @property {string} url
65429 * @property {boolean} _decoded
65430 * @property {ParsedURL} _parsedUrl
65431 */
65432
65433/**
65434 * @param {Request} req
65435 * @param {boolean} [toDecode]
65436 * @returns {ParsedURL|void}
65437 */
65438function parse$4(req, toDecode) {
65439 let raw = req.url;
65440 if (raw == null) return;
65441
65442 let prev = req._parsedUrl;
65443 if (prev && prev.raw === raw) return prev;
65444
65445 let pathname=raw, search='', query;
65446
65447 if (raw.length > 1) {
65448 let idx = raw.indexOf('?', 1);
65449
65450 if (idx !== -1) {
65451 search = raw.substring(idx);
65452 pathname = raw.substring(0, idx);
65453 if (search.length > 1) {
65454 query = qs__namespace.parse(search.substring(1));
65455 }
65456 }
65457
65458 if (!!toDecode && !req._decoded) {
65459 req._decoded = true;
65460 if (pathname.indexOf('%') !== -1) {
65461 try { pathname = decodeURIComponent(pathname); }
65462 catch (e) { /* URI malformed */ }
65463 }
65464 }
65465 }
65466
65467 return req._parsedUrl = { pathname, search, query, raw };
65468}
65469
65470function list(dir, callback, pre='') {
65471 dir = path$A.resolve('.', dir);
65472 let arr = fs$w.readdirSync(dir);
65473 let i=0, abs, stats;
65474 for (; i < arr.length; i++) {
65475 abs = path$A.join(dir, arr[i]);
65476 stats = fs$w.statSync(abs);
65477 stats.isDirectory()
65478 ? list(abs, callback, path$A.join(pre, arr[i]))
65479 : callback(path$A.join(pre, arr[i]), abs, stats);
65480 }
65481}
65482
65483/**
65484 * @param typeMap [Object] Map of MIME type -> Array[extensions]
65485 * @param ...
65486 */
65487function Mime$1() {
65488 this._types = Object.create(null);
65489 this._extensions = Object.create(null);
65490
65491 for (let i = 0; i < arguments.length; i++) {
65492 this.define(arguments[i]);
65493 }
65494
65495 this.define = this.define.bind(this);
65496 this.getType = this.getType.bind(this);
65497 this.getExtension = this.getExtension.bind(this);
65498}
65499
65500/**
65501 * Define mimetype -> extension mappings. Each key is a mime-type that maps
65502 * to an array of extensions associated with the type. The first extension is
65503 * used as the default extension for the type.
65504 *
65505 * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']});
65506 *
65507 * If a type declares an extension that has already been defined, an error will
65508 * be thrown. To suppress this error and force the extension to be associated
65509 * with the new type, pass `force`=true. Alternatively, you may prefix the
65510 * extension with "*" to map the type to extension, without mapping the
65511 * extension to the type.
65512 *
65513 * e.g. mime.define({'audio/wav', ['wav']}, {'audio/x-wav', ['*wav']});
65514 *
65515 *
65516 * @param map (Object) type definitions
65517 * @param force (Boolean) if true, force overriding of existing definitions
65518 */
65519Mime$1.prototype.define = function(typeMap, force) {
65520 for (let type in typeMap) {
65521 let extensions = typeMap[type].map(function(t) {
65522 return t.toLowerCase();
65523 });
65524 type = type.toLowerCase();
65525
65526 for (let i = 0; i < extensions.length; i++) {
65527 const ext = extensions[i];
65528
65529 // '*' prefix = not the preferred type for this extension. So fixup the
65530 // extension, and skip it.
65531 if (ext[0] === '*') {
65532 continue;
65533 }
65534
65535 if (!force && (ext in this._types)) {
65536 throw new Error(
65537 'Attempt to change mapping for "' + ext +
65538 '" extension from "' + this._types[ext] + '" to "' + type +
65539 '". Pass `force=true` to allow this, otherwise remove "' + ext +
65540 '" from the list of extensions for "' + type + '".'
65541 );
65542 }
65543
65544 this._types[ext] = type;
65545 }
65546
65547 // Use first extension as default
65548 if (force || !this._extensions[type]) {
65549 const ext = extensions[0];
65550 this._extensions[type] = (ext[0] !== '*') ? ext : ext.substr(1);
65551 }
65552 }
65553};
65554
65555/**
65556 * Lookup a mime type based on extension
65557 */
65558Mime$1.prototype.getType = function(path) {
65559 path = String(path);
65560 let last = path.replace(/^.*[/\\]/, '').toLowerCase();
65561 let ext = last.replace(/^.*\./, '').toLowerCase();
65562
65563 let hasPath = last.length < path.length;
65564 let hasDot = ext.length < last.length - 1;
65565
65566 return (hasDot || !hasPath) && this._types[ext] || null;
65567};
65568
65569/**
65570 * Return file extension associated with a mime type
65571 */
65572Mime$1.prototype.getExtension = function(type) {
65573 type = /^\s*([^;\s]*)/.test(type) && RegExp.$1;
65574 return type && this._extensions[type.toLowerCase()] || null;
65575};
65576
65577var Mime_1 = Mime$1;
65578
65579var standard = {"application/andrew-inset":["ez"],"application/applixware":["aw"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cu-seeme":["cu"],"application/dash+xml":["mpd"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["ecma","es"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["js","mjs"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["mp4s","m4p"],"application/mrb-consumer+xml":["*xdf"],"application/mrb-publish+xml":["*xdf"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["*xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-signature":["asc","sig"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-error+xml":["xer"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avif":["avif"],"image/bmp":["bmp"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/stl":["stl"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["markdown","md"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]};
65580
65581let Mime = Mime_1;
65582var lite = new Mime(standard);
65583
65584const noop$1 = () => {};
65585
65586function isMatch(uri, arr) {
65587 for (let i=0; i < arr.length; i++) {
65588 if (arr[i].test(uri)) return true;
65589 }
65590}
65591
65592function toAssume(uri, extns) {
65593 let i=0, x, len=uri.length - 1;
65594 if (uri.charCodeAt(len) === 47) {
65595 uri = uri.substring(0, len);
65596 }
65597
65598 let arr=[], tmp=`${uri}/index`;
65599 for (; i < extns.length; i++) {
65600 x = extns[i] ? `.${extns[i]}` : '';
65601 if (uri) arr.push(uri + x);
65602 arr.push(tmp + x);
65603 }
65604
65605 return arr;
65606}
65607
65608function viaCache(cache, uri, extns) {
65609 let i=0, data, arr=toAssume(uri, extns);
65610 for (; i < arr.length; i++) {
65611 if (data = cache[arr[i]]) return data;
65612 }
65613}
65614
65615function viaLocal(dir, isEtag, uri, extns) {
65616 let i=0, arr=toAssume(uri, extns);
65617 let abs, stats, name, headers;
65618 for (; i < arr.length; i++) {
65619 abs = path$A.normalize(path$A.join(dir, name=arr[i]));
65620 if (abs.startsWith(dir) && fs__namespace.existsSync(abs)) {
65621 stats = fs__namespace.statSync(abs);
65622 if (stats.isDirectory()) continue;
65623 headers = toHeaders(name, stats, isEtag);
65624 headers['Cache-Control'] = isEtag ? 'no-cache' : 'no-store';
65625 return { abs, stats, headers };
65626 }
65627 }
65628}
65629
65630function is404(req, res) {
65631 return (res.statusCode=404,res.end());
65632}
65633
65634function send(req, res, file, stats, headers) {
65635 let code=200, tmp, opts={};
65636 headers = { ...headers };
65637
65638 for (let key in headers) {
65639 tmp = res.getHeader(key);
65640 if (tmp) headers[key] = tmp;
65641 }
65642
65643 if (tmp = res.getHeader('content-type')) {
65644 headers['Content-Type'] = tmp;
65645 }
65646
65647 if (req.headers.range) {
65648 code = 206;
65649 let [x, y] = req.headers.range.replace('bytes=', '').split('-');
65650 let end = opts.end = parseInt(y, 10) || stats.size - 1;
65651 let start = opts.start = parseInt(x, 10) || 0;
65652
65653 if (start >= stats.size || end >= stats.size) {
65654 res.setHeader('Content-Range', `bytes */${stats.size}`);
65655 res.statusCode = 416;
65656 return res.end();
65657 }
65658
65659 headers['Content-Range'] = `bytes ${start}-${end}/${stats.size}`;
65660 headers['Content-Length'] = (end - start + 1);
65661 headers['Accept-Ranges'] = 'bytes';
65662 }
65663
65664 res.writeHead(code, headers);
65665 fs__namespace.createReadStream(file, opts).pipe(res);
65666}
65667
65668function isEncoding(name, type, headers) {
65669 headers['Content-Encoding'] = type;
65670 headers['Content-Type'] = lite.getType(name.replace(/\.([^.]*)$/, '')) || '';
65671}
65672
65673function toHeaders(name, stats, isEtag) {
65674 let headers = {
65675 'Content-Length': stats.size,
65676 'Content-Type': lite.getType(name) || '',
65677 'Last-Modified': stats.mtime.toUTCString(),
65678 };
65679 if (isEtag) headers['ETag'] = `W/"${stats.size}-${stats.mtime.getTime()}"`;
65680 if (/\.br$/.test(name)) isEncoding(name, 'br', headers);
65681 if (/\.gz$/.test(name)) isEncoding(name, 'gzip', headers);
65682 return headers;
65683}
65684
65685function sirv (dir, opts={}) {
65686 dir = path$A.resolve(dir || '.');
65687
65688 let isNotFound = opts.onNoMatch || is404;
65689 let setHeaders = opts.setHeaders || noop$1;
65690
65691 let extensions = opts.extensions || ['html', 'htm'];
65692 let gzips = opts.gzip && extensions.map(x => `${x}.gz`).concat('gz');
65693 let brots = opts.brotli && extensions.map(x => `${x}.br`).concat('br');
65694
65695 const FILES = {};
65696
65697 let fallback = '/';
65698 let isEtag = !!opts.etag;
65699 let isSPA = !!opts.single;
65700 if (typeof opts.single === 'string') {
65701 let idx = opts.single.lastIndexOf('.');
65702 fallback += !!~idx ? opts.single.substring(0, idx) : opts.single;
65703 }
65704
65705 let ignores = [];
65706 if (opts.ignores !== false) {
65707 ignores.push(/[/]([A-Za-z\s\d~$._-]+\.\w+){1,}$/); // any extn
65708 if (opts.dotfiles) ignores.push(/\/\.\w/);
65709 else ignores.push(/\/\.well-known/);
65710 [].concat(opts.ignores || []).forEach(x => {
65711 ignores.push(new RegExp(x, 'i'));
65712 });
65713 }
65714
65715 let cc = opts.maxAge != null && `public,max-age=${opts.maxAge}`;
65716 if (cc && opts.immutable) cc += ',immutable';
65717 else if (cc && opts.maxAge === 0) cc += ',must-revalidate';
65718
65719 if (!opts.dev) {
65720 list(dir, (name, abs, stats) => {
65721 if (/\.well-known[\\+\/]/.test(name)) ; // keep
65722 else if (!opts.dotfiles && /(^\.|[\\+|\/+]\.)/.test(name)) return;
65723
65724 let headers = toHeaders(name, stats, isEtag);
65725 if (cc) headers['Cache-Control'] = cc;
65726
65727 FILES['/' + name.normalize().replace(/\\+/g, '/')] = { abs, stats, headers };
65728 });
65729 }
65730
65731 let lookup = opts.dev ? viaLocal.bind(0, dir, isEtag) : viaCache.bind(0, FILES);
65732
65733 return function (req, res, next) {
65734 let extns = [''];
65735 let val = req.headers['accept-encoding'] || '';
65736 if (gzips && val.includes('gzip')) extns.unshift(...gzips);
65737 if (brots && /(br|brotli)/i.test(val)) extns.unshift(...brots);
65738 extns.push(...extensions); // [...br, ...gz, orig, ...exts]
65739
65740 let pathname = req.path || parse$4(req, true).pathname;
65741 let data = lookup(pathname, extns) || isSPA && !isMatch(pathname, ignores) && lookup(fallback, extns);
65742 if (!data) return next ? next() : isNotFound(req, res);
65743
65744 if (isEtag && req.headers['if-none-match'] === data.headers['ETag']) {
65745 res.writeHead(304);
65746 return res.end();
65747 }
65748
65749 if (gzips || brots) {
65750 res.setHeader('Vary', 'Accept-Encoding');
65751 }
65752
65753 setHeaders(res, pathname, data.stats);
65754 send(req, res, data.abs, data.stats, data.headers);
65755 };
65756}
65757
65758const sirvOptions = {
65759 dev: true,
65760 etag: true,
65761 extensions: [],
65762 setHeaders(res, pathname) {
65763 // Matches js, jsx, ts, tsx.
65764 // The reason this is done, is that the .ts file extension is reserved
65765 // for the MIME type video/mp2t. In almost all cases, we can expect
65766 // these files to be TypeScript files, and for Vite to serve them with
65767 // this Content-Type.
65768 if (/\.[tj]sx?$/.test(pathname)) {
65769 res.setHeader('Content-Type', 'application/javascript');
65770 }
65771 }
65772};
65773function servePublicMiddleware(dir) {
65774 const serve = sirv(dir, sirvOptions);
65775 // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
65776 return function viteServePublicMiddleware(req, res, next) {
65777 // skip import request
65778 if (isImportRequest(req.url)) {
65779 return next();
65780 }
65781 serve(req, res, next);
65782 };
65783}
65784function serveStaticMiddleware(dir, config) {
65785 const serve = sirv(dir, sirvOptions);
65786 // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
65787 return function viteServeStaticMiddleware(req, res, next) {
65788 const url = req.url;
65789 // only serve the file if it's not an html request
65790 // so that html requests can fallthrough to our html middleware for
65791 // special processing
65792 if (path__default.extname(cleanUrl(url)) === '.html') {
65793 return next();
65794 }
65795 // apply aliases to static requests as well
65796 let redirected;
65797 for (const { find, replacement } of config.resolve.alias) {
65798 const matches = typeof find === 'string' ? url.startsWith(find) : find.test(url);
65799 if (matches) {
65800 redirected = url.replace(find, replacement);
65801 break;
65802 }
65803 }
65804 if (redirected) {
65805 // dir is pre-normalized to posix style
65806 if (redirected.startsWith(dir)) {
65807 redirected = redirected.slice(dir.length);
65808 }
65809 req.url = redirected;
65810 }
65811 serve(req, res, next);
65812 };
65813}
65814function serveRawFsMiddleware(server) {
65815 const serveFromRoot = sirv('/', sirvOptions);
65816 // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
65817 return function viteServeRawFsMiddleware(req, res, next) {
65818 let url = req.url;
65819 // In some cases (e.g. linked monorepos) files outside of root will
65820 // reference assets that are also out of served root. In such cases
65821 // the paths are rewritten to `/@fs/` prefixed paths and must be served by
65822 // searching based from fs root.
65823 if (url.startsWith(FS_PREFIX)) {
65824 // restrict files outside of `fs.allow`
65825 ensureServingAccess(slash$3(path__default.resolve(fsPathFromId(url))), server);
65826 url = url.slice(FS_PREFIX.length);
65827 if (isWindows$4)
65828 url = url.replace(/^[A-Z]:/i, '');
65829 req.url = url;
65830 serveFromRoot(req, res, next);
65831 }
65832 else {
65833 next();
65834 }
65835 };
65836}
65837function isFileServingAllowed(url, server) {
65838 // explicitly disabled
65839 if (server.config.server.fs.strict === false)
65840 return true;
65841 const file = ensureLeadingSlash(normalizePath$4(cleanUrl(url)));
65842 if (server.moduleGraph.safeModulesPath.has(file))
65843 return true;
65844 if (server.config.server.fs.allow.some((i) => file.startsWith(i + '/')))
65845 return true;
65846 if (!server.config.server.fs.strict) {
65847 server.config.logger.warnOnce(`Unrestricted file system access to "${url}"`);
65848 server.config.logger.warnOnce(`For security concerns, accessing files outside of serving allow list will ` +
65849 `be restricted by default in the future version of Vite. ` +
65850 `Refer to https://vitejs.dev/config/#server-fs-allow for more details.`);
65851 return true;
65852 }
65853 return false;
65854}
65855function ensureServingAccess(url, server) {
65856 if (!isFileServingAllowed(url, server)) {
65857 const allow = server.config.server.fs.allow;
65858 throw new AccessRestrictedError(`The request url "${url}" is outside of Vite serving allow list:
65859
65860${allow.map((i) => `- ${i}`).join('\n')}
65861
65862Refer to docs https://vitejs.dev/config/#server-fs-allow for configurations and more details.`);
65863 }
65864}
65865
65866const debugLoad = createDebugger('vite:load');
65867const debugTransform = createDebugger('vite:transform');
65868const debugCache$1 = createDebugger('vite:cache');
65869const isDebug$2 = !!process.env.DEBUG;
65870async function transformRequest(url, server, options = {}) {
65871 var _a, _b;
65872 const { config, pluginContainer, moduleGraph, watcher } = server;
65873 url = removeTimestampQuery(url);
65874 const { root, logger } = config;
65875 const prettyUrl = isDebug$2 ? prettifyUrl(url, root) : '';
65876 const ssr = !!options.ssr;
65877 // check if we have a fresh cache
65878 const module = await moduleGraph.getModuleByUrl(url);
65879 const cached = module && (ssr ? module.ssrTransformResult : module.transformResult);
65880 if (cached) {
65881 isDebug$2 && debugCache$1(`[memory] ${prettyUrl}`);
65882 return cached;
65883 }
65884 // resolve
65885 const id = ((_a = (await pluginContainer.resolveId(url))) === null || _a === void 0 ? void 0 : _a.id) || url;
65886 const file = cleanUrl(id);
65887 let code = null;
65888 let map = null;
65889 // load
65890 const loadStart = isDebug$2 ? Date.now() : 0;
65891 const loadResult = await pluginContainer.load(id, ssr);
65892 if (loadResult == null) {
65893 // if this is an html request and there is no load result, skip ahead to
65894 // SPA fallback.
65895 if (options.html && !id.endsWith('.html')) {
65896 return null;
65897 }
65898 // try fallback loading it from fs as string
65899 // if the file is a binary, there should be a plugin that already loaded it
65900 // as string
65901 // only try the fallback if access is allowed, skip for out of root url
65902 // like /service-worker.js or /api/users
65903 if (options.ssr || isFileServingAllowed(file, server)) {
65904 try {
65905 code = await fs$w.promises.readFile(file, 'utf-8');
65906 isDebug$2 && debugLoad(`${timeFrom(loadStart)} [fs] ${prettyUrl}`);
65907 }
65908 catch (e) {
65909 if (e.code !== 'ENOENT') {
65910 throw e;
65911 }
65912 }
65913 }
65914 if (code) {
65915 try {
65916 map = (_b = (convertSourceMap.fromSource(code) ||
65917 convertSourceMap.fromMapFileSource(code, path__default.dirname(file)))) === null || _b === void 0 ? void 0 : _b.toObject();
65918 }
65919 catch (e) {
65920 logger.warn(`Failed to load source map for ${url}.`, {
65921 timestamp: true
65922 });
65923 }
65924 }
65925 }
65926 else {
65927 isDebug$2 && debugLoad(`${timeFrom(loadStart)} [plugin] ${prettyUrl}`);
65928 if (typeof loadResult === 'object') {
65929 code = loadResult.code;
65930 map = loadResult.map;
65931 }
65932 else {
65933 code = loadResult;
65934 }
65935 }
65936 if (code == null) {
65937 if (checkPublicFile(url, config)) {
65938 throw new Error(`Failed to load url ${url} (resolved id: ${id}). ` +
65939 `This file is in /public and will be copied as-is during build without ` +
65940 `going through the plugin transforms, and therefore should not be ` +
65941 `imported from source code. It can only be referenced via HTML tags.`);
65942 }
65943 else {
65944 return null;
65945 }
65946 }
65947 // ensure module in graph after successful load
65948 const mod = await moduleGraph.ensureEntryFromUrl(url);
65949 ensureWatchedFile(watcher, mod.file, root);
65950 // transform
65951 const transformStart = isDebug$2 ? Date.now() : 0;
65952 const transformResult = await pluginContainer.transform(code, id, map, ssr);
65953 if (transformResult == null ||
65954 (typeof transformResult === 'object' && transformResult.code == null)) {
65955 // no transform applied, keep code as-is
65956 isDebug$2 &&
65957 debugTransform(timeFrom(transformStart) + source.dim(` [skipped] ${prettyUrl}`));
65958 }
65959 else {
65960 isDebug$2 && debugTransform(`${timeFrom(transformStart)} ${prettyUrl}`);
65961 code = transformResult.code;
65962 map = transformResult.map;
65963 }
65964 if (map && mod.file) {
65965 map = (typeof map === 'string' ? JSON.parse(map) : map);
65966 if (map.mappings && !map.sourcesContent) {
65967 await injectSourcesContent(map, mod.file);
65968 }
65969 }
65970 if (ssr) {
65971 return (mod.ssrTransformResult = await ssrTransform(code, map, url));
65972 }
65973 else {
65974 return (mod.transformResult = {
65975 code,
65976 map,
65977 etag: etag_1(code, { weak: true })
65978 });
65979 }
65980}
65981
65982/**
65983 * Time (ms) Vite has to full-reload the page before returning
65984 * an empty response.
65985 */
65986const NEW_DEPENDENCY_BUILD_TIMEOUT = 1000;
65987const debugCache = createDebugger('vite:cache');
65988const isDebug$1 = !!process.env.DEBUG;
65989const knownIgnoreList = new Set(['/', '/favicon.ico']);
65990function transformMiddleware(server) {
65991 const { config: { root, logger, cacheDir }, moduleGraph } = server;
65992 // determine the url prefix of files inside cache directory
65993 let cacheDirPrefix;
65994 if (cacheDir) {
65995 const cacheDirRelative = normalizePath$4(path__default.relative(root, cacheDir));
65996 if (cacheDirRelative.startsWith('../')) {
65997 // if the cache directory is outside root, the url prefix would be something
65998 // like '/@fs/absolute/path/to/node_modules/.vite'
65999 cacheDirPrefix = `/@fs/${normalizePath$4(cacheDir).replace(/^\//, '')}`;
66000 }
66001 else {
66002 // if the cache directory is inside root, the url prefix would be something
66003 // like '/node_modules/.vite'
66004 cacheDirPrefix = `/${cacheDirRelative}`;
66005 }
66006 }
66007 // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
66008 return async function viteTransformMiddleware(req, res, next) {
66009 var _a, _b, _c, _d, _e, _f, _g, _h, _j;
66010 if (req.method !== 'GET' || knownIgnoreList.has(req.url)) {
66011 return next();
66012 }
66013 if (server._pendingReload &&
66014 // always allow vite client requests so that it can trigger page reload
66015 !((_a = req.url) === null || _a === void 0 ? void 0 : _a.startsWith(CLIENT_PUBLIC_PATH)) &&
66016 !((_b = req.url) === null || _b === void 0 ? void 0 : _b.includes('vite/dist/client'))) {
66017 // missing dep pending reload, hold request until reload happens
66018 server._pendingReload.then(() =>
66019 // If the refresh has not happened after timeout, Vite considers
66020 // something unexpected has happened. In this case, Vite
66021 // returns an empty response that will error.
66022 setTimeout(() => {
66023 // status code request timeout
66024 res.statusCode = 408;
66025 res.end(`<h1>[vite] Something unexpected happened while optimizing "${req.url}"<h1>` +
66026 `<p>The current page should have reloaded by now</p>`);
66027 }, NEW_DEPENDENCY_BUILD_TIMEOUT));
66028 return;
66029 }
66030 let url;
66031 try {
66032 url = removeTimestampQuery(req.url).replace(NULL_BYTE_PLACEHOLDER, '\0');
66033 }
66034 catch (err) {
66035 // if it starts with %PUBLIC%, someone's migrating from something
66036 // like create-react-app
66037 let errorMessage;
66038 if ((_c = req.url) === null || _c === void 0 ? void 0 : _c.startsWith('/%PUBLIC')) {
66039 errorMessage = `index.html shouldn't include environment variables like %PUBLIC_URL%, see https://vitejs.dev/guide/#index-html-and-project-root for more information`;
66040 }
66041 else {
66042 errorMessage = `Vite encountered a suspiciously malformed request ${req.url}`;
66043 }
66044 next(new Error(errorMessage));
66045 return;
66046 }
66047 const withoutQuery = cleanUrl(url);
66048 try {
66049 const isSourceMap = withoutQuery.endsWith('.map');
66050 // since we generate source map references, handle those requests here
66051 if (isSourceMap) {
66052 const originalUrl = url.replace(/\.map($|\?)/, '$1');
66053 const map = (_e = (_d = (await moduleGraph.getModuleByUrl(originalUrl))) === null || _d === void 0 ? void 0 : _d.transformResult) === null || _e === void 0 ? void 0 : _e.map;
66054 if (map) {
66055 return send$1(req, res, JSON.stringify(map), 'json');
66056 }
66057 else {
66058 return next();
66059 }
66060 }
66061 // warn explicit /public/ paths
66062 if (url.startsWith('/public/')) {
66063 logger.warn(source.yellow(`files in the public directory are served at the root path.\n` +
66064 `Instead of ${source.cyan(url)}, use ${source.cyan(url.replace(/^\/public\//, '/'))}.`));
66065 }
66066 if (isJSRequest(url) ||
66067 isImportRequest(url) ||
66068 isCSSRequest(url) ||
66069 isHTMLProxy(url)) {
66070 // strip ?import
66071 url = removeImportQuery(url);
66072 // Strip valid id prefix. This is prepended to resolved Ids that are
66073 // not valid browser import specifiers by the importAnalysis plugin.
66074 url = unwrapId$1(url);
66075 // for CSS, we need to differentiate between normal CSS requests and
66076 // imports
66077 if (isCSSRequest(url) && ((_f = req.headers.accept) === null || _f === void 0 ? void 0 : _f.includes('text/css'))) {
66078 url = injectQuery(url, 'direct');
66079 }
66080 // check if we can return 304 early
66081 const ifNoneMatch = req.headers['if-none-match'];
66082 if (ifNoneMatch &&
66083 ((_h = (_g = (await moduleGraph.getModuleByUrl(url))) === null || _g === void 0 ? void 0 : _g.transformResult) === null || _h === void 0 ? void 0 : _h.etag) ===
66084 ifNoneMatch) {
66085 isDebug$1 && debugCache(`[304] ${prettifyUrl(url, root)}`);
66086 res.statusCode = 304;
66087 return res.end();
66088 }
66089 // resolve, load and transform using the plugin container
66090 const result = await transformRequest(url, server, {
66091 html: (_j = req.headers.accept) === null || _j === void 0 ? void 0 : _j.includes('text/html')
66092 });
66093 if (result) {
66094 const type = isDirectCSSRequest(url) ? 'css' : 'js';
66095 const isDep = DEP_VERSION_RE.test(url) ||
66096 (cacheDirPrefix && url.startsWith(cacheDirPrefix));
66097 return send$1(req, res, result.code, type, result.etag,
66098 // allow browser to cache npm deps!
66099 isDep ? 'max-age=31536000,immutable' : 'no-cache', result.map);
66100 }
66101 }
66102 }
66103 catch (e) {
66104 return next(e);
66105 }
66106 next();
66107 };
66108}
66109
66110function createDevHtmlTransformFn(server) {
66111 const [preHooks, postHooks] = resolveHtmlTransforms(server.config.plugins);
66112 return (url, html, originalUrl) => {
66113 return applyHtmlTransforms(html, [...preHooks, devHtmlHook, ...postHooks], {
66114 path: url,
66115 filename: getHtmlFilename(url, server),
66116 server,
66117 originalUrl
66118 });
66119 };
66120}
66121function getHtmlFilename(url, server) {
66122 if (url.startsWith(FS_PREFIX)) {
66123 return fsPathFromId(url);
66124 }
66125 else {
66126 return path__default.join(server.config.root, url.slice(1));
66127 }
66128}
66129const startsWithSingleSlashRE = /^\/(?!\/)/;
66130const processNodeUrl = (node, s, config, htmlPath, originalUrl) => {
66131 var _a;
66132 const url = ((_a = node.value) === null || _a === void 0 ? void 0 : _a.content) || '';
66133 if (startsWithSingleSlashRE.test(url)) {
66134 // prefix with base
66135 s.overwrite(node.value.loc.start.offset, node.value.loc.end.offset, `"${config.base + url.slice(1)}"`);
66136 }
66137 else if (url.startsWith('.') &&
66138 originalUrl &&
66139 originalUrl !== '/' &&
66140 htmlPath === '/index.html') {
66141 // #3230 if some request url (localhost:3000/a/b) return to fallback html, the relative assets
66142 // path will add `/a/` prefix, it will caused 404.
66143 // rewrite before `./index.js` -> `localhost:3000/a/index.js`.
66144 // rewrite after `../index.js` -> `localhost:3000/index.js`.
66145 s.overwrite(node.value.loc.start.offset, node.value.loc.end.offset, `"${path__default.posix.join(path__default.posix.relative(originalUrl, '/'), url.slice(1))}"`);
66146 }
66147};
66148const devHtmlHook = async (html, { path: htmlPath, server, originalUrl }) => {
66149 // TODO: solve this design issue
66150 // Optional chain expressions can return undefined by design
66151 // eslint-disable-next-line @typescript-eslint/no-non-null-asserted-optional-chain
66152 const config = server === null || server === void 0 ? void 0 : server.config;
66153 const base = config.base || '/';
66154 const s = new MagicString(html);
66155 let scriptModuleIndex = -1;
66156 await traverseHtml(html, htmlPath, (node) => {
66157 if (node.type !== 1 /* ELEMENT */) {
66158 return;
66159 }
66160 // script tags
66161 if (node.tag === 'script') {
66162 const { src, isModule } = getScriptInfo(node);
66163 if (isModule) {
66164 scriptModuleIndex++;
66165 }
66166 if (src) {
66167 processNodeUrl(src, s, config, htmlPath, originalUrl);
66168 }
66169 else if (isModule) {
66170 // inline js module. convert to src="proxy"
66171 s.overwrite(node.loc.start.offset, node.loc.end.offset, `<script type="module" src="${config.base + htmlPath.slice(1)}?html-proxy&index=${scriptModuleIndex}.js"></script>`);
66172 }
66173 }
66174 // elements with [href/src] attrs
66175 const assetAttrs = assetAttrsConfig[node.tag];
66176 if (assetAttrs) {
66177 for (const p of node.props) {
66178 if (p.type === 6 /* ATTRIBUTE */ &&
66179 p.value &&
66180 assetAttrs.includes(p.name)) {
66181 processNodeUrl(p, s, config, htmlPath, originalUrl);
66182 }
66183 }
66184 }
66185 });
66186 html = s.toString();
66187 return {
66188 html,
66189 tags: [
66190 {
66191 tag: 'script',
66192 attrs: {
66193 type: 'module',
66194 src: path__default.posix.join(base, CLIENT_PUBLIC_PATH)
66195 },
66196 injectTo: 'head-prepend'
66197 }
66198 ]
66199 };
66200};
66201function indexHtmlMiddleware(server) {
66202 // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
66203 return async function viteIndexHtmlMiddleware(req, res, next) {
66204 const url = req.url && cleanUrl(req.url);
66205 // spa-fallback always redirects to /index.html
66206 if ((url === null || url === void 0 ? void 0 : url.endsWith('.html')) && req.headers['sec-fetch-dest'] !== 'script') {
66207 const filename = getHtmlFilename(url, server);
66208 if (fs__default.existsSync(filename)) {
66209 try {
66210 let html = fs__default.readFileSync(filename, 'utf-8');
66211 html = await server.transformIndexHtml(url, html, req.originalUrl);
66212 return send$1(req, res, html, 'html');
66213 }
66214 catch (e) {
66215 return next(e);
66216 }
66217 }
66218 }
66219 next();
66220 };
66221}
66222
66223var lib = {exports: {}};
66224
66225(function (module, exports) {
66226
66227var url = require$$0__default$7;
66228
66229module.exports = function historyApiFallback(options) {
66230 options = options || {};
66231 var logger = getLogger(options);
66232
66233 return function(req, res, next) {
66234 var headers = req.headers;
66235 if (req.method !== 'GET') {
66236 logger(
66237 'Not rewriting',
66238 req.method,
66239 req.url,
66240 'because the method is not GET.'
66241 );
66242 return next();
66243 } else if (!headers || typeof headers.accept !== 'string') {
66244 logger(
66245 'Not rewriting',
66246 req.method,
66247 req.url,
66248 'because the client did not send an HTTP accept header.'
66249 );
66250 return next();
66251 } else if (headers.accept.indexOf('application/json') === 0) {
66252 logger(
66253 'Not rewriting',
66254 req.method,
66255 req.url,
66256 'because the client prefers JSON.'
66257 );
66258 return next();
66259 } else if (!acceptsHtml(headers.accept, options)) {
66260 logger(
66261 'Not rewriting',
66262 req.method,
66263 req.url,
66264 'because the client does not accept HTML.'
66265 );
66266 return next();
66267 }
66268
66269 var parsedUrl = url.parse(req.url);
66270 var rewriteTarget;
66271 options.rewrites = options.rewrites || [];
66272 for (var i = 0; i < options.rewrites.length; i++) {
66273 var rewrite = options.rewrites[i];
66274 var match = parsedUrl.pathname.match(rewrite.from);
66275 if (match !== null) {
66276 rewriteTarget = evaluateRewriteRule(parsedUrl, match, rewrite.to, req);
66277
66278 if(rewriteTarget.charAt(0) !== '/') {
66279 logger(
66280 'We recommend using an absolute path for the rewrite target.',
66281 'Received a non-absolute rewrite target',
66282 rewriteTarget,
66283 'for URL',
66284 req.url
66285 );
66286 }
66287
66288 logger('Rewriting', req.method, req.url, 'to', rewriteTarget);
66289 req.url = rewriteTarget;
66290 return next();
66291 }
66292 }
66293
66294 var pathname = parsedUrl.pathname;
66295 if (pathname.lastIndexOf('.') > pathname.lastIndexOf('/') &&
66296 options.disableDotRule !== true) {
66297 logger(
66298 'Not rewriting',
66299 req.method,
66300 req.url,
66301 'because the path includes a dot (.) character.'
66302 );
66303 return next();
66304 }
66305
66306 rewriteTarget = options.index || '/index.html';
66307 logger('Rewriting', req.method, req.url, 'to', rewriteTarget);
66308 req.url = rewriteTarget;
66309 next();
66310 };
66311};
66312
66313function evaluateRewriteRule(parsedUrl, match, rule, req) {
66314 if (typeof rule === 'string') {
66315 return rule;
66316 } else if (typeof rule !== 'function') {
66317 throw new Error('Rewrite rule can only be of type string or function.');
66318 }
66319
66320 return rule({
66321 parsedUrl: parsedUrl,
66322 match: match,
66323 request: req
66324 });
66325}
66326
66327function acceptsHtml(header, options) {
66328 options.htmlAcceptHeaders = options.htmlAcceptHeaders || ['text/html', '*/*'];
66329 for (var i = 0; i < options.htmlAcceptHeaders.length; i++) {
66330 if (header.indexOf(options.htmlAcceptHeaders[i]) !== -1) {
66331 return true;
66332 }
66333 }
66334 return false;
66335}
66336
66337function getLogger(options) {
66338 if (options && options.logger) {
66339 return options.logger;
66340 } else if (options && options.verbose) {
66341 return console.log.bind(console);
66342 }
66343 return function(){};
66344}
66345}(lib));
66346
66347var history = lib.exports;
66348
66349function decodeURIMiddleware() {
66350 // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
66351 return function viteDecoreURIMiddleware(req, _, next) {
66352 // #2195
66353 req.url = decodeURI(req.url);
66354 // `sirv` middleware uses the req._parsedUrl values to find the file,
66355 // so decode it all together.
66356 // @ts-ignore
66357 const parsedUrl = req._parsedUrl;
66358 for (const key of Object.keys(parsedUrl)) {
66359 const val = parsedUrl[key];
66360 if (val)
66361 parsedUrl[key] = decodeURI(val);
66362 }
66363 next();
66364 };
66365}
66366
66367const logTime = createDebugger('vite:time');
66368function timeMiddleware(root) {
66369 // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
66370 return function viteTimeMiddleware(req, res, next) {
66371 const start = Date.now();
66372 const end = res.end;
66373 res.end = (...args) => {
66374 logTime(`${timeFrom(start)} ${prettifyUrl(req.url, root)}`);
66375 // @ts-ignore
66376 return end.call(res, ...args);
66377 };
66378 next();
66379 };
66380}
66381
66382class ModuleNode {
66383 constructor(url) {
66384 /**
66385 * Resolved file system path + query
66386 */
66387 this.id = null;
66388 this.file = null;
66389 this.importers = new Set();
66390 this.importedModules = new Set();
66391 this.acceptedHmrDeps = new Set();
66392 this.isSelfAccepting = false;
66393 this.transformResult = null;
66394 this.ssrTransformResult = null;
66395 this.ssrModule = null;
66396 this.lastHMRTimestamp = 0;
66397 this.url = url;
66398 this.type = isDirectCSSRequest(url) ? 'css' : 'js';
66399 }
66400}
66401function invalidateSSRModule(mod, seen) {
66402 if (seen.has(mod)) {
66403 return;
66404 }
66405 seen.add(mod);
66406 mod.ssrModule = null;
66407 mod.importers.forEach((importer) => invalidateSSRModule(importer, seen));
66408}
66409class ModuleGraph {
66410 constructor(container) {
66411 this.urlToModuleMap = new Map();
66412 this.idToModuleMap = new Map();
66413 // a single file may corresponds to multiple modules with different queries
66414 this.fileToModulesMap = new Map();
66415 this.safeModulesPath = new Set();
66416 this.container = container;
66417 }
66418 async getModuleByUrl(rawUrl) {
66419 const [url] = await this.resolveUrl(rawUrl);
66420 return this.urlToModuleMap.get(url);
66421 }
66422 getModuleById(id) {
66423 return this.idToModuleMap.get(removeTimestampQuery(id));
66424 }
66425 getModulesByFile(file) {
66426 return this.fileToModulesMap.get(file);
66427 }
66428 onFileChange(file) {
66429 const mods = this.getModulesByFile(file);
66430 if (mods) {
66431 const seen = new Set();
66432 mods.forEach((mod) => {
66433 this.invalidateModule(mod, seen);
66434 });
66435 }
66436 }
66437 invalidateModule(mod, seen = new Set()) {
66438 mod.transformResult = null;
66439 mod.ssrTransformResult = null;
66440 invalidateSSRModule(mod, seen);
66441 }
66442 invalidateAll() {
66443 const seen = new Set();
66444 this.idToModuleMap.forEach((mod) => {
66445 this.invalidateModule(mod, seen);
66446 });
66447 }
66448 /**
66449 * Update the module graph based on a module's updated imports information
66450 * If there are dependencies that no longer have any importers, they are
66451 * returned as a Set.
66452 */
66453 async updateModuleInfo(mod, importedModules, acceptedModules, isSelfAccepting) {
66454 mod.isSelfAccepting = isSelfAccepting;
66455 const prevImports = mod.importedModules;
66456 const nextImports = (mod.importedModules = new Set());
66457 let noLongerImported;
66458 // update import graph
66459 for (const imported of importedModules) {
66460 const dep = typeof imported === 'string'
66461 ? await this.ensureEntryFromUrl(imported)
66462 : imported;
66463 dep.importers.add(mod);
66464 nextImports.add(dep);
66465 }
66466 // remove the importer from deps that were imported but no longer are.
66467 prevImports.forEach((dep) => {
66468 if (!nextImports.has(dep)) {
66469 dep.importers.delete(mod);
66470 if (!dep.importers.size) {
66471 (noLongerImported || (noLongerImported = new Set())).add(dep);
66472 }
66473 }
66474 });
66475 // update accepted hmr deps
66476 const deps = (mod.acceptedHmrDeps = new Set());
66477 for (const accepted of acceptedModules) {
66478 const dep = typeof accepted === 'string'
66479 ? await this.ensureEntryFromUrl(accepted)
66480 : accepted;
66481 deps.add(dep);
66482 }
66483 return noLongerImported;
66484 }
66485 async ensureEntryFromUrl(rawUrl) {
66486 const [url, resolvedId] = await this.resolveUrl(rawUrl);
66487 let mod = this.urlToModuleMap.get(url);
66488 if (!mod) {
66489 mod = new ModuleNode(url);
66490 this.urlToModuleMap.set(url, mod);
66491 mod.id = resolvedId;
66492 this.idToModuleMap.set(resolvedId, mod);
66493 const file = (mod.file = cleanUrl(resolvedId));
66494 let fileMappedModules = this.fileToModulesMap.get(file);
66495 if (!fileMappedModules) {
66496 fileMappedModules = new Set();
66497 this.fileToModulesMap.set(file, fileMappedModules);
66498 }
66499 fileMappedModules.add(mod);
66500 }
66501 return mod;
66502 }
66503 // some deps, like a css file referenced via @import, don't have its own
66504 // url because they are inlined into the main css import. But they still
66505 // need to be represented in the module graph so that they can trigger
66506 // hmr in the importing css file.
66507 createFileOnlyEntry(file) {
66508 file = normalizePath$4(file);
66509 let fileMappedModules = this.fileToModulesMap.get(file);
66510 if (!fileMappedModules) {
66511 fileMappedModules = new Set();
66512 this.fileToModulesMap.set(file, fileMappedModules);
66513 }
66514 const url = `${FS_PREFIX}${file}`;
66515 for (const m of fileMappedModules) {
66516 if (m.url === url || m.id === file) {
66517 return m;
66518 }
66519 }
66520 const mod = new ModuleNode(url);
66521 mod.file = file;
66522 fileMappedModules.add(mod);
66523 return mod;
66524 }
66525 // for incoming urls, it is important to:
66526 // 1. remove the HMR timestamp query (?t=xxxx)
66527 // 2. resolve its extension so that urls with or without extension all map to
66528 // the same module
66529 async resolveUrl(url) {
66530 var _a;
66531 url = removeImportQuery(removeTimestampQuery(url));
66532 const resolvedId = ((_a = (await this.container.resolveId(url))) === null || _a === void 0 ? void 0 : _a.id) || url;
66533 const ext = path$A.extname(cleanUrl(resolvedId));
66534 const { pathname, search, hash } = require$$0$b.parse(url);
66535 if (ext && !pathname.endsWith(ext)) {
66536 url = pathname + ext + (search || '') + (hash || '');
66537 }
66538 return [url, resolvedId];
66539 }
66540}
66541
66542const debugHmr = createDebugger('vite:hmr');
66543const normalizedClientDir = normalizePath$4(CLIENT_DIR);
66544function getShortName(file, root) {
66545 return file.startsWith(root + '/') ? path__default.posix.relative(root, file) : file;
66546}
66547async function handleHMRUpdate(file, server) {
66548 const { ws, config, moduleGraph } = server;
66549 const shortFile = getShortName(file, config.root);
66550 const isConfig = file === config.configFile;
66551 const isConfigDependency = config.configFileDependencies.some((name) => file === path__default.resolve(name));
66552 const isEnv = config.inlineConfig.envFile !== false && file.endsWith('.env');
66553 if (isConfig || isConfigDependency || isEnv) {
66554 // auto restart server
66555 debugHmr(`[config change] ${source.dim(shortFile)}`);
66556 config.logger.info(source.green(`${path__default.relative(process.cwd(), file)} changed, restarting server...`), { clear: true, timestamp: true });
66557 await restartServer(server);
66558 return;
66559 }
66560 debugHmr(`[file change] ${source.dim(shortFile)}`);
66561 // (dev only) the client itself cannot be hot updated.
66562 if (file.startsWith(normalizedClientDir)) {
66563 ws.send({
66564 type: 'full-reload',
66565 path: '*'
66566 });
66567 return;
66568 }
66569 const mods = moduleGraph.getModulesByFile(file);
66570 // check if any plugin wants to perform custom HMR handling
66571 const timestamp = Date.now();
66572 const hmrContext = {
66573 file,
66574 timestamp,
66575 modules: mods ? [...mods] : [],
66576 read: () => readModifiedFile(file),
66577 server
66578 };
66579 for (const plugin of config.plugins) {
66580 if (plugin.handleHotUpdate) {
66581 const filteredModules = await plugin.handleHotUpdate(hmrContext);
66582 if (filteredModules) {
66583 hmrContext.modules = filteredModules;
66584 }
66585 }
66586 }
66587 if (!hmrContext.modules.length) {
66588 // html file cannot be hot updated
66589 if (file.endsWith('.html')) {
66590 config.logger.info(source.green(`page reload `) + source.dim(shortFile), {
66591 clear: true,
66592 timestamp: true
66593 });
66594 ws.send({
66595 type: 'full-reload',
66596 path: config.server.middlewareMode
66597 ? '*'
66598 : '/' + normalizePath$4(path__default.relative(config.root, file))
66599 });
66600 }
66601 else {
66602 // loaded but not in the module graph, probably not js
66603 debugHmr(`[no modules matched] ${source.dim(shortFile)}`);
66604 }
66605 return;
66606 }
66607 updateModules(shortFile, hmrContext.modules, timestamp, server);
66608}
66609function updateModules(file, modules, timestamp, { config, ws }) {
66610 const updates = [];
66611 const invalidatedModules = new Set();
66612 let needFullReload = false;
66613 for (const mod of modules) {
66614 invalidate(mod, timestamp, invalidatedModules);
66615 if (needFullReload) {
66616 continue;
66617 }
66618 const boundaries = new Set();
66619 const hasDeadEnd = propagateUpdate(mod, timestamp, boundaries);
66620 if (hasDeadEnd) {
66621 needFullReload = true;
66622 continue;
66623 }
66624 updates.push(...[...boundaries].map(({ boundary, acceptedVia }) => ({
66625 type: `${boundary.type}-update`,
66626 timestamp,
66627 path: boundary.url,
66628 acceptedPath: acceptedVia.url
66629 })));
66630 }
66631 if (needFullReload) {
66632 config.logger.info(source.green(`page reload `) + source.dim(file), {
66633 clear: true,
66634 timestamp: true
66635 });
66636 ws.send({
66637 type: 'full-reload'
66638 });
66639 }
66640 else {
66641 config.logger.info(updates
66642 .map(({ path }) => source.green(`hmr update `) + source.dim(path))
66643 .join('\n'), { clear: true, timestamp: true });
66644 ws.send({
66645 type: 'update',
66646 updates
66647 });
66648 }
66649}
66650async function handleFileAddUnlink(file, server, isUnlink = false) {
66651 var _a;
66652 const modules = [...((_a = server.moduleGraph.getModulesByFile(file)) !== null && _a !== void 0 ? _a : [])];
66653 if (isUnlink && file in server._globImporters) {
66654 delete server._globImporters[file];
66655 }
66656 else {
66657 for (const i in server._globImporters) {
66658 const { module, importGlobs } = server._globImporters[i];
66659 for (const { base, pattern } of importGlobs) {
66660 if (minimatch_1(file, pattern) || minimatch_1(path__default.relative(base, file), pattern)) {
66661 modules.push(module);
66662 // We use `onFileChange` to invalidate `module.file` so that subsequent `ssrLoadModule()`
66663 // calls get fresh glob import results with(out) the newly added(/removed) `file`.
66664 server.moduleGraph.onFileChange(module.file);
66665 break;
66666 }
66667 }
66668 }
66669 }
66670 if (modules.length > 0) {
66671 updateModules(getShortName(file, server.config.root), modules, Date.now(), server);
66672 }
66673}
66674function propagateUpdate(node, timestamp, boundaries, currentChain = [node]) {
66675 if (node.isSelfAccepting) {
66676 boundaries.add({
66677 boundary: node,
66678 acceptedVia: node
66679 });
66680 // additionally check for CSS importers, since a PostCSS plugin like
66681 // Tailwind JIT may register any file as a dependency to a CSS file.
66682 for (const importer of node.importers) {
66683 if (cssLangRE.test(importer.url) && !currentChain.includes(importer)) {
66684 propagateUpdate(importer, timestamp, boundaries, currentChain.concat(importer));
66685 }
66686 }
66687 return false;
66688 }
66689 if (!node.importers.size) {
66690 return true;
66691 }
66692 // #3716, #3913
66693 // For a non-CSS file, if all of its importers are CSS files (registered via
66694 // PostCSS plugins) it should be considered a dead end and force full reload.
66695 if (!cssLangRE.test(node.url) &&
66696 [...node.importers].every((i) => cssLangRE.test(i.url))) {
66697 return true;
66698 }
66699 for (const importer of node.importers) {
66700 const subChain = currentChain.concat(importer);
66701 if (importer.acceptedHmrDeps.has(node)) {
66702 boundaries.add({
66703 boundary: importer,
66704 acceptedVia: node
66705 });
66706 continue;
66707 }
66708 if (currentChain.includes(importer)) {
66709 // circular deps is considered dead end
66710 return true;
66711 }
66712 if (propagateUpdate(importer, timestamp, boundaries, subChain)) {
66713 return true;
66714 }
66715 }
66716 return false;
66717}
66718function invalidate(mod, timestamp, seen) {
66719 if (seen.has(mod)) {
66720 return;
66721 }
66722 seen.add(mod);
66723 mod.lastHMRTimestamp = timestamp;
66724 mod.transformResult = null;
66725 mod.ssrModule = null;
66726 mod.ssrTransformResult = null;
66727 mod.importers.forEach((importer) => {
66728 if (!importer.acceptedHmrDeps.has(mod)) {
66729 invalidate(importer, timestamp, seen);
66730 }
66731 });
66732}
66733function handlePrunedModules(mods, { ws }) {
66734 // update the disposed modules' hmr timestamp
66735 // since if it's re-imported, it should re-apply side effects
66736 // and without the timestamp the browser will not re-import it!
66737 const t = Date.now();
66738 mods.forEach((mod) => {
66739 mod.lastHMRTimestamp = t;
66740 debugHmr(`[dispose] ${source.dim(mod.file)}`);
66741 });
66742 ws.send({
66743 type: 'prune',
66744 paths: [...mods].map((m) => m.url)
66745 });
66746}
66747/**
66748 * Lex import.meta.hot.accept() for accepted deps.
66749 * Since hot.accept() can only accept string literals or array of string
66750 * literals, we don't really need a heavy @babel/parse call on the entire source.
66751 *
66752 * @returns selfAccepts
66753 */
66754function lexAcceptedHmrDeps(code, start, urls) {
66755 let state = 0 /* inCall */;
66756 // the state can only be 2 levels deep so no need for a stack
66757 let prevState = 0 /* inCall */;
66758 let currentDep = '';
66759 function addDep(index) {
66760 urls.add({
66761 url: currentDep,
66762 start: index - currentDep.length - 1,
66763 end: index + 1
66764 });
66765 currentDep = '';
66766 }
66767 for (let i = start; i < code.length; i++) {
66768 const char = code.charAt(i);
66769 switch (state) {
66770 case 0 /* inCall */:
66771 case 4 /* inArray */:
66772 if (char === `'`) {
66773 prevState = state;
66774 state = 1 /* inSingleQuoteString */;
66775 }
66776 else if (char === `"`) {
66777 prevState = state;
66778 state = 2 /* inDoubleQuoteString */;
66779 }
66780 else if (char === '`') {
66781 prevState = state;
66782 state = 3 /* inTemplateString */;
66783 }
66784 else if (/\s/.test(char)) {
66785 continue;
66786 }
66787 else {
66788 if (state === 0 /* inCall */) {
66789 if (char === `[`) {
66790 state = 4 /* inArray */;
66791 }
66792 else {
66793 // reaching here means the first arg is neither a string literal
66794 // nor an Array literal (direct callback) or there is no arg
66795 // in both case this indicates a self-accepting module
66796 return true; // done
66797 }
66798 }
66799 else if (state === 4 /* inArray */) {
66800 if (char === `]`) {
66801 return false; // done
66802 }
66803 else if (char === ',') {
66804 continue;
66805 }
66806 else {
66807 error$1(i);
66808 }
66809 }
66810 }
66811 break;
66812 case 1 /* inSingleQuoteString */:
66813 if (char === `'`) {
66814 addDep(i);
66815 if (prevState === 0 /* inCall */) {
66816 // accept('foo', ...)
66817 return false;
66818 }
66819 else {
66820 state = prevState;
66821 }
66822 }
66823 else {
66824 currentDep += char;
66825 }
66826 break;
66827 case 2 /* inDoubleQuoteString */:
66828 if (char === `"`) {
66829 addDep(i);
66830 if (prevState === 0 /* inCall */) {
66831 // accept('foo', ...)
66832 return false;
66833 }
66834 else {
66835 state = prevState;
66836 }
66837 }
66838 else {
66839 currentDep += char;
66840 }
66841 break;
66842 case 3 /* inTemplateString */:
66843 if (char === '`') {
66844 addDep(i);
66845 if (prevState === 0 /* inCall */) {
66846 // accept('foo', ...)
66847 return false;
66848 }
66849 else {
66850 state = prevState;
66851 }
66852 }
66853 else if (char === '$' && code.charAt(i + 1) === '{') {
66854 error$1(i);
66855 }
66856 else {
66857 currentDep += char;
66858 }
66859 break;
66860 default:
66861 throw new Error('unknown import.meta.hot lexer state');
66862 }
66863 }
66864 return false;
66865}
66866function error$1(pos) {
66867 const err = new Error(`import.meta.accept() can only accept string literals or an ` +
66868 `Array of string literals.`);
66869 err.pos = pos;
66870 throw err;
66871}
66872// vitejs/vite#610 when hot-reloading Vue files, we read immediately on file
66873// change event and sometimes this can be too early and get an empty buffer.
66874// Poll until the file's modified time has changed before reading again.
66875async function readModifiedFile(file) {
66876 const content = fs__default.readFileSync(file, 'utf-8');
66877 if (!content) {
66878 const mtime = fs__default.statSync(file).mtimeMs;
66879 await new Promise((r) => {
66880 let n = 0;
66881 const poll = async () => {
66882 n++;
66883 const newMtime = fs__default.statSync(file).mtimeMs;
66884 if (newMtime !== mtime || n > 10) {
66885 r(0);
66886 }
66887 else {
66888 setTimeout(poll, 10);
66889 }
66890 };
66891 setTimeout(poll, 10);
66892 });
66893 return fs__default.readFileSync(file, 'utf-8');
66894 }
66895 else {
66896 return content;
66897 }
66898}
66899async function restartServer(server) {
66900 // @ts-ignore
66901 global.__vite_start_time = Date.now();
66902 let newServer = null;
66903 try {
66904 newServer = await createServer(server.config.inlineConfig);
66905 }
66906 catch (err) {
66907 server.ws.send({
66908 type: 'error',
66909 err: prepareError(err)
66910 });
66911 return;
66912 }
66913 await server.close();
66914 for (const key in newServer) {
66915 if (key !== 'app') {
66916 // @ts-ignore
66917 server[key] = newServer[key];
66918 }
66919 }
66920 if (!server.config.server.middlewareMode) {
66921 await server.listen(undefined, true);
66922 }
66923 else {
66924 server.config.logger.info('server restarted.', { timestamp: true });
66925 }
66926}
66927
66928var isWsl$2 = {exports: {}};
66929
66930const fs$7 = fs__default;
66931
66932let isDocker$2;
66933
66934function hasDockerEnv() {
66935 try {
66936 fs$7.statSync('/.dockerenv');
66937 return true;
66938 } catch (_) {
66939 return false;
66940 }
66941}
66942
66943function hasDockerCGroup() {
66944 try {
66945 return fs$7.readFileSync('/proc/self/cgroup', 'utf8').includes('docker');
66946 } catch (_) {
66947 return false;
66948 }
66949}
66950
66951var isDocker_1 = () => {
66952 if (isDocker$2 === undefined) {
66953 isDocker$2 = hasDockerEnv() || hasDockerCGroup();
66954 }
66955
66956 return isDocker$2;
66957};
66958
66959const os$4 = require$$0__default$1;
66960const fs$6 = fs__default;
66961const isDocker$1 = isDocker_1;
66962
66963const isWsl$1 = () => {
66964 if (process.platform !== 'linux') {
66965 return false;
66966 }
66967
66968 if (os$4.release().toLowerCase().includes('microsoft')) {
66969 if (isDocker$1()) {
66970 return false;
66971 }
66972
66973 return true;
66974 }
66975
66976 try {
66977 return fs$6.readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft') ?
66978 !isDocker$1() : false;
66979 } catch (_) {
66980 return false;
66981 }
66982};
66983
66984if (process.env.__IS_WSL_TEST__) {
66985 isWsl$2.exports = isWsl$1;
66986} else {
66987 isWsl$2.exports = isWsl$1();
66988}
66989
66990var defineLazyProp = (object, propertyName, fn) => {
66991 const define = value => Object.defineProperty(object, propertyName, {value, enumerable: true, writable: true});
66992
66993 Object.defineProperty(object, propertyName, {
66994 configurable: true,
66995 enumerable: true,
66996 get() {
66997 const result = fn();
66998 define(result);
66999 return result;
67000 },
67001 set(value) {
67002 define(value);
67003 }
67004 });
67005
67006 return object;
67007};
67008
67009const path$9 = path__default;
67010const childProcess$3 = require$$1__default$3;
67011const {promises: fs$5, constants: fsConstants} = fs__default;
67012const isWsl = isWsl$2.exports;
67013const isDocker = isDocker_1;
67014const defineLazyProperty = defineLazyProp;
67015
67016// Path to included `xdg-open`.
67017const localXdgOpenPath = path$9.join(__dirname, 'xdg-open');
67018
67019const {platform, arch} = process;
67020
67021/**
67022Get the mount point for fixed drives in WSL.
67023
67024@inner
67025@returns {string} The mount point.
67026*/
67027const getWslDrivesMountPoint = (() => {
67028 // Default value for "root" param
67029 // according to https://docs.microsoft.com/en-us/windows/wsl/wsl-config
67030 const defaultMountPoint = '/mnt/';
67031
67032 let mountPoint;
67033
67034 return async function () {
67035 if (mountPoint) {
67036 // Return memoized mount point value
67037 return mountPoint;
67038 }
67039
67040 const configFilePath = '/etc/wsl.conf';
67041
67042 let isConfigFileExists = false;
67043 try {
67044 await fs$5.access(configFilePath, fsConstants.F_OK);
67045 isConfigFileExists = true;
67046 } catch {}
67047
67048 if (!isConfigFileExists) {
67049 return defaultMountPoint;
67050 }
67051
67052 const configContent = await fs$5.readFile(configFilePath, {encoding: 'utf8'});
67053 const configMountPoint = /(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(configContent);
67054
67055 if (!configMountPoint) {
67056 return defaultMountPoint;
67057 }
67058
67059 mountPoint = configMountPoint.groups.mountPoint.trim();
67060 mountPoint = mountPoint.endsWith('/') ? mountPoint : `${mountPoint}/`;
67061
67062 return mountPoint;
67063 };
67064})();
67065
67066const pTryEach = async (array, mapper) => {
67067 let latestError;
67068
67069 for (const item of array) {
67070 try {
67071 return await mapper(item); // eslint-disable-line no-await-in-loop
67072 } catch (error) {
67073 latestError = error;
67074 }
67075 }
67076
67077 throw latestError;
67078};
67079
67080const open = async (target, options) => {
67081 if (typeof target !== 'string') {
67082 throw new TypeError('Expected a `target`');
67083 }
67084
67085 options = {
67086 wait: false,
67087 background: false,
67088 newInstance: false,
67089 allowNonzeroExitCode: false,
67090 ...options
67091 };
67092
67093 if (Array.isArray(options.app)) {
67094 return pTryEach(options.app, singleApp => open(target, {
67095 ...options,
67096 app: singleApp
67097 }));
67098 }
67099
67100 let {name: app, arguments: appArguments = []} = options.app || {};
67101 appArguments = [...appArguments];
67102
67103 if (Array.isArray(app)) {
67104 return pTryEach(app, appName => open(target, {
67105 ...options,
67106 app: {
67107 name: appName,
67108 arguments: appArguments
67109 }
67110 }));
67111 }
67112
67113 let command;
67114 const cliArguments = [];
67115 const childProcessOptions = {};
67116
67117 if (platform === 'darwin') {
67118 command = 'open';
67119
67120 if (options.wait) {
67121 cliArguments.push('--wait-apps');
67122 }
67123
67124 if (options.background) {
67125 cliArguments.push('--background');
67126 }
67127
67128 if (options.newInstance) {
67129 cliArguments.push('--new');
67130 }
67131
67132 if (app) {
67133 cliArguments.push('-a', app);
67134 }
67135 } else if (platform === 'win32' || (isWsl && !isDocker())) {
67136 const mountPoint = await getWslDrivesMountPoint();
67137
67138 command = isWsl ?
67139 `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe` :
67140 `${process.env.SYSTEMROOT}\\System32\\WindowsPowerShell\\v1.0\\powershell`;
67141
67142 cliArguments.push(
67143 '-NoProfile',
67144 '-NonInteractive',
67145 '–ExecutionPolicy',
67146 'Bypass',
67147 '-EncodedCommand'
67148 );
67149
67150 if (!isWsl) {
67151 childProcessOptions.windowsVerbatimArguments = true;
67152 }
67153
67154 const encodedArguments = ['Start'];
67155
67156 if (options.wait) {
67157 encodedArguments.push('-Wait');
67158 }
67159
67160 if (app) {
67161 // Double quote with double quotes to ensure the inner quotes are passed through.
67162 // Inner quotes are delimited for PowerShell interpretation with backticks.
67163 encodedArguments.push(`"\`"${app}\`""`, '-ArgumentList');
67164 appArguments.unshift(target);
67165 } else {
67166 encodedArguments.push(`"${target}"`);
67167 }
67168
67169 if (appArguments.length > 0) {
67170 appArguments = appArguments.map(arg => `"\`"${arg}\`""`);
67171 encodedArguments.push(appArguments.join(','));
67172 }
67173
67174 // Using Base64-encoded command, accepted by PowerShell, to allow special characters.
67175 target = Buffer.from(encodedArguments.join(' '), 'utf16le').toString('base64');
67176 } else {
67177 if (app) {
67178 command = app;
67179 } else {
67180 // When bundled by Webpack, there's no actual package file path and no local `xdg-open`.
67181 const isBundled = !__dirname || __dirname === '/';
67182
67183 // Check if local `xdg-open` exists and is executable.
67184 let exeLocalXdgOpen = false;
67185 try {
67186 await fs$5.access(localXdgOpenPath, fsConstants.X_OK);
67187 exeLocalXdgOpen = true;
67188 } catch {}
67189
67190 const useSystemXdgOpen = process.versions.electron ||
67191 platform === 'android' || isBundled || !exeLocalXdgOpen;
67192 command = useSystemXdgOpen ? 'xdg-open' : localXdgOpenPath;
67193 }
67194
67195 if (appArguments.length > 0) {
67196 cliArguments.push(...appArguments);
67197 }
67198
67199 if (!options.wait) {
67200 // `xdg-open` will block the process unless stdio is ignored
67201 // and it's detached from the parent even if it's unref'd.
67202 childProcessOptions.stdio = 'ignore';
67203 childProcessOptions.detached = true;
67204 }
67205 }
67206
67207 cliArguments.push(target);
67208
67209 if (platform === 'darwin' && appArguments.length > 0) {
67210 cliArguments.push('--args', ...appArguments);
67211 }
67212
67213 const subprocess = childProcess$3.spawn(command, cliArguments, childProcessOptions);
67214
67215 if (options.wait) {
67216 return new Promise((resolve, reject) => {
67217 subprocess.once('error', reject);
67218
67219 subprocess.once('close', exitCode => {
67220 if (options.allowNonzeroExitCode && exitCode > 0) {
67221 reject(new Error(`Exited with code ${exitCode}`));
67222 return;
67223 }
67224
67225 resolve(subprocess);
67226 });
67227 });
67228 }
67229
67230 subprocess.unref();
67231
67232 return subprocess;
67233};
67234
67235function detectArchBinary(binary) {
67236 if (typeof binary === 'string' || Array.isArray(binary)) {
67237 return binary;
67238 }
67239
67240 const {[arch]: archBinary} = binary;
67241
67242 if (!archBinary) {
67243 throw new Error(`${arch} is not supported`);
67244 }
67245
67246 return archBinary;
67247}
67248
67249function detectPlatformBinary({[platform]: platformBinary}, {wsl}) {
67250 if (wsl && isWsl) {
67251 return detectArchBinary(wsl);
67252 }
67253
67254 if (!platformBinary) {
67255 throw new Error(`${platform} is not supported`);
67256 }
67257
67258 return detectArchBinary(platformBinary);
67259}
67260
67261const apps = {};
67262
67263defineLazyProperty(apps, 'chrome', () => detectPlatformBinary({
67264 darwin: 'google chrome',
67265 win32: 'chrome',
67266 linux: ['google-chrome', 'google-chrome-stable']
67267}, {
67268 wsl: {
67269 ia32: '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe',
67270 x64: ['/mnt/c/Program Files/Google/Chrome/Application/chrome.exe', '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe']
67271 }
67272}));
67273
67274defineLazyProperty(apps, 'firefox', () => detectPlatformBinary({
67275 darwin: 'firefox',
67276 win32: 'C:\\Program Files\\Mozilla Firefox\\firefox.exe',
67277 linux: 'firefox'
67278}, {
67279 wsl: '/mnt/c/Program Files/Mozilla Firefox/firefox.exe'
67280}));
67281
67282defineLazyProperty(apps, 'edge', () => detectPlatformBinary({
67283 darwin: 'microsoft edge',
67284 win32: 'msedge',
67285 linux: 'microsoft-edge'
67286}, {
67287 wsl: '/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe'
67288}));
67289
67290open.apps = apps;
67291
67292var open_1 = open;
67293
67294var execa$2 = {exports: {}};
67295
67296var crossSpawn$1 = {exports: {}};
67297
67298var windows$1 = isexe$3;
67299isexe$3.sync = sync$2;
67300
67301var fs$4 = fs__default;
67302
67303function checkPathExt (path, options) {
67304 var pathext = options.pathExt !== undefined ?
67305 options.pathExt : process.env.PATHEXT;
67306
67307 if (!pathext) {
67308 return true
67309 }
67310
67311 pathext = pathext.split(';');
67312 if (pathext.indexOf('') !== -1) {
67313 return true
67314 }
67315 for (var i = 0; i < pathext.length; i++) {
67316 var p = pathext[i].toLowerCase();
67317 if (p && path.substr(-p.length).toLowerCase() === p) {
67318 return true
67319 }
67320 }
67321 return false
67322}
67323
67324function checkStat$1 (stat, path, options) {
67325 if (!stat.isSymbolicLink() && !stat.isFile()) {
67326 return false
67327 }
67328 return checkPathExt(path, options)
67329}
67330
67331function isexe$3 (path, options, cb) {
67332 fs$4.stat(path, function (er, stat) {
67333 cb(er, er ? false : checkStat$1(stat, path, options));
67334 });
67335}
67336
67337function sync$2 (path, options) {
67338 return checkStat$1(fs$4.statSync(path), path, options)
67339}
67340
67341var mode = isexe$2;
67342isexe$2.sync = sync$1;
67343
67344var fs$3 = fs__default;
67345
67346function isexe$2 (path, options, cb) {
67347 fs$3.stat(path, function (er, stat) {
67348 cb(er, er ? false : checkStat(stat, options));
67349 });
67350}
67351
67352function sync$1 (path, options) {
67353 return checkStat(fs$3.statSync(path), options)
67354}
67355
67356function checkStat (stat, options) {
67357 return stat.isFile() && checkMode(stat, options)
67358}
67359
67360function checkMode (stat, options) {
67361 var mod = stat.mode;
67362 var uid = stat.uid;
67363 var gid = stat.gid;
67364
67365 var myUid = options.uid !== undefined ?
67366 options.uid : process.getuid && process.getuid();
67367 var myGid = options.gid !== undefined ?
67368 options.gid : process.getgid && process.getgid();
67369
67370 var u = parseInt('100', 8);
67371 var g = parseInt('010', 8);
67372 var o = parseInt('001', 8);
67373 var ug = u | g;
67374
67375 var ret = (mod & o) ||
67376 (mod & g) && gid === myGid ||
67377 (mod & u) && uid === myUid ||
67378 (mod & ug) && myUid === 0;
67379
67380 return ret
67381}
67382
67383var core$1;
67384if (process.platform === 'win32' || commonjsGlobal.TESTING_WINDOWS) {
67385 core$1 = windows$1;
67386} else {
67387 core$1 = mode;
67388}
67389
67390var isexe_1 = isexe$1;
67391isexe$1.sync = sync;
67392
67393function isexe$1 (path, options, cb) {
67394 if (typeof options === 'function') {
67395 cb = options;
67396 options = {};
67397 }
67398
67399 if (!cb) {
67400 if (typeof Promise !== 'function') {
67401 throw new TypeError('callback not provided')
67402 }
67403
67404 return new Promise(function (resolve, reject) {
67405 isexe$1(path, options || {}, function (er, is) {
67406 if (er) {
67407 reject(er);
67408 } else {
67409 resolve(is);
67410 }
67411 });
67412 })
67413 }
67414
67415 core$1(path, options || {}, function (er, is) {
67416 // ignore EACCES because that just means we aren't allowed to run it
67417 if (er) {
67418 if (er.code === 'EACCES' || options && options.ignoreErrors) {
67419 er = null;
67420 is = false;
67421 }
67422 }
67423 cb(er, is);
67424 });
67425}
67426
67427function sync (path, options) {
67428 // my kingdom for a filtered catch
67429 try {
67430 return core$1.sync(path, options || {})
67431 } catch (er) {
67432 if (options && options.ignoreErrors || er.code === 'EACCES') {
67433 return false
67434 } else {
67435 throw er
67436 }
67437 }
67438}
67439
67440const isWindows = process.platform === 'win32' ||
67441 process.env.OSTYPE === 'cygwin' ||
67442 process.env.OSTYPE === 'msys';
67443
67444const path$8 = path__default;
67445const COLON = isWindows ? ';' : ':';
67446const isexe = isexe_1;
67447
67448const getNotFoundError = (cmd) =>
67449 Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' });
67450
67451const getPathInfo = (cmd, opt) => {
67452 const colon = opt.colon || COLON;
67453
67454 // If it has a slash, then we don't bother searching the pathenv.
67455 // just check the file itself, and that's it.
67456 const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? ['']
67457 : (
67458 [
67459 // windows always checks the cwd first
67460 ...(isWindows ? [process.cwd()] : []),
67461 ...(opt.path || process.env.PATH ||
67462 /* istanbul ignore next: very unusual */ '').split(colon),
67463 ]
67464 );
67465 const pathExtExe = isWindows
67466 ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM'
67467 : '';
67468 const pathExt = isWindows ? pathExtExe.split(colon) : [''];
67469
67470 if (isWindows) {
67471 if (cmd.indexOf('.') !== -1 && pathExt[0] !== '')
67472 pathExt.unshift('');
67473 }
67474
67475 return {
67476 pathEnv,
67477 pathExt,
67478 pathExtExe,
67479 }
67480};
67481
67482const which$1 = (cmd, opt, cb) => {
67483 if (typeof opt === 'function') {
67484 cb = opt;
67485 opt = {};
67486 }
67487 if (!opt)
67488 opt = {};
67489
67490 const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
67491 const found = [];
67492
67493 const step = i => new Promise((resolve, reject) => {
67494 if (i === pathEnv.length)
67495 return opt.all && found.length ? resolve(found)
67496 : reject(getNotFoundError(cmd))
67497
67498 const ppRaw = pathEnv[i];
67499 const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
67500
67501 const pCmd = path$8.join(pathPart, cmd);
67502 const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
67503 : pCmd;
67504
67505 resolve(subStep(p, i, 0));
67506 });
67507
67508 const subStep = (p, i, ii) => new Promise((resolve, reject) => {
67509 if (ii === pathExt.length)
67510 return resolve(step(i + 1))
67511 const ext = pathExt[ii];
67512 isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
67513 if (!er && is) {
67514 if (opt.all)
67515 found.push(p + ext);
67516 else
67517 return resolve(p + ext)
67518 }
67519 return resolve(subStep(p, i, ii + 1))
67520 });
67521 });
67522
67523 return cb ? step(0).then(res => cb(null, res), cb) : step(0)
67524};
67525
67526const whichSync = (cmd, opt) => {
67527 opt = opt || {};
67528
67529 const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
67530 const found = [];
67531
67532 for (let i = 0; i < pathEnv.length; i ++) {
67533 const ppRaw = pathEnv[i];
67534 const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
67535
67536 const pCmd = path$8.join(pathPart, cmd);
67537 const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
67538 : pCmd;
67539
67540 for (let j = 0; j < pathExt.length; j ++) {
67541 const cur = p + pathExt[j];
67542 try {
67543 const is = isexe.sync(cur, { pathExt: pathExtExe });
67544 if (is) {
67545 if (opt.all)
67546 found.push(cur);
67547 else
67548 return cur
67549 }
67550 } catch (ex) {}
67551 }
67552 }
67553
67554 if (opt.all && found.length)
67555 return found
67556
67557 if (opt.nothrow)
67558 return null
67559
67560 throw getNotFoundError(cmd)
67561};
67562
67563var which_1 = which$1;
67564which$1.sync = whichSync;
67565
67566var pathKey$3 = {exports: {}};
67567
67568const pathKey$2 = (options = {}) => {
67569 const environment = options.env || process.env;
67570 const platform = options.platform || process.platform;
67571
67572 if (platform !== 'win32') {
67573 return 'PATH';
67574 }
67575
67576 return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path';
67577};
67578
67579pathKey$3.exports = pathKey$2;
67580// TODO: Remove this for the next major release
67581pathKey$3.exports.default = pathKey$2;
67582
67583const path$7 = path__default;
67584const which = which_1;
67585const getPathKey = pathKey$3.exports;
67586
67587function resolveCommandAttempt(parsed, withoutPathExt) {
67588 const env = parsed.options.env || process.env;
67589 const cwd = process.cwd();
67590 const hasCustomCwd = parsed.options.cwd != null;
67591 // Worker threads do not have process.chdir()
67592 const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled;
67593
67594 // If a custom `cwd` was specified, we need to change the process cwd
67595 // because `which` will do stat calls but does not support a custom cwd
67596 if (shouldSwitchCwd) {
67597 try {
67598 process.chdir(parsed.options.cwd);
67599 } catch (err) {
67600 /* Empty */
67601 }
67602 }
67603
67604 let resolved;
67605
67606 try {
67607 resolved = which.sync(parsed.command, {
67608 path: env[getPathKey({ env })],
67609 pathExt: withoutPathExt ? path$7.delimiter : undefined,
67610 });
67611 } catch (e) {
67612 /* Empty */
67613 } finally {
67614 if (shouldSwitchCwd) {
67615 process.chdir(cwd);
67616 }
67617 }
67618
67619 // If we successfully resolved, ensure that an absolute path is returned
67620 // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it
67621 if (resolved) {
67622 resolved = path$7.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved);
67623 }
67624
67625 return resolved;
67626}
67627
67628function resolveCommand$1(parsed) {
67629 return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
67630}
67631
67632var resolveCommand_1 = resolveCommand$1;
67633
67634var _escape = {};
67635
67636// See http://www.robvanderwoude.com/escapechars.php
67637const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
67638
67639function escapeCommand(arg) {
67640 // Escape meta chars
67641 arg = arg.replace(metaCharsRegExp, '^$1');
67642
67643 return arg;
67644}
67645
67646function escapeArgument(arg, doubleEscapeMetaChars) {
67647 // Convert to string
67648 arg = `${arg}`;
67649
67650 // Algorithm below is based on https://qntm.org/cmd
67651
67652 // Sequence of backslashes followed by a double quote:
67653 // double up all the backslashes and escape the double quote
67654 arg = arg.replace(/(\\*)"/g, '$1$1\\"');
67655
67656 // Sequence of backslashes followed by the end of the string
67657 // (which will become a double quote later):
67658 // double up all the backslashes
67659 arg = arg.replace(/(\\*)$/, '$1$1');
67660
67661 // All other backslashes occur literally
67662
67663 // Quote the whole thing:
67664 arg = `"${arg}"`;
67665
67666 // Escape meta chars
67667 arg = arg.replace(metaCharsRegExp, '^$1');
67668
67669 // Double escape meta chars if necessary
67670 if (doubleEscapeMetaChars) {
67671 arg = arg.replace(metaCharsRegExp, '^$1');
67672 }
67673
67674 return arg;
67675}
67676
67677_escape.command = escapeCommand;
67678_escape.argument = escapeArgument;
67679
67680var shebangRegex$1 = /^#!(.*)/;
67681
67682const shebangRegex = shebangRegex$1;
67683
67684var shebangCommand$1 = (string = '') => {
67685 const match = string.match(shebangRegex);
67686
67687 if (!match) {
67688 return null;
67689 }
67690
67691 const [path, argument] = match[0].replace(/#! ?/, '').split(' ');
67692 const binary = path.split('/').pop();
67693
67694 if (binary === 'env') {
67695 return argument;
67696 }
67697
67698 return argument ? `${binary} ${argument}` : binary;
67699};
67700
67701const fs$2 = fs__default;
67702const shebangCommand = shebangCommand$1;
67703
67704function readShebang$1(command) {
67705 // Read the first 150 bytes from the file
67706 const size = 150;
67707 const buffer = Buffer.alloc(size);
67708
67709 let fd;
67710
67711 try {
67712 fd = fs$2.openSync(command, 'r');
67713 fs$2.readSync(fd, buffer, 0, size, 0);
67714 fs$2.closeSync(fd);
67715 } catch (e) { /* Empty */ }
67716
67717 // Attempt to extract shebang (null is returned if not a shebang)
67718 return shebangCommand(buffer.toString());
67719}
67720
67721var readShebang_1 = readShebang$1;
67722
67723const path$6 = path__default;
67724const resolveCommand = resolveCommand_1;
67725const escape = _escape;
67726const readShebang = readShebang_1;
67727
67728const isWin$2 = process.platform === 'win32';
67729const isExecutableRegExp = /\.(?:com|exe)$/i;
67730const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
67731
67732function detectShebang(parsed) {
67733 parsed.file = resolveCommand(parsed);
67734
67735 const shebang = parsed.file && readShebang(parsed.file);
67736
67737 if (shebang) {
67738 parsed.args.unshift(parsed.file);
67739 parsed.command = shebang;
67740
67741 return resolveCommand(parsed);
67742 }
67743
67744 return parsed.file;
67745}
67746
67747function parseNonShell(parsed) {
67748 if (!isWin$2) {
67749 return parsed;
67750 }
67751
67752 // Detect & add support for shebangs
67753 const commandFile = detectShebang(parsed);
67754
67755 // We don't need a shell if the command filename is an executable
67756 const needsShell = !isExecutableRegExp.test(commandFile);
67757
67758 // If a shell is required, use cmd.exe and take care of escaping everything correctly
67759 // Note that `forceShell` is an hidden option used only in tests
67760 if (parsed.options.forceShell || needsShell) {
67761 // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/`
67762 // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument
67763 // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called,
67764 // we need to double escape them
67765 const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
67766
67767 // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar)
67768 // This is necessary otherwise it will always fail with ENOENT in those cases
67769 parsed.command = path$6.normalize(parsed.command);
67770
67771 // Escape command & arguments
67772 parsed.command = escape.command(parsed.command);
67773 parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));
67774
67775 const shellCommand = [parsed.command].concat(parsed.args).join(' ');
67776
67777 parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`];
67778 parsed.command = process.env.comspec || 'cmd.exe';
67779 parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped
67780 }
67781
67782 return parsed;
67783}
67784
67785function parse$3(command, args, options) {
67786 // Normalize arguments, similar to nodejs
67787 if (args && !Array.isArray(args)) {
67788 options = args;
67789 args = null;
67790 }
67791
67792 args = args ? args.slice(0) : []; // Clone array to avoid changing the original
67793 options = Object.assign({}, options); // Clone object to avoid changing the original
67794
67795 // Build our parsed object
67796 const parsed = {
67797 command,
67798 args,
67799 options,
67800 file: undefined,
67801 original: {
67802 command,
67803 args,
67804 },
67805 };
67806
67807 // Delegate further parsing to shell or non-shell
67808 return options.shell ? parsed : parseNonShell(parsed);
67809}
67810
67811var parse_1 = parse$3;
67812
67813const isWin$1 = process.platform === 'win32';
67814
67815function notFoundError(original, syscall) {
67816 return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {
67817 code: 'ENOENT',
67818 errno: 'ENOENT',
67819 syscall: `${syscall} ${original.command}`,
67820 path: original.command,
67821 spawnargs: original.args,
67822 });
67823}
67824
67825function hookChildProcess(cp, parsed) {
67826 if (!isWin$1) {
67827 return;
67828 }
67829
67830 const originalEmit = cp.emit;
67831
67832 cp.emit = function (name, arg1) {
67833 // If emitting "exit" event and exit code is 1, we need to check if
67834 // the command exists and emit an "error" instead
67835 // See https://github.com/IndigoUnited/node-cross-spawn/issues/16
67836 if (name === 'exit') {
67837 const err = verifyENOENT(arg1, parsed);
67838
67839 if (err) {
67840 return originalEmit.call(cp, 'error', err);
67841 }
67842 }
67843
67844 return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params
67845 };
67846}
67847
67848function verifyENOENT(status, parsed) {
67849 if (isWin$1 && status === 1 && !parsed.file) {
67850 return notFoundError(parsed.original, 'spawn');
67851 }
67852
67853 return null;
67854}
67855
67856function verifyENOENTSync(status, parsed) {
67857 if (isWin$1 && status === 1 && !parsed.file) {
67858 return notFoundError(parsed.original, 'spawnSync');
67859 }
67860
67861 return null;
67862}
67863
67864var enoent$1 = {
67865 hookChildProcess,
67866 verifyENOENT,
67867 verifyENOENTSync,
67868 notFoundError,
67869};
67870
67871const cp = require$$1__default$3;
67872const parse$2 = parse_1;
67873const enoent = enoent$1;
67874
67875function spawn(command, args, options) {
67876 // Parse the arguments
67877 const parsed = parse$2(command, args, options);
67878
67879 // Spawn the child process
67880 const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
67881
67882 // Hook into child process "exit" event to emit an error if the command
67883 // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16
67884 enoent.hookChildProcess(spawned, parsed);
67885
67886 return spawned;
67887}
67888
67889function spawnSync(command, args, options) {
67890 // Parse the arguments
67891 const parsed = parse$2(command, args, options);
67892
67893 // Spawn the child process
67894 const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
67895
67896 // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16
67897 result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
67898
67899 return result;
67900}
67901
67902crossSpawn$1.exports = spawn;
67903crossSpawn$1.exports.spawn = spawn;
67904crossSpawn$1.exports.sync = spawnSync;
67905
67906crossSpawn$1.exports._parse = parse$2;
67907crossSpawn$1.exports._enoent = enoent;
67908
67909var stripFinalNewline$1 = input => {
67910 const LF = typeof input === 'string' ? '\n' : '\n'.charCodeAt();
67911 const CR = typeof input === 'string' ? '\r' : '\r'.charCodeAt();
67912
67913 if (input[input.length - 1] === LF) {
67914 input = input.slice(0, input.length - 1);
67915 }
67916
67917 if (input[input.length - 1] === CR) {
67918 input = input.slice(0, input.length - 1);
67919 }
67920
67921 return input;
67922};
67923
67924var npmRunPath$1 = {exports: {}};
67925
67926var pathKey$1 = {exports: {}};
67927
67928const pathKey = (options = {}) => {
67929 const environment = options.env || process.env;
67930 const platform = options.platform || process.platform;
67931
67932 if (platform !== 'win32') {
67933 return 'PATH';
67934 }
67935
67936 return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path';
67937};
67938
67939pathKey$1.exports = pathKey;
67940// TODO: Remove this for the next major release
67941pathKey$1.exports.default = pathKey;
67942
67943(function (module) {
67944const path = path__default;
67945const pathKey = pathKey$1.exports;
67946
67947const npmRunPath = options => {
67948 options = {
67949 cwd: process.cwd(),
67950 path: process.env[pathKey()],
67951 execPath: process.execPath,
67952 ...options
67953 };
67954
67955 let previous;
67956 let cwdPath = path.resolve(options.cwd);
67957 const result = [];
67958
67959 while (previous !== cwdPath) {
67960 result.push(path.join(cwdPath, 'node_modules/.bin'));
67961 previous = cwdPath;
67962 cwdPath = path.resolve(cwdPath, '..');
67963 }
67964
67965 // Ensure the running `node` binary is used
67966 const execPathDir = path.resolve(options.cwd, options.execPath, '..');
67967 result.push(execPathDir);
67968
67969 return result.concat(options.path).join(path.delimiter);
67970};
67971
67972module.exports = npmRunPath;
67973// TODO: Remove this for the next major release
67974module.exports.default = npmRunPath;
67975
67976module.exports.env = options => {
67977 options = {
67978 env: process.env,
67979 ...options
67980 };
67981
67982 const env = {...options.env};
67983 const path = pathKey({env});
67984
67985 options.path = env[path];
67986 env[path] = module.exports(options);
67987
67988 return env;
67989};
67990}(npmRunPath$1));
67991
67992var onetime$2 = {exports: {}};
67993
67994var mimicFn$2 = {exports: {}};
67995
67996const mimicFn$1 = (to, from) => {
67997 for (const prop of Reflect.ownKeys(from)) {
67998 Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop));
67999 }
68000
68001 return to;
68002};
68003
68004mimicFn$2.exports = mimicFn$1;
68005// TODO: Remove this for the next major release
68006mimicFn$2.exports.default = mimicFn$1;
68007
68008const mimicFn = mimicFn$2.exports;
68009
68010const calledFunctions = new WeakMap();
68011
68012const onetime$1 = (function_, options = {}) => {
68013 if (typeof function_ !== 'function') {
68014 throw new TypeError('Expected a function');
68015 }
68016
68017 let returnValue;
68018 let callCount = 0;
68019 const functionName = function_.displayName || function_.name || '<anonymous>';
68020
68021 const onetime = function (...arguments_) {
68022 calledFunctions.set(onetime, ++callCount);
68023
68024 if (callCount === 1) {
68025 returnValue = function_.apply(this, arguments_);
68026 function_ = null;
68027 } else if (options.throw === true) {
68028 throw new Error(`Function \`${functionName}\` can only be called once`);
68029 }
68030
68031 return returnValue;
68032 };
68033
68034 mimicFn(onetime, function_);
68035 calledFunctions.set(onetime, callCount);
68036
68037 return onetime;
68038};
68039
68040onetime$2.exports = onetime$1;
68041// TODO: Remove this for the next major release
68042onetime$2.exports.default = onetime$1;
68043
68044onetime$2.exports.callCount = function_ => {
68045 if (!calledFunctions.has(function_)) {
68046 throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`);
68047 }
68048
68049 return calledFunctions.get(function_);
68050};
68051
68052var main$2 = {};
68053
68054var signals$2 = {};
68055
68056var core = {};
68057
68058Object.defineProperty(core,"__esModule",{value:true});core.SIGNALS=void 0;
68059
68060const SIGNALS=[
68061{
68062name:"SIGHUP",
68063number:1,
68064action:"terminate",
68065description:"Terminal closed",
68066standard:"posix"},
68067
68068{
68069name:"SIGINT",
68070number:2,
68071action:"terminate",
68072description:"User interruption with CTRL-C",
68073standard:"ansi"},
68074
68075{
68076name:"SIGQUIT",
68077number:3,
68078action:"core",
68079description:"User interruption with CTRL-\\",
68080standard:"posix"},
68081
68082{
68083name:"SIGILL",
68084number:4,
68085action:"core",
68086description:"Invalid machine instruction",
68087standard:"ansi"},
68088
68089{
68090name:"SIGTRAP",
68091number:5,
68092action:"core",
68093description:"Debugger breakpoint",
68094standard:"posix"},
68095
68096{
68097name:"SIGABRT",
68098number:6,
68099action:"core",
68100description:"Aborted",
68101standard:"ansi"},
68102
68103{
68104name:"SIGIOT",
68105number:6,
68106action:"core",
68107description:"Aborted",
68108standard:"bsd"},
68109
68110{
68111name:"SIGBUS",
68112number:7,
68113action:"core",
68114description:
68115"Bus error due to misaligned, non-existing address or paging error",
68116standard:"bsd"},
68117
68118{
68119name:"SIGEMT",
68120number:7,
68121action:"terminate",
68122description:"Command should be emulated but is not implemented",
68123standard:"other"},
68124
68125{
68126name:"SIGFPE",
68127number:8,
68128action:"core",
68129description:"Floating point arithmetic error",
68130standard:"ansi"},
68131
68132{
68133name:"SIGKILL",
68134number:9,
68135action:"terminate",
68136description:"Forced termination",
68137standard:"posix",
68138forced:true},
68139
68140{
68141name:"SIGUSR1",
68142number:10,
68143action:"terminate",
68144description:"Application-specific signal",
68145standard:"posix"},
68146
68147{
68148name:"SIGSEGV",
68149number:11,
68150action:"core",
68151description:"Segmentation fault",
68152standard:"ansi"},
68153
68154{
68155name:"SIGUSR2",
68156number:12,
68157action:"terminate",
68158description:"Application-specific signal",
68159standard:"posix"},
68160
68161{
68162name:"SIGPIPE",
68163number:13,
68164action:"terminate",
68165description:"Broken pipe or socket",
68166standard:"posix"},
68167
68168{
68169name:"SIGALRM",
68170number:14,
68171action:"terminate",
68172description:"Timeout or timer",
68173standard:"posix"},
68174
68175{
68176name:"SIGTERM",
68177number:15,
68178action:"terminate",
68179description:"Termination",
68180standard:"ansi"},
68181
68182{
68183name:"SIGSTKFLT",
68184number:16,
68185action:"terminate",
68186description:"Stack is empty or overflowed",
68187standard:"other"},
68188
68189{
68190name:"SIGCHLD",
68191number:17,
68192action:"ignore",
68193description:"Child process terminated, paused or unpaused",
68194standard:"posix"},
68195
68196{
68197name:"SIGCLD",
68198number:17,
68199action:"ignore",
68200description:"Child process terminated, paused or unpaused",
68201standard:"other"},
68202
68203{
68204name:"SIGCONT",
68205number:18,
68206action:"unpause",
68207description:"Unpaused",
68208standard:"posix",
68209forced:true},
68210
68211{
68212name:"SIGSTOP",
68213number:19,
68214action:"pause",
68215description:"Paused",
68216standard:"posix",
68217forced:true},
68218
68219{
68220name:"SIGTSTP",
68221number:20,
68222action:"pause",
68223description:"Paused using CTRL-Z or \"suspend\"",
68224standard:"posix"},
68225
68226{
68227name:"SIGTTIN",
68228number:21,
68229action:"pause",
68230description:"Background process cannot read terminal input",
68231standard:"posix"},
68232
68233{
68234name:"SIGBREAK",
68235number:21,
68236action:"terminate",
68237description:"User interruption with CTRL-BREAK",
68238standard:"other"},
68239
68240{
68241name:"SIGTTOU",
68242number:22,
68243action:"pause",
68244description:"Background process cannot write to terminal output",
68245standard:"posix"},
68246
68247{
68248name:"SIGURG",
68249number:23,
68250action:"ignore",
68251description:"Socket received out-of-band data",
68252standard:"bsd"},
68253
68254{
68255name:"SIGXCPU",
68256number:24,
68257action:"core",
68258description:"Process timed out",
68259standard:"bsd"},
68260
68261{
68262name:"SIGXFSZ",
68263number:25,
68264action:"core",
68265description:"File too big",
68266standard:"bsd"},
68267
68268{
68269name:"SIGVTALRM",
68270number:26,
68271action:"terminate",
68272description:"Timeout or timer",
68273standard:"bsd"},
68274
68275{
68276name:"SIGPROF",
68277number:27,
68278action:"terminate",
68279description:"Timeout or timer",
68280standard:"bsd"},
68281
68282{
68283name:"SIGWINCH",
68284number:28,
68285action:"ignore",
68286description:"Terminal window size changed",
68287standard:"bsd"},
68288
68289{
68290name:"SIGIO",
68291number:29,
68292action:"terminate",
68293description:"I/O is available",
68294standard:"other"},
68295
68296{
68297name:"SIGPOLL",
68298number:29,
68299action:"terminate",
68300description:"Watched event",
68301standard:"other"},
68302
68303{
68304name:"SIGINFO",
68305number:29,
68306action:"ignore",
68307description:"Request for process information",
68308standard:"other"},
68309
68310{
68311name:"SIGPWR",
68312number:30,
68313action:"terminate",
68314description:"Device running out of power",
68315standard:"systemv"},
68316
68317{
68318name:"SIGSYS",
68319number:31,
68320action:"core",
68321description:"Invalid system call",
68322standard:"other"},
68323
68324{
68325name:"SIGUNUSED",
68326number:31,
68327action:"terminate",
68328description:"Invalid system call",
68329standard:"other"}];core.SIGNALS=SIGNALS;
68330
68331var realtime = {};
68332
68333Object.defineProperty(realtime,"__esModule",{value:true});realtime.SIGRTMAX=realtime.getRealtimeSignals=void 0;
68334const getRealtimeSignals=function(){
68335const length=SIGRTMAX-SIGRTMIN+1;
68336return Array.from({length},getRealtimeSignal);
68337};realtime.getRealtimeSignals=getRealtimeSignals;
68338
68339const getRealtimeSignal=function(value,index){
68340return {
68341name:`SIGRT${index+1}`,
68342number:SIGRTMIN+index,
68343action:"terminate",
68344description:"Application-specific signal (realtime)",
68345standard:"posix"};
68346
68347};
68348
68349const SIGRTMIN=34;
68350const SIGRTMAX=64;realtime.SIGRTMAX=SIGRTMAX;
68351
68352Object.defineProperty(signals$2,"__esModule",{value:true});signals$2.getSignals=void 0;var _os$1=require$$0__default$1;
68353
68354var _core=core;
68355var _realtime$1=realtime;
68356
68357
68358
68359const getSignals=function(){
68360const realtimeSignals=(0, _realtime$1.getRealtimeSignals)();
68361const signals=[..._core.SIGNALS,...realtimeSignals].map(normalizeSignal);
68362return signals;
68363};signals$2.getSignals=getSignals;
68364
68365
68366
68367
68368
68369
68370
68371const normalizeSignal=function({
68372name,
68373number:defaultNumber,
68374description,
68375action,
68376forced=false,
68377standard})
68378{
68379const{
68380signals:{[name]:constantSignal}}=
68381_os$1.constants;
68382const supported=constantSignal!==undefined;
68383const number=supported?constantSignal:defaultNumber;
68384return {name,number,description,supported,action,forced,standard};
68385};
68386
68387Object.defineProperty(main$2,"__esModule",{value:true});main$2.signalsByNumber=main$2.signalsByName=void 0;var _os=require$$0__default$1;
68388
68389var _signals=signals$2;
68390var _realtime=realtime;
68391
68392
68393
68394const getSignalsByName=function(){
68395const signals=(0, _signals.getSignals)();
68396return signals.reduce(getSignalByName,{});
68397};
68398
68399const getSignalByName=function(
68400signalByNameMemo,
68401{name,number,description,supported,action,forced,standard})
68402{
68403return {
68404...signalByNameMemo,
68405[name]:{name,number,description,supported,action,forced,standard}};
68406
68407};
68408
68409const signalsByName$1=getSignalsByName();main$2.signalsByName=signalsByName$1;
68410
68411
68412
68413
68414const getSignalsByNumber=function(){
68415const signals=(0, _signals.getSignals)();
68416const length=_realtime.SIGRTMAX+1;
68417const signalsA=Array.from({length},(value,number)=>
68418getSignalByNumber(number,signals));
68419
68420return Object.assign({},...signalsA);
68421};
68422
68423const getSignalByNumber=function(number,signals){
68424const signal=findSignalByNumber(number,signals);
68425
68426if(signal===undefined){
68427return {};
68428}
68429
68430const{name,description,supported,action,forced,standard}=signal;
68431return {
68432[number]:{
68433name,
68434number,
68435description,
68436supported,
68437action,
68438forced,
68439standard}};
68440
68441
68442};
68443
68444
68445
68446const findSignalByNumber=function(number,signals){
68447const signal=signals.find(({name})=>_os.constants.signals[name]===number);
68448
68449if(signal!==undefined){
68450return signal;
68451}
68452
68453return signals.find(signalA=>signalA.number===number);
68454};
68455
68456const signalsByNumber=getSignalsByNumber();main$2.signalsByNumber=signalsByNumber;
68457
68458const {signalsByName} = main$2;
68459
68460const getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => {
68461 if (timedOut) {
68462 return `timed out after ${timeout} milliseconds`;
68463 }
68464
68465 if (isCanceled) {
68466 return 'was canceled';
68467 }
68468
68469 if (errorCode !== undefined) {
68470 return `failed with ${errorCode}`;
68471 }
68472
68473 if (signal !== undefined) {
68474 return `was killed with ${signal} (${signalDescription})`;
68475 }
68476
68477 if (exitCode !== undefined) {
68478 return `failed with exit code ${exitCode}`;
68479 }
68480
68481 return 'failed';
68482};
68483
68484const makeError$1 = ({
68485 stdout,
68486 stderr,
68487 all,
68488 error,
68489 signal,
68490 exitCode,
68491 command,
68492 escapedCommand,
68493 timedOut,
68494 isCanceled,
68495 killed,
68496 parsed: {options: {timeout}}
68497}) => {
68498 // `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`.
68499 // We normalize them to `undefined`
68500 exitCode = exitCode === null ? undefined : exitCode;
68501 signal = signal === null ? undefined : signal;
68502 const signalDescription = signal === undefined ? undefined : signalsByName[signal].description;
68503
68504 const errorCode = error && error.code;
68505
68506 const prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled});
68507 const execaMessage = `Command ${prefix}: ${command}`;
68508 const isError = Object.prototype.toString.call(error) === '[object Error]';
68509 const shortMessage = isError ? `${execaMessage}\n${error.message}` : execaMessage;
68510 const message = [shortMessage, stderr, stdout].filter(Boolean).join('\n');
68511
68512 if (isError) {
68513 error.originalMessage = error.message;
68514 error.message = message;
68515 } else {
68516 error = new Error(message);
68517 }
68518
68519 error.shortMessage = shortMessage;
68520 error.command = command;
68521 error.escapedCommand = escapedCommand;
68522 error.exitCode = exitCode;
68523 error.signal = signal;
68524 error.signalDescription = signalDescription;
68525 error.stdout = stdout;
68526 error.stderr = stderr;
68527
68528 if (all !== undefined) {
68529 error.all = all;
68530 }
68531
68532 if ('bufferedData' in error) {
68533 delete error.bufferedData;
68534 }
68535
68536 error.failed = true;
68537 error.timedOut = Boolean(timedOut);
68538 error.isCanceled = isCanceled;
68539 error.killed = killed && !timedOut;
68540
68541 return error;
68542};
68543
68544var error = makeError$1;
68545
68546var stdio = {exports: {}};
68547
68548const aliases = ['stdin', 'stdout', 'stderr'];
68549
68550const hasAlias = options => aliases.some(alias => options[alias] !== undefined);
68551
68552const normalizeStdio$1 = options => {
68553 if (!options) {
68554 return;
68555 }
68556
68557 const {stdio} = options;
68558
68559 if (stdio === undefined) {
68560 return aliases.map(alias => options[alias]);
68561 }
68562
68563 if (hasAlias(options)) {
68564 throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${aliases.map(alias => `\`${alias}\``).join(', ')}`);
68565 }
68566
68567 if (typeof stdio === 'string') {
68568 return stdio;
68569 }
68570
68571 if (!Array.isArray(stdio)) {
68572 throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``);
68573 }
68574
68575 const length = Math.max(stdio.length, aliases.length);
68576 return Array.from({length}, (value, index) => stdio[index]);
68577};
68578
68579stdio.exports = normalizeStdio$1;
68580
68581// `ipc` is pushed unless it is already present
68582stdio.exports.node = options => {
68583 const stdio = normalizeStdio$1(options);
68584
68585 if (stdio === 'ipc') {
68586 return 'ipc';
68587 }
68588
68589 if (stdio === undefined || typeof stdio === 'string') {
68590 return [stdio, stdio, stdio, 'ipc'];
68591 }
68592
68593 if (stdio.includes('ipc')) {
68594 return stdio;
68595 }
68596
68597 return [...stdio, 'ipc'];
68598};
68599
68600var signalExit = {exports: {}};
68601
68602var signals$1 = {exports: {}};
68603
68604(function (module) {
68605// This is not the set of all possible signals.
68606//
68607// It IS, however, the set of all signals that trigger
68608// an exit on either Linux or BSD systems. Linux is a
68609// superset of the signal names supported on BSD, and
68610// the unknown signals just fail to register, so we can
68611// catch that easily enough.
68612//
68613// Don't bother with SIGKILL. It's uncatchable, which
68614// means that we can't fire any callbacks anyway.
68615//
68616// If a user does happen to register a handler on a non-
68617// fatal signal like SIGWINCH or something, and then
68618// exit, it'll end up firing `process.emit('exit')`, so
68619// the handler will be fired anyway.
68620//
68621// SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised
68622// artificially, inherently leave the process in a
68623// state from which it is not safe to try and enter JS
68624// listeners.
68625module.exports = [
68626 'SIGABRT',
68627 'SIGALRM',
68628 'SIGHUP',
68629 'SIGINT',
68630 'SIGTERM'
68631];
68632
68633if (process.platform !== 'win32') {
68634 module.exports.push(
68635 'SIGVTALRM',
68636 'SIGXCPU',
68637 'SIGXFSZ',
68638 'SIGUSR2',
68639 'SIGTRAP',
68640 'SIGSYS',
68641 'SIGQUIT',
68642 'SIGIOT'
68643 // should detect profiler and enable/disable accordingly.
68644 // see #21
68645 // 'SIGPROF'
68646 );
68647}
68648
68649if (process.platform === 'linux') {
68650 module.exports.push(
68651 'SIGIO',
68652 'SIGPOLL',
68653 'SIGPWR',
68654 'SIGSTKFLT',
68655 'SIGUNUSED'
68656 );
68657}
68658}(signals$1));
68659
68660// Note: since nyc uses this module to output coverage, any lines
68661// that are in the direct sync flow of nyc's outputCoverage are
68662// ignored, since we can never get coverage for them.
68663var assert = require$$6__default;
68664var signals = signals$1.exports;
68665var isWin = /^win/i.test(process.platform);
68666
68667var EE = require$$0__default$6;
68668/* istanbul ignore if */
68669if (typeof EE !== 'function') {
68670 EE = EE.EventEmitter;
68671}
68672
68673var emitter;
68674if (process.__signal_exit_emitter__) {
68675 emitter = process.__signal_exit_emitter__;
68676} else {
68677 emitter = process.__signal_exit_emitter__ = new EE();
68678 emitter.count = 0;
68679 emitter.emitted = {};
68680}
68681
68682// Because this emitter is a global, we have to check to see if a
68683// previous version of this library failed to enable infinite listeners.
68684// I know what you're about to say. But literally everything about
68685// signal-exit is a compromise with evil. Get used to it.
68686if (!emitter.infinite) {
68687 emitter.setMaxListeners(Infinity);
68688 emitter.infinite = true;
68689}
68690
68691signalExit.exports = function (cb, opts) {
68692 assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler');
68693
68694 if (loaded === false) {
68695 load();
68696 }
68697
68698 var ev = 'exit';
68699 if (opts && opts.alwaysLast) {
68700 ev = 'afterexit';
68701 }
68702
68703 var remove = function () {
68704 emitter.removeListener(ev, cb);
68705 if (emitter.listeners('exit').length === 0 &&
68706 emitter.listeners('afterexit').length === 0) {
68707 unload();
68708 }
68709 };
68710 emitter.on(ev, cb);
68711
68712 return remove
68713};
68714
68715signalExit.exports.unload = unload;
68716function unload () {
68717 if (!loaded) {
68718 return
68719 }
68720 loaded = false;
68721
68722 signals.forEach(function (sig) {
68723 try {
68724 process.removeListener(sig, sigListeners[sig]);
68725 } catch (er) {}
68726 });
68727 process.emit = originalProcessEmit;
68728 process.reallyExit = originalProcessReallyExit;
68729 emitter.count -= 1;
68730}
68731
68732function emit (event, code, signal) {
68733 if (emitter.emitted[event]) {
68734 return
68735 }
68736 emitter.emitted[event] = true;
68737 emitter.emit(event, code, signal);
68738}
68739
68740// { <signal>: <listener fn>, ... }
68741var sigListeners = {};
68742signals.forEach(function (sig) {
68743 sigListeners[sig] = function listener () {
68744 // If there are no other listeners, an exit is coming!
68745 // Simplest way: remove us and then re-send the signal.
68746 // We know that this will kill the process, so we can
68747 // safely emit now.
68748 var listeners = process.listeners(sig);
68749 if (listeners.length === emitter.count) {
68750 unload();
68751 emit('exit', null, sig);
68752 /* istanbul ignore next */
68753 emit('afterexit', null, sig);
68754 /* istanbul ignore next */
68755 if (isWin && sig === 'SIGHUP') {
68756 // "SIGHUP" throws an `ENOSYS` error on Windows,
68757 // so use a supported signal instead
68758 sig = 'SIGINT';
68759 }
68760 process.kill(process.pid, sig);
68761 }
68762 };
68763});
68764
68765signalExit.exports.signals = function () {
68766 return signals
68767};
68768
68769signalExit.exports.load = load;
68770
68771var loaded = false;
68772
68773function load () {
68774 if (loaded) {
68775 return
68776 }
68777 loaded = true;
68778
68779 // This is the number of onSignalExit's that are in play.
68780 // It's important so that we can count the correct number of
68781 // listeners on signals, and don't wait for the other one to
68782 // handle it instead of us.
68783 emitter.count += 1;
68784
68785 signals = signals.filter(function (sig) {
68786 try {
68787 process.on(sig, sigListeners[sig]);
68788 return true
68789 } catch (er) {
68790 return false
68791 }
68792 });
68793
68794 process.emit = processEmit;
68795 process.reallyExit = processReallyExit;
68796}
68797
68798var originalProcessReallyExit = process.reallyExit;
68799function processReallyExit (code) {
68800 process.exitCode = code || 0;
68801 emit('exit', process.exitCode, null);
68802 /* istanbul ignore next */
68803 emit('afterexit', process.exitCode, null);
68804 /* istanbul ignore next */
68805 originalProcessReallyExit.call(process, process.exitCode);
68806}
68807
68808var originalProcessEmit = process.emit;
68809function processEmit (ev, arg) {
68810 if (ev === 'exit') {
68811 if (arg !== undefined) {
68812 process.exitCode = arg;
68813 }
68814 var ret = originalProcessEmit.apply(this, arguments);
68815 emit('exit', process.exitCode, null);
68816 /* istanbul ignore next */
68817 emit('afterexit', process.exitCode, null);
68818 return ret
68819 } else {
68820 return originalProcessEmit.apply(this, arguments)
68821 }
68822}
68823
68824const os$3 = require$$0__default$1;
68825const onExit = signalExit.exports;
68826
68827const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;
68828
68829// Monkey-patches `childProcess.kill()` to add `forceKillAfterTimeout` behavior
68830const spawnedKill$1 = (kill, signal = 'SIGTERM', options = {}) => {
68831 const killResult = kill(signal);
68832 setKillTimeout(kill, signal, options, killResult);
68833 return killResult;
68834};
68835
68836const setKillTimeout = (kill, signal, options, killResult) => {
68837 if (!shouldForceKill(signal, options, killResult)) {
68838 return;
68839 }
68840
68841 const timeout = getForceKillAfterTimeout(options);
68842 const t = setTimeout(() => {
68843 kill('SIGKILL');
68844 }, timeout);
68845
68846 // Guarded because there's no `.unref()` when `execa` is used in the renderer
68847 // process in Electron. This cannot be tested since we don't run tests in
68848 // Electron.
68849 // istanbul ignore else
68850 if (t.unref) {
68851 t.unref();
68852 }
68853};
68854
68855const shouldForceKill = (signal, {forceKillAfterTimeout}, killResult) => {
68856 return isSigterm(signal) && forceKillAfterTimeout !== false && killResult;
68857};
68858
68859const isSigterm = signal => {
68860 return signal === os$3.constants.signals.SIGTERM ||
68861 (typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM');
68862};
68863
68864const getForceKillAfterTimeout = ({forceKillAfterTimeout = true}) => {
68865 if (forceKillAfterTimeout === true) {
68866 return DEFAULT_FORCE_KILL_TIMEOUT;
68867 }
68868
68869 if (!Number.isFinite(forceKillAfterTimeout) || forceKillAfterTimeout < 0) {
68870 throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${forceKillAfterTimeout}\` (${typeof forceKillAfterTimeout})`);
68871 }
68872
68873 return forceKillAfterTimeout;
68874};
68875
68876// `childProcess.cancel()`
68877const spawnedCancel$1 = (spawned, context) => {
68878 const killResult = spawned.kill();
68879
68880 if (killResult) {
68881 context.isCanceled = true;
68882 }
68883};
68884
68885const timeoutKill = (spawned, signal, reject) => {
68886 spawned.kill(signal);
68887 reject(Object.assign(new Error('Timed out'), {timedOut: true, signal}));
68888};
68889
68890// `timeout` option handling
68891const setupTimeout$1 = (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise) => {
68892 if (timeout === 0 || timeout === undefined) {
68893 return spawnedPromise;
68894 }
68895
68896 let timeoutId;
68897 const timeoutPromise = new Promise((resolve, reject) => {
68898 timeoutId = setTimeout(() => {
68899 timeoutKill(spawned, killSignal, reject);
68900 }, timeout);
68901 });
68902
68903 const safeSpawnedPromise = spawnedPromise.finally(() => {
68904 clearTimeout(timeoutId);
68905 });
68906
68907 return Promise.race([timeoutPromise, safeSpawnedPromise]);
68908};
68909
68910const validateTimeout$1 = ({timeout}) => {
68911 if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) {
68912 throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`);
68913 }
68914};
68915
68916// `cleanup` option handling
68917const setExitHandler$1 = async (spawned, {cleanup, detached}, timedPromise) => {
68918 if (!cleanup || detached) {
68919 return timedPromise;
68920 }
68921
68922 const removeExitHandler = onExit(() => {
68923 spawned.kill();
68924 });
68925
68926 return timedPromise.finally(() => {
68927 removeExitHandler();
68928 });
68929};
68930
68931var kill = {
68932 spawnedKill: spawnedKill$1,
68933 spawnedCancel: spawnedCancel$1,
68934 setupTimeout: setupTimeout$1,
68935 validateTimeout: validateTimeout$1,
68936 setExitHandler: setExitHandler$1
68937};
68938
68939const isStream$1 = stream =>
68940 stream !== null &&
68941 typeof stream === 'object' &&
68942 typeof stream.pipe === 'function';
68943
68944isStream$1.writable = stream =>
68945 isStream$1(stream) &&
68946 stream.writable !== false &&
68947 typeof stream._write === 'function' &&
68948 typeof stream._writableState === 'object';
68949
68950isStream$1.readable = stream =>
68951 isStream$1(stream) &&
68952 stream.readable !== false &&
68953 typeof stream._read === 'function' &&
68954 typeof stream._readableState === 'object';
68955
68956isStream$1.duplex = stream =>
68957 isStream$1.writable(stream) &&
68958 isStream$1.readable(stream);
68959
68960isStream$1.transform = stream =>
68961 isStream$1.duplex(stream) &&
68962 typeof stream._transform === 'function' &&
68963 typeof stream._transformState === 'object';
68964
68965var isStream_1 = isStream$1;
68966
68967var getStream$2 = {exports: {}};
68968
68969const {PassThrough: PassThroughStream} = require$$0__default$2;
68970
68971var bufferStream$1 = options => {
68972 options = {...options};
68973
68974 const {array} = options;
68975 let {encoding} = options;
68976 const isBuffer = encoding === 'buffer';
68977 let objectMode = false;
68978
68979 if (array) {
68980 objectMode = !(encoding || isBuffer);
68981 } else {
68982 encoding = encoding || 'utf8';
68983 }
68984
68985 if (isBuffer) {
68986 encoding = null;
68987 }
68988
68989 const stream = new PassThroughStream({objectMode});
68990
68991 if (encoding) {
68992 stream.setEncoding(encoding);
68993 }
68994
68995 let length = 0;
68996 const chunks = [];
68997
68998 stream.on('data', chunk => {
68999 chunks.push(chunk);
69000
69001 if (objectMode) {
69002 length = chunks.length;
69003 } else {
69004 length += chunk.length;
69005 }
69006 });
69007
69008 stream.getBufferedValue = () => {
69009 if (array) {
69010 return chunks;
69011 }
69012
69013 return isBuffer ? Buffer.concat(chunks, length) : chunks.join('');
69014 };
69015
69016 stream.getBufferedLength = () => length;
69017
69018 return stream;
69019};
69020
69021const {constants: BufferConstants} = require$$0__default$9;
69022const stream$1 = require$$0__default$2;
69023const {promisify} = require$$0__default$3;
69024const bufferStream = bufferStream$1;
69025
69026const streamPipelinePromisified = promisify(stream$1.pipeline);
69027
69028class MaxBufferError extends Error {
69029 constructor() {
69030 super('maxBuffer exceeded');
69031 this.name = 'MaxBufferError';
69032 }
69033}
69034
69035async function getStream$1(inputStream, options) {
69036 if (!inputStream) {
69037 throw new Error('Expected a stream');
69038 }
69039
69040 options = {
69041 maxBuffer: Infinity,
69042 ...options
69043 };
69044
69045 const {maxBuffer} = options;
69046 const stream = bufferStream(options);
69047
69048 await new Promise((resolve, reject) => {
69049 const rejectPromise = error => {
69050 // Don't retrieve an oversized buffer.
69051 if (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) {
69052 error.bufferedData = stream.getBufferedValue();
69053 }
69054
69055 reject(error);
69056 };
69057
69058 (async () => {
69059 try {
69060 await streamPipelinePromisified(inputStream, stream);
69061 resolve();
69062 } catch (error) {
69063 rejectPromise(error);
69064 }
69065 })();
69066
69067 stream.on('data', () => {
69068 if (stream.getBufferedLength() > maxBuffer) {
69069 rejectPromise(new MaxBufferError());
69070 }
69071 });
69072 });
69073
69074 return stream.getBufferedValue();
69075}
69076
69077getStream$2.exports = getStream$1;
69078getStream$2.exports.buffer = (stream, options) => getStream$1(stream, {...options, encoding: 'buffer'});
69079getStream$2.exports.array = (stream, options) => getStream$1(stream, {...options, array: true});
69080getStream$2.exports.MaxBufferError = MaxBufferError;
69081
69082const { PassThrough } = require$$0__default$2;
69083
69084var mergeStream$1 = function (/*streams...*/) {
69085 var sources = [];
69086 var output = new PassThrough({objectMode: true});
69087
69088 output.setMaxListeners(0);
69089
69090 output.add = add;
69091 output.isEmpty = isEmpty;
69092
69093 output.on('unpipe', remove);
69094
69095 Array.prototype.slice.call(arguments).forEach(add);
69096
69097 return output
69098
69099 function add (source) {
69100 if (Array.isArray(source)) {
69101 source.forEach(add);
69102 return this
69103 }
69104
69105 sources.push(source);
69106 source.once('end', remove.bind(null, source));
69107 source.once('error', output.emit.bind(output, 'error'));
69108 source.pipe(output, {end: false});
69109 return this
69110 }
69111
69112 function isEmpty () {
69113 return sources.length == 0;
69114 }
69115
69116 function remove (source) {
69117 sources = sources.filter(function (it) { return it !== source });
69118 if (!sources.length && output.readable) { output.end(); }
69119 }
69120};
69121
69122const isStream = isStream_1;
69123const getStream = getStream$2.exports;
69124const mergeStream = mergeStream$1;
69125
69126// `input` option
69127const handleInput$1 = (spawned, input) => {
69128 // Checking for stdin is workaround for https://github.com/nodejs/node/issues/26852
69129 // @todo remove `|| spawned.stdin === undefined` once we drop support for Node.js <=12.2.0
69130 if (input === undefined || spawned.stdin === undefined) {
69131 return;
69132 }
69133
69134 if (isStream(input)) {
69135 input.pipe(spawned.stdin);
69136 } else {
69137 spawned.stdin.end(input);
69138 }
69139};
69140
69141// `all` interleaves `stdout` and `stderr`
69142const makeAllStream$1 = (spawned, {all}) => {
69143 if (!all || (!spawned.stdout && !spawned.stderr)) {
69144 return;
69145 }
69146
69147 const mixed = mergeStream();
69148
69149 if (spawned.stdout) {
69150 mixed.add(spawned.stdout);
69151 }
69152
69153 if (spawned.stderr) {
69154 mixed.add(spawned.stderr);
69155 }
69156
69157 return mixed;
69158};
69159
69160// On failure, `result.stdout|stderr|all` should contain the currently buffered stream
69161const getBufferedData = async (stream, streamPromise) => {
69162 if (!stream) {
69163 return;
69164 }
69165
69166 stream.destroy();
69167
69168 try {
69169 return await streamPromise;
69170 } catch (error) {
69171 return error.bufferedData;
69172 }
69173};
69174
69175const getStreamPromise = (stream, {encoding, buffer, maxBuffer}) => {
69176 if (!stream || !buffer) {
69177 return;
69178 }
69179
69180 if (encoding) {
69181 return getStream(stream, {encoding, maxBuffer});
69182 }
69183
69184 return getStream.buffer(stream, {maxBuffer});
69185};
69186
69187// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)
69188const getSpawnedResult$1 = async ({stdout, stderr, all}, {encoding, buffer, maxBuffer}, processDone) => {
69189 const stdoutPromise = getStreamPromise(stdout, {encoding, buffer, maxBuffer});
69190 const stderrPromise = getStreamPromise(stderr, {encoding, buffer, maxBuffer});
69191 const allPromise = getStreamPromise(all, {encoding, buffer, maxBuffer: maxBuffer * 2});
69192
69193 try {
69194 return await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]);
69195 } catch (error) {
69196 return Promise.all([
69197 {error, signal: error.signal, timedOut: error.timedOut},
69198 getBufferedData(stdout, stdoutPromise),
69199 getBufferedData(stderr, stderrPromise),
69200 getBufferedData(all, allPromise)
69201 ]);
69202 }
69203};
69204
69205const validateInputSync$1 = ({input}) => {
69206 if (isStream(input)) {
69207 throw new TypeError('The `input` option cannot be a stream in sync mode');
69208 }
69209};
69210
69211var stream = {
69212 handleInput: handleInput$1,
69213 makeAllStream: makeAllStream$1,
69214 getSpawnedResult: getSpawnedResult$1,
69215 validateInputSync: validateInputSync$1
69216};
69217
69218const nativePromisePrototype = (async () => {})().constructor.prototype;
69219const descriptors = ['then', 'catch', 'finally'].map(property => [
69220 property,
69221 Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property)
69222]);
69223
69224// The return value is a mixin of `childProcess` and `Promise`
69225const mergePromise$1 = (spawned, promise) => {
69226 for (const [property, descriptor] of descriptors) {
69227 // Starting the main `promise` is deferred to avoid consuming streams
69228 const value = typeof promise === 'function' ?
69229 (...args) => Reflect.apply(descriptor.value, promise(), args) :
69230 descriptor.value.bind(promise);
69231
69232 Reflect.defineProperty(spawned, property, {...descriptor, value});
69233 }
69234
69235 return spawned;
69236};
69237
69238// Use promises instead of `child_process` events
69239const getSpawnedPromise$1 = spawned => {
69240 return new Promise((resolve, reject) => {
69241 spawned.on('exit', (exitCode, signal) => {
69242 resolve({exitCode, signal});
69243 });
69244
69245 spawned.on('error', error => {
69246 reject(error);
69247 });
69248
69249 if (spawned.stdin) {
69250 spawned.stdin.on('error', error => {
69251 reject(error);
69252 });
69253 }
69254 });
69255};
69256
69257var promise = {
69258 mergePromise: mergePromise$1,
69259 getSpawnedPromise: getSpawnedPromise$1
69260};
69261
69262const normalizeArgs = (file, args = []) => {
69263 if (!Array.isArray(args)) {
69264 return [file];
69265 }
69266
69267 return [file, ...args];
69268};
69269
69270const NO_ESCAPE_REGEXP = /^[\w.-]+$/;
69271const DOUBLE_QUOTES_REGEXP = /"/g;
69272
69273const escapeArg = arg => {
69274 if (typeof arg !== 'string' || NO_ESCAPE_REGEXP.test(arg)) {
69275 return arg;
69276 }
69277
69278 return `"${arg.replace(DOUBLE_QUOTES_REGEXP, '\\"')}"`;
69279};
69280
69281const joinCommand$1 = (file, args) => {
69282 return normalizeArgs(file, args).join(' ');
69283};
69284
69285const getEscapedCommand$1 = (file, args) => {
69286 return normalizeArgs(file, args).map(arg => escapeArg(arg)).join(' ');
69287};
69288
69289const SPACES_REGEXP = / +/g;
69290
69291// Handle `execa.command()`
69292const parseCommand$1 = command => {
69293 const tokens = [];
69294 for (const token of command.trim().split(SPACES_REGEXP)) {
69295 // Allow spaces to be escaped by a backslash if not meant as a delimiter
69296 const previousToken = tokens[tokens.length - 1];
69297 if (previousToken && previousToken.endsWith('\\')) {
69298 // Merge previous token with current one
69299 tokens[tokens.length - 1] = `${previousToken.slice(0, -1)} ${token}`;
69300 } else {
69301 tokens.push(token);
69302 }
69303 }
69304
69305 return tokens;
69306};
69307
69308var command = {
69309 joinCommand: joinCommand$1,
69310 getEscapedCommand: getEscapedCommand$1,
69311 parseCommand: parseCommand$1
69312};
69313
69314const path$5 = path__default;
69315const childProcess$2 = require$$1__default$3;
69316const crossSpawn = crossSpawn$1.exports;
69317const stripFinalNewline = stripFinalNewline$1;
69318const npmRunPath = npmRunPath$1.exports;
69319const onetime = onetime$2.exports;
69320const makeError = error;
69321const normalizeStdio = stdio.exports;
69322const {spawnedKill, spawnedCancel, setupTimeout, validateTimeout, setExitHandler} = kill;
69323const {handleInput, getSpawnedResult, makeAllStream, validateInputSync} = stream;
69324const {mergePromise, getSpawnedPromise} = promise;
69325const {joinCommand, parseCommand, getEscapedCommand} = command;
69326
69327const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100;
69328
69329const getEnv = ({env: envOption, extendEnv, preferLocal, localDir, execPath}) => {
69330 const env = extendEnv ? {...process.env, ...envOption} : envOption;
69331
69332 if (preferLocal) {
69333 return npmRunPath.env({env, cwd: localDir, execPath});
69334 }
69335
69336 return env;
69337};
69338
69339const handleArguments = (file, args, options = {}) => {
69340 const parsed = crossSpawn._parse(file, args, options);
69341 file = parsed.command;
69342 args = parsed.args;
69343 options = parsed.options;
69344
69345 options = {
69346 maxBuffer: DEFAULT_MAX_BUFFER,
69347 buffer: true,
69348 stripFinalNewline: true,
69349 extendEnv: true,
69350 preferLocal: false,
69351 localDir: options.cwd || process.cwd(),
69352 execPath: process.execPath,
69353 encoding: 'utf8',
69354 reject: true,
69355 cleanup: true,
69356 all: false,
69357 windowsHide: true,
69358 ...options
69359 };
69360
69361 options.env = getEnv(options);
69362
69363 options.stdio = normalizeStdio(options);
69364
69365 if (process.platform === 'win32' && path$5.basename(file, '.exe') === 'cmd') {
69366 // #116
69367 args.unshift('/q');
69368 }
69369
69370 return {file, args, options, parsed};
69371};
69372
69373const handleOutput = (options, value, error) => {
69374 if (typeof value !== 'string' && !Buffer.isBuffer(value)) {
69375 // When `execa.sync()` errors, we normalize it to '' to mimic `execa()`
69376 return error === undefined ? undefined : '';
69377 }
69378
69379 if (options.stripFinalNewline) {
69380 return stripFinalNewline(value);
69381 }
69382
69383 return value;
69384};
69385
69386const execa = (file, args, options) => {
69387 const parsed = handleArguments(file, args, options);
69388 const command = joinCommand(file, args);
69389 const escapedCommand = getEscapedCommand(file, args);
69390
69391 validateTimeout(parsed.options);
69392
69393 let spawned;
69394 try {
69395 spawned = childProcess$2.spawn(parsed.file, parsed.args, parsed.options);
69396 } catch (error) {
69397 // Ensure the returned error is always both a promise and a child process
69398 const dummySpawned = new childProcess$2.ChildProcess();
69399 const errorPromise = Promise.reject(makeError({
69400 error,
69401 stdout: '',
69402 stderr: '',
69403 all: '',
69404 command,
69405 escapedCommand,
69406 parsed,
69407 timedOut: false,
69408 isCanceled: false,
69409 killed: false
69410 }));
69411 return mergePromise(dummySpawned, errorPromise);
69412 }
69413
69414 const spawnedPromise = getSpawnedPromise(spawned);
69415 const timedPromise = setupTimeout(spawned, parsed.options, spawnedPromise);
69416 const processDone = setExitHandler(spawned, parsed.options, timedPromise);
69417
69418 const context = {isCanceled: false};
69419
69420 spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned));
69421 spawned.cancel = spawnedCancel.bind(null, spawned, context);
69422
69423 const handlePromise = async () => {
69424 const [{error, exitCode, signal, timedOut}, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, processDone);
69425 const stdout = handleOutput(parsed.options, stdoutResult);
69426 const stderr = handleOutput(parsed.options, stderrResult);
69427 const all = handleOutput(parsed.options, allResult);
69428
69429 if (error || exitCode !== 0 || signal !== null) {
69430 const returnedError = makeError({
69431 error,
69432 exitCode,
69433 signal,
69434 stdout,
69435 stderr,
69436 all,
69437 command,
69438 escapedCommand,
69439 parsed,
69440 timedOut,
69441 isCanceled: context.isCanceled,
69442 killed: spawned.killed
69443 });
69444
69445 if (!parsed.options.reject) {
69446 return returnedError;
69447 }
69448
69449 throw returnedError;
69450 }
69451
69452 return {
69453 command,
69454 escapedCommand,
69455 exitCode: 0,
69456 stdout,
69457 stderr,
69458 all,
69459 failed: false,
69460 timedOut: false,
69461 isCanceled: false,
69462 killed: false
69463 };
69464 };
69465
69466 const handlePromiseOnce = onetime(handlePromise);
69467
69468 handleInput(spawned, parsed.options.input);
69469
69470 spawned.all = makeAllStream(spawned, parsed.options);
69471
69472 return mergePromise(spawned, handlePromiseOnce);
69473};
69474
69475execa$2.exports = execa;
69476
69477execa$2.exports.sync = (file, args, options) => {
69478 const parsed = handleArguments(file, args, options);
69479 const command = joinCommand(file, args);
69480 const escapedCommand = getEscapedCommand(file, args);
69481
69482 validateInputSync(parsed.options);
69483
69484 let result;
69485 try {
69486 result = childProcess$2.spawnSync(parsed.file, parsed.args, parsed.options);
69487 } catch (error) {
69488 throw makeError({
69489 error,
69490 stdout: '',
69491 stderr: '',
69492 all: '',
69493 command,
69494 escapedCommand,
69495 parsed,
69496 timedOut: false,
69497 isCanceled: false,
69498 killed: false
69499 });
69500 }
69501
69502 const stdout = handleOutput(parsed.options, result.stdout, result.error);
69503 const stderr = handleOutput(parsed.options, result.stderr, result.error);
69504
69505 if (result.error || result.status !== 0 || result.signal !== null) {
69506 const error = makeError({
69507 stdout,
69508 stderr,
69509 error: result.error,
69510 signal: result.signal,
69511 exitCode: result.status,
69512 command,
69513 escapedCommand,
69514 parsed,
69515 timedOut: result.error && result.error.code === 'ETIMEDOUT',
69516 isCanceled: false,
69517 killed: result.signal !== null
69518 });
69519
69520 if (!parsed.options.reject) {
69521 return error;
69522 }
69523
69524 throw error;
69525 }
69526
69527 return {
69528 command,
69529 escapedCommand,
69530 exitCode: 0,
69531 stdout,
69532 stderr,
69533 failed: false,
69534 timedOut: false,
69535 isCanceled: false,
69536 killed: false
69537 };
69538};
69539
69540execa$2.exports.command = (command, options) => {
69541 const [file, ...args] = parseCommand(command);
69542 return execa(file, args, options);
69543};
69544
69545execa$2.exports.commandSync = (command, options) => {
69546 const [file, ...args] = parseCommand(command);
69547 return execa.sync(file, args, options);
69548};
69549
69550execa$2.exports.node = (scriptPath, args, options = {}) => {
69551 if (args && !Array.isArray(args) && typeof args === 'object') {
69552 options = args;
69553 args = [];
69554 }
69555
69556 const stdio = normalizeStdio.node(options);
69557 const defaultExecArgv = process.execArgv.filter(arg => !arg.startsWith('--inspect'));
69558
69559 const {
69560 nodePath = process.execPath,
69561 nodeOptions = defaultExecArgv
69562 } = options;
69563
69564 return execa(
69565 nodePath,
69566 [
69567 ...nodeOptions,
69568 scriptPath,
69569 ...(Array.isArray(args) ? args : [])
69570 ],
69571 {
69572 ...options,
69573 stdin: undefined,
69574 stdout: undefined,
69575 stderr: undefined,
69576 stdio,
69577 shell: false
69578 }
69579 );
69580};
69581
69582var execa$1 = execa$2.exports;
69583
69584/**
69585 * The following is modified based on source found in
69586 * https://github.com/facebook/create-react-app
69587 *
69588 * MIT Licensed
69589 * Copyright (c) 2015-present, Facebook, Inc.
69590 * https://github.com/facebook/create-react-app/blob/master/LICENSE
69591 *
69592 */
69593// https://github.com/sindresorhus/open#app
69594const OSX_CHROME = 'google chrome';
69595/**
69596 * Reads the BROWSER environment variable and decides what to do with it.
69597 * Returns true if it opened a browser or ran a node.js script, otherwise false.
69598 */
69599function openBrowser(url, opt, logger) {
69600 // The browser executable to open.
69601 // See https://github.com/sindresorhus/open#app for documentation.
69602 const browser = typeof opt === 'string' ? opt : process.env.BROWSER || '';
69603 if (browser.toLowerCase().endsWith('.js')) {
69604 return executeNodeScript(browser, url, logger);
69605 }
69606 else if (browser.toLowerCase() !== 'none') {
69607 return startBrowserProcess(browser, url);
69608 }
69609 return false;
69610}
69611function executeNodeScript(scriptPath, url, logger) {
69612 const extraArgs = process.argv.slice(2);
69613 const child = execa$1('node', [scriptPath, ...extraArgs, url], {
69614 stdio: 'inherit'
69615 });
69616 child.on('close', (code) => {
69617 if (code !== 0) {
69618 logger.error(source.red('\nThe script specified as BROWSER environment variable failed.\n'));
69619 logger.error(source.cyan(scriptPath) + ' exited with code ' + code + '.');
69620 return;
69621 }
69622 });
69623 return true;
69624}
69625function startBrowserProcess(browser, url) {
69626 // If we're on OS X, the user hasn't specifically
69627 // requested a different browser, we can try opening
69628 // Chrome with AppleScript. This lets us reuse an
69629 // existing tab when possible instead of creating a new one.
69630 const shouldTryOpenChromeWithAppleScript = process.platform === 'darwin' && (browser === '' || browser === OSX_CHROME);
69631 if (shouldTryOpenChromeWithAppleScript) {
69632 try {
69633 // Try our best to reuse existing tab
69634 // on OS X Google Chrome with AppleScript
69635 require$$1$5.execSync('ps cax | grep "Google Chrome"');
69636 require$$1$5.execSync('osascript openChrome.applescript "' + encodeURI(url) + '"', {
69637 cwd: path__default.dirname(require.resolve('vite/bin/openChrome.applescript')),
69638 stdio: 'ignore'
69639 });
69640 return true;
69641 }
69642 catch (err) {
69643 // Ignore errors
69644 }
69645 }
69646 // Another special case: on OS X, check if BROWSER has been set to "open".
69647 // In this case, instead of passing the string `open` to `open` function (which won't work),
69648 // just ignore it (thus ensuring the intended behavior, i.e. opening the system browser):
69649 // https://github.com/facebook/create-react-app/pull/1690#issuecomment-283518768
69650 if (process.platform === 'darwin' && browser === 'open') {
69651 browser = undefined;
69652 }
69653 // Fallback to open
69654 // (It will always open new tab)
69655 try {
69656 const options = browser ? { app: { name: browser } } : {};
69657 open_1(url, options).catch(() => { }); // Prevent `unhandledRejection` error.
69658 return true;
69659 }
69660 catch (err) {
69661 return false;
69662 }
69663}
69664
69665var chalk$1 = {exports: {}};
69666
69667var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
69668
69669var escapeStringRegexp = function (str) {
69670 if (typeof str !== 'string') {
69671 throw new TypeError('Expected a string');
69672 }
69673
69674 return str.replace(matchOperatorsRe, '\\$&');
69675};
69676
69677var ansiStyles = {exports: {}};
69678
69679var conversions$2 = {exports: {}};
69680
69681var colorName = {
69682 "aliceblue": [240, 248, 255],
69683 "antiquewhite": [250, 235, 215],
69684 "aqua": [0, 255, 255],
69685 "aquamarine": [127, 255, 212],
69686 "azure": [240, 255, 255],
69687 "beige": [245, 245, 220],
69688 "bisque": [255, 228, 196],
69689 "black": [0, 0, 0],
69690 "blanchedalmond": [255, 235, 205],
69691 "blue": [0, 0, 255],
69692 "blueviolet": [138, 43, 226],
69693 "brown": [165, 42, 42],
69694 "burlywood": [222, 184, 135],
69695 "cadetblue": [95, 158, 160],
69696 "chartreuse": [127, 255, 0],
69697 "chocolate": [210, 105, 30],
69698 "coral": [255, 127, 80],
69699 "cornflowerblue": [100, 149, 237],
69700 "cornsilk": [255, 248, 220],
69701 "crimson": [220, 20, 60],
69702 "cyan": [0, 255, 255],
69703 "darkblue": [0, 0, 139],
69704 "darkcyan": [0, 139, 139],
69705 "darkgoldenrod": [184, 134, 11],
69706 "darkgray": [169, 169, 169],
69707 "darkgreen": [0, 100, 0],
69708 "darkgrey": [169, 169, 169],
69709 "darkkhaki": [189, 183, 107],
69710 "darkmagenta": [139, 0, 139],
69711 "darkolivegreen": [85, 107, 47],
69712 "darkorange": [255, 140, 0],
69713 "darkorchid": [153, 50, 204],
69714 "darkred": [139, 0, 0],
69715 "darksalmon": [233, 150, 122],
69716 "darkseagreen": [143, 188, 143],
69717 "darkslateblue": [72, 61, 139],
69718 "darkslategray": [47, 79, 79],
69719 "darkslategrey": [47, 79, 79],
69720 "darkturquoise": [0, 206, 209],
69721 "darkviolet": [148, 0, 211],
69722 "deeppink": [255, 20, 147],
69723 "deepskyblue": [0, 191, 255],
69724 "dimgray": [105, 105, 105],
69725 "dimgrey": [105, 105, 105],
69726 "dodgerblue": [30, 144, 255],
69727 "firebrick": [178, 34, 34],
69728 "floralwhite": [255, 250, 240],
69729 "forestgreen": [34, 139, 34],
69730 "fuchsia": [255, 0, 255],
69731 "gainsboro": [220, 220, 220],
69732 "ghostwhite": [248, 248, 255],
69733 "gold": [255, 215, 0],
69734 "goldenrod": [218, 165, 32],
69735 "gray": [128, 128, 128],
69736 "green": [0, 128, 0],
69737 "greenyellow": [173, 255, 47],
69738 "grey": [128, 128, 128],
69739 "honeydew": [240, 255, 240],
69740 "hotpink": [255, 105, 180],
69741 "indianred": [205, 92, 92],
69742 "indigo": [75, 0, 130],
69743 "ivory": [255, 255, 240],
69744 "khaki": [240, 230, 140],
69745 "lavender": [230, 230, 250],
69746 "lavenderblush": [255, 240, 245],
69747 "lawngreen": [124, 252, 0],
69748 "lemonchiffon": [255, 250, 205],
69749 "lightblue": [173, 216, 230],
69750 "lightcoral": [240, 128, 128],
69751 "lightcyan": [224, 255, 255],
69752 "lightgoldenrodyellow": [250, 250, 210],
69753 "lightgray": [211, 211, 211],
69754 "lightgreen": [144, 238, 144],
69755 "lightgrey": [211, 211, 211],
69756 "lightpink": [255, 182, 193],
69757 "lightsalmon": [255, 160, 122],
69758 "lightseagreen": [32, 178, 170],
69759 "lightskyblue": [135, 206, 250],
69760 "lightslategray": [119, 136, 153],
69761 "lightslategrey": [119, 136, 153],
69762 "lightsteelblue": [176, 196, 222],
69763 "lightyellow": [255, 255, 224],
69764 "lime": [0, 255, 0],
69765 "limegreen": [50, 205, 50],
69766 "linen": [250, 240, 230],
69767 "magenta": [255, 0, 255],
69768 "maroon": [128, 0, 0],
69769 "mediumaquamarine": [102, 205, 170],
69770 "mediumblue": [0, 0, 205],
69771 "mediumorchid": [186, 85, 211],
69772 "mediumpurple": [147, 112, 219],
69773 "mediumseagreen": [60, 179, 113],
69774 "mediumslateblue": [123, 104, 238],
69775 "mediumspringgreen": [0, 250, 154],
69776 "mediumturquoise": [72, 209, 204],
69777 "mediumvioletred": [199, 21, 133],
69778 "midnightblue": [25, 25, 112],
69779 "mintcream": [245, 255, 250],
69780 "mistyrose": [255, 228, 225],
69781 "moccasin": [255, 228, 181],
69782 "navajowhite": [255, 222, 173],
69783 "navy": [0, 0, 128],
69784 "oldlace": [253, 245, 230],
69785 "olive": [128, 128, 0],
69786 "olivedrab": [107, 142, 35],
69787 "orange": [255, 165, 0],
69788 "orangered": [255, 69, 0],
69789 "orchid": [218, 112, 214],
69790 "palegoldenrod": [238, 232, 170],
69791 "palegreen": [152, 251, 152],
69792 "paleturquoise": [175, 238, 238],
69793 "palevioletred": [219, 112, 147],
69794 "papayawhip": [255, 239, 213],
69795 "peachpuff": [255, 218, 185],
69796 "peru": [205, 133, 63],
69797 "pink": [255, 192, 203],
69798 "plum": [221, 160, 221],
69799 "powderblue": [176, 224, 230],
69800 "purple": [128, 0, 128],
69801 "rebeccapurple": [102, 51, 153],
69802 "red": [255, 0, 0],
69803 "rosybrown": [188, 143, 143],
69804 "royalblue": [65, 105, 225],
69805 "saddlebrown": [139, 69, 19],
69806 "salmon": [250, 128, 114],
69807 "sandybrown": [244, 164, 96],
69808 "seagreen": [46, 139, 87],
69809 "seashell": [255, 245, 238],
69810 "sienna": [160, 82, 45],
69811 "silver": [192, 192, 192],
69812 "skyblue": [135, 206, 235],
69813 "slateblue": [106, 90, 205],
69814 "slategray": [112, 128, 144],
69815 "slategrey": [112, 128, 144],
69816 "snow": [255, 250, 250],
69817 "springgreen": [0, 255, 127],
69818 "steelblue": [70, 130, 180],
69819 "tan": [210, 180, 140],
69820 "teal": [0, 128, 128],
69821 "thistle": [216, 191, 216],
69822 "tomato": [255, 99, 71],
69823 "turquoise": [64, 224, 208],
69824 "violet": [238, 130, 238],
69825 "wheat": [245, 222, 179],
69826 "white": [255, 255, 255],
69827 "whitesmoke": [245, 245, 245],
69828 "yellow": [255, 255, 0],
69829 "yellowgreen": [154, 205, 50]
69830};
69831
69832/* MIT license */
69833
69834var cssKeywords = colorName;
69835
69836// NOTE: conversions should only return primitive values (i.e. arrays, or
69837// values that give correct `typeof` results).
69838// do not use box values types (i.e. Number(), String(), etc.)
69839
69840var reverseKeywords = {};
69841for (var key in cssKeywords) {
69842 if (cssKeywords.hasOwnProperty(key)) {
69843 reverseKeywords[cssKeywords[key]] = key;
69844 }
69845}
69846
69847var convert$1 = conversions$2.exports = {
69848 rgb: {channels: 3, labels: 'rgb'},
69849 hsl: {channels: 3, labels: 'hsl'},
69850 hsv: {channels: 3, labels: 'hsv'},
69851 hwb: {channels: 3, labels: 'hwb'},
69852 cmyk: {channels: 4, labels: 'cmyk'},
69853 xyz: {channels: 3, labels: 'xyz'},
69854 lab: {channels: 3, labels: 'lab'},
69855 lch: {channels: 3, labels: 'lch'},
69856 hex: {channels: 1, labels: ['hex']},
69857 keyword: {channels: 1, labels: ['keyword']},
69858 ansi16: {channels: 1, labels: ['ansi16']},
69859 ansi256: {channels: 1, labels: ['ansi256']},
69860 hcg: {channels: 3, labels: ['h', 'c', 'g']},
69861 apple: {channels: 3, labels: ['r16', 'g16', 'b16']},
69862 gray: {channels: 1, labels: ['gray']}
69863};
69864
69865// hide .channels and .labels properties
69866for (var model in convert$1) {
69867 if (convert$1.hasOwnProperty(model)) {
69868 if (!('channels' in convert$1[model])) {
69869 throw new Error('missing channels property: ' + model);
69870 }
69871
69872 if (!('labels' in convert$1[model])) {
69873 throw new Error('missing channel labels property: ' + model);
69874 }
69875
69876 if (convert$1[model].labels.length !== convert$1[model].channels) {
69877 throw new Error('channel and label counts mismatch: ' + model);
69878 }
69879
69880 var channels = convert$1[model].channels;
69881 var labels = convert$1[model].labels;
69882 delete convert$1[model].channels;
69883 delete convert$1[model].labels;
69884 Object.defineProperty(convert$1[model], 'channels', {value: channels});
69885 Object.defineProperty(convert$1[model], 'labels', {value: labels});
69886 }
69887}
69888
69889convert$1.rgb.hsl = function (rgb) {
69890 var r = rgb[0] / 255;
69891 var g = rgb[1] / 255;
69892 var b = rgb[2] / 255;
69893 var min = Math.min(r, g, b);
69894 var max = Math.max(r, g, b);
69895 var delta = max - min;
69896 var h;
69897 var s;
69898 var l;
69899
69900 if (max === min) {
69901 h = 0;
69902 } else if (r === max) {
69903 h = (g - b) / delta;
69904 } else if (g === max) {
69905 h = 2 + (b - r) / delta;
69906 } else if (b === max) {
69907 h = 4 + (r - g) / delta;
69908 }
69909
69910 h = Math.min(h * 60, 360);
69911
69912 if (h < 0) {
69913 h += 360;
69914 }
69915
69916 l = (min + max) / 2;
69917
69918 if (max === min) {
69919 s = 0;
69920 } else if (l <= 0.5) {
69921 s = delta / (max + min);
69922 } else {
69923 s = delta / (2 - max - min);
69924 }
69925
69926 return [h, s * 100, l * 100];
69927};
69928
69929convert$1.rgb.hsv = function (rgb) {
69930 var rdif;
69931 var gdif;
69932 var bdif;
69933 var h;
69934 var s;
69935
69936 var r = rgb[0] / 255;
69937 var g = rgb[1] / 255;
69938 var b = rgb[2] / 255;
69939 var v = Math.max(r, g, b);
69940 var diff = v - Math.min(r, g, b);
69941 var diffc = function (c) {
69942 return (v - c) / 6 / diff + 1 / 2;
69943 };
69944
69945 if (diff === 0) {
69946 h = s = 0;
69947 } else {
69948 s = diff / v;
69949 rdif = diffc(r);
69950 gdif = diffc(g);
69951 bdif = diffc(b);
69952
69953 if (r === v) {
69954 h = bdif - gdif;
69955 } else if (g === v) {
69956 h = (1 / 3) + rdif - bdif;
69957 } else if (b === v) {
69958 h = (2 / 3) + gdif - rdif;
69959 }
69960 if (h < 0) {
69961 h += 1;
69962 } else if (h > 1) {
69963 h -= 1;
69964 }
69965 }
69966
69967 return [
69968 h * 360,
69969 s * 100,
69970 v * 100
69971 ];
69972};
69973
69974convert$1.rgb.hwb = function (rgb) {
69975 var r = rgb[0];
69976 var g = rgb[1];
69977 var b = rgb[2];
69978 var h = convert$1.rgb.hsl(rgb)[0];
69979 var w = 1 / 255 * Math.min(r, Math.min(g, b));
69980
69981 b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
69982
69983 return [h, w * 100, b * 100];
69984};
69985
69986convert$1.rgb.cmyk = function (rgb) {
69987 var r = rgb[0] / 255;
69988 var g = rgb[1] / 255;
69989 var b = rgb[2] / 255;
69990 var c;
69991 var m;
69992 var y;
69993 var k;
69994
69995 k = Math.min(1 - r, 1 - g, 1 - b);
69996 c = (1 - r - k) / (1 - k) || 0;
69997 m = (1 - g - k) / (1 - k) || 0;
69998 y = (1 - b - k) / (1 - k) || 0;
69999
70000 return [c * 100, m * 100, y * 100, k * 100];
70001};
70002
70003/**
70004 * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
70005 * */
70006function comparativeDistance(x, y) {
70007 return (
70008 Math.pow(x[0] - y[0], 2) +
70009 Math.pow(x[1] - y[1], 2) +
70010 Math.pow(x[2] - y[2], 2)
70011 );
70012}
70013
70014convert$1.rgb.keyword = function (rgb) {
70015 var reversed = reverseKeywords[rgb];
70016 if (reversed) {
70017 return reversed;
70018 }
70019
70020 var currentClosestDistance = Infinity;
70021 var currentClosestKeyword;
70022
70023 for (var keyword in cssKeywords) {
70024 if (cssKeywords.hasOwnProperty(keyword)) {
70025 var value = cssKeywords[keyword];
70026
70027 // Compute comparative distance
70028 var distance = comparativeDistance(rgb, value);
70029
70030 // Check if its less, if so set as closest
70031 if (distance < currentClosestDistance) {
70032 currentClosestDistance = distance;
70033 currentClosestKeyword = keyword;
70034 }
70035 }
70036 }
70037
70038 return currentClosestKeyword;
70039};
70040
70041convert$1.keyword.rgb = function (keyword) {
70042 return cssKeywords[keyword];
70043};
70044
70045convert$1.rgb.xyz = function (rgb) {
70046 var r = rgb[0] / 255;
70047 var g = rgb[1] / 255;
70048 var b = rgb[2] / 255;
70049
70050 // assume sRGB
70051 r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92);
70052 g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92);
70053 b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92);
70054
70055 var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
70056 var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
70057 var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
70058
70059 return [x * 100, y * 100, z * 100];
70060};
70061
70062convert$1.rgb.lab = function (rgb) {
70063 var xyz = convert$1.rgb.xyz(rgb);
70064 var x = xyz[0];
70065 var y = xyz[1];
70066 var z = xyz[2];
70067 var l;
70068 var a;
70069 var b;
70070
70071 x /= 95.047;
70072 y /= 100;
70073 z /= 108.883;
70074
70075 x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);
70076 y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);
70077 z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);
70078
70079 l = (116 * y) - 16;
70080 a = 500 * (x - y);
70081 b = 200 * (y - z);
70082
70083 return [l, a, b];
70084};
70085
70086convert$1.hsl.rgb = function (hsl) {
70087 var h = hsl[0] / 360;
70088 var s = hsl[1] / 100;
70089 var l = hsl[2] / 100;
70090 var t1;
70091 var t2;
70092 var t3;
70093 var rgb;
70094 var val;
70095
70096 if (s === 0) {
70097 val = l * 255;
70098 return [val, val, val];
70099 }
70100
70101 if (l < 0.5) {
70102 t2 = l * (1 + s);
70103 } else {
70104 t2 = l + s - l * s;
70105 }
70106
70107 t1 = 2 * l - t2;
70108
70109 rgb = [0, 0, 0];
70110 for (var i = 0; i < 3; i++) {
70111 t3 = h + 1 / 3 * -(i - 1);
70112 if (t3 < 0) {
70113 t3++;
70114 }
70115 if (t3 > 1) {
70116 t3--;
70117 }
70118
70119 if (6 * t3 < 1) {
70120 val = t1 + (t2 - t1) * 6 * t3;
70121 } else if (2 * t3 < 1) {
70122 val = t2;
70123 } else if (3 * t3 < 2) {
70124 val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
70125 } else {
70126 val = t1;
70127 }
70128
70129 rgb[i] = val * 255;
70130 }
70131
70132 return rgb;
70133};
70134
70135convert$1.hsl.hsv = function (hsl) {
70136 var h = hsl[0];
70137 var s = hsl[1] / 100;
70138 var l = hsl[2] / 100;
70139 var smin = s;
70140 var lmin = Math.max(l, 0.01);
70141 var sv;
70142 var v;
70143
70144 l *= 2;
70145 s *= (l <= 1) ? l : 2 - l;
70146 smin *= lmin <= 1 ? lmin : 2 - lmin;
70147 v = (l + s) / 2;
70148 sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);
70149
70150 return [h, sv * 100, v * 100];
70151};
70152
70153convert$1.hsv.rgb = function (hsv) {
70154 var h = hsv[0] / 60;
70155 var s = hsv[1] / 100;
70156 var v = hsv[2] / 100;
70157 var hi = Math.floor(h) % 6;
70158
70159 var f = h - Math.floor(h);
70160 var p = 255 * v * (1 - s);
70161 var q = 255 * v * (1 - (s * f));
70162 var t = 255 * v * (1 - (s * (1 - f)));
70163 v *= 255;
70164
70165 switch (hi) {
70166 case 0:
70167 return [v, t, p];
70168 case 1:
70169 return [q, v, p];
70170 case 2:
70171 return [p, v, t];
70172 case 3:
70173 return [p, q, v];
70174 case 4:
70175 return [t, p, v];
70176 case 5:
70177 return [v, p, q];
70178 }
70179};
70180
70181convert$1.hsv.hsl = function (hsv) {
70182 var h = hsv[0];
70183 var s = hsv[1] / 100;
70184 var v = hsv[2] / 100;
70185 var vmin = Math.max(v, 0.01);
70186 var lmin;
70187 var sl;
70188 var l;
70189
70190 l = (2 - s) * v;
70191 lmin = (2 - s) * vmin;
70192 sl = s * vmin;
70193 sl /= (lmin <= 1) ? lmin : 2 - lmin;
70194 sl = sl || 0;
70195 l /= 2;
70196
70197 return [h, sl * 100, l * 100];
70198};
70199
70200// http://dev.w3.org/csswg/css-color/#hwb-to-rgb
70201convert$1.hwb.rgb = function (hwb) {
70202 var h = hwb[0] / 360;
70203 var wh = hwb[1] / 100;
70204 var bl = hwb[2] / 100;
70205 var ratio = wh + bl;
70206 var i;
70207 var v;
70208 var f;
70209 var n;
70210
70211 // wh + bl cant be > 1
70212 if (ratio > 1) {
70213 wh /= ratio;
70214 bl /= ratio;
70215 }
70216
70217 i = Math.floor(6 * h);
70218 v = 1 - bl;
70219 f = 6 * h - i;
70220
70221 if ((i & 0x01) !== 0) {
70222 f = 1 - f;
70223 }
70224
70225 n = wh + f * (v - wh); // linear interpolation
70226
70227 var r;
70228 var g;
70229 var b;
70230 switch (i) {
70231 default:
70232 case 6:
70233 case 0: r = v; g = n; b = wh; break;
70234 case 1: r = n; g = v; b = wh; break;
70235 case 2: r = wh; g = v; b = n; break;
70236 case 3: r = wh; g = n; b = v; break;
70237 case 4: r = n; g = wh; b = v; break;
70238 case 5: r = v; g = wh; b = n; break;
70239 }
70240
70241 return [r * 255, g * 255, b * 255];
70242};
70243
70244convert$1.cmyk.rgb = function (cmyk) {
70245 var c = cmyk[0] / 100;
70246 var m = cmyk[1] / 100;
70247 var y = cmyk[2] / 100;
70248 var k = cmyk[3] / 100;
70249 var r;
70250 var g;
70251 var b;
70252
70253 r = 1 - Math.min(1, c * (1 - k) + k);
70254 g = 1 - Math.min(1, m * (1 - k) + k);
70255 b = 1 - Math.min(1, y * (1 - k) + k);
70256
70257 return [r * 255, g * 255, b * 255];
70258};
70259
70260convert$1.xyz.rgb = function (xyz) {
70261 var x = xyz[0] / 100;
70262 var y = xyz[1] / 100;
70263 var z = xyz[2] / 100;
70264 var r;
70265 var g;
70266 var b;
70267
70268 r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
70269 g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
70270 b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
70271
70272 // assume sRGB
70273 r = r > 0.0031308
70274 ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055)
70275 : r * 12.92;
70276
70277 g = g > 0.0031308
70278 ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055)
70279 : g * 12.92;
70280
70281 b = b > 0.0031308
70282 ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055)
70283 : b * 12.92;
70284
70285 r = Math.min(Math.max(0, r), 1);
70286 g = Math.min(Math.max(0, g), 1);
70287 b = Math.min(Math.max(0, b), 1);
70288
70289 return [r * 255, g * 255, b * 255];
70290};
70291
70292convert$1.xyz.lab = function (xyz) {
70293 var x = xyz[0];
70294 var y = xyz[1];
70295 var z = xyz[2];
70296 var l;
70297 var a;
70298 var b;
70299
70300 x /= 95.047;
70301 y /= 100;
70302 z /= 108.883;
70303
70304 x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);
70305 y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);
70306 z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);
70307
70308 l = (116 * y) - 16;
70309 a = 500 * (x - y);
70310 b = 200 * (y - z);
70311
70312 return [l, a, b];
70313};
70314
70315convert$1.lab.xyz = function (lab) {
70316 var l = lab[0];
70317 var a = lab[1];
70318 var b = lab[2];
70319 var x;
70320 var y;
70321 var z;
70322
70323 y = (l + 16) / 116;
70324 x = a / 500 + y;
70325 z = y - b / 200;
70326
70327 var y2 = Math.pow(y, 3);
70328 var x2 = Math.pow(x, 3);
70329 var z2 = Math.pow(z, 3);
70330 y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
70331 x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
70332 z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
70333
70334 x *= 95.047;
70335 y *= 100;
70336 z *= 108.883;
70337
70338 return [x, y, z];
70339};
70340
70341convert$1.lab.lch = function (lab) {
70342 var l = lab[0];
70343 var a = lab[1];
70344 var b = lab[2];
70345 var hr;
70346 var h;
70347 var c;
70348
70349 hr = Math.atan2(b, a);
70350 h = hr * 360 / 2 / Math.PI;
70351
70352 if (h < 0) {
70353 h += 360;
70354 }
70355
70356 c = Math.sqrt(a * a + b * b);
70357
70358 return [l, c, h];
70359};
70360
70361convert$1.lch.lab = function (lch) {
70362 var l = lch[0];
70363 var c = lch[1];
70364 var h = lch[2];
70365 var a;
70366 var b;
70367 var hr;
70368
70369 hr = h / 360 * 2 * Math.PI;
70370 a = c * Math.cos(hr);
70371 b = c * Math.sin(hr);
70372
70373 return [l, a, b];
70374};
70375
70376convert$1.rgb.ansi16 = function (args) {
70377 var r = args[0];
70378 var g = args[1];
70379 var b = args[2];
70380 var value = 1 in arguments ? arguments[1] : convert$1.rgb.hsv(args)[2]; // hsv -> ansi16 optimization
70381
70382 value = Math.round(value / 50);
70383
70384 if (value === 0) {
70385 return 30;
70386 }
70387
70388 var ansi = 30
70389 + ((Math.round(b / 255) << 2)
70390 | (Math.round(g / 255) << 1)
70391 | Math.round(r / 255));
70392
70393 if (value === 2) {
70394 ansi += 60;
70395 }
70396
70397 return ansi;
70398};
70399
70400convert$1.hsv.ansi16 = function (args) {
70401 // optimization here; we already know the value and don't need to get
70402 // it converted for us.
70403 return convert$1.rgb.ansi16(convert$1.hsv.rgb(args), args[2]);
70404};
70405
70406convert$1.rgb.ansi256 = function (args) {
70407 var r = args[0];
70408 var g = args[1];
70409 var b = args[2];
70410
70411 // we use the extended greyscale palette here, with the exception of
70412 // black and white. normal palette only has 4 greyscale shades.
70413 if (r === g && g === b) {
70414 if (r < 8) {
70415 return 16;
70416 }
70417
70418 if (r > 248) {
70419 return 231;
70420 }
70421
70422 return Math.round(((r - 8) / 247) * 24) + 232;
70423 }
70424
70425 var ansi = 16
70426 + (36 * Math.round(r / 255 * 5))
70427 + (6 * Math.round(g / 255 * 5))
70428 + Math.round(b / 255 * 5);
70429
70430 return ansi;
70431};
70432
70433convert$1.ansi16.rgb = function (args) {
70434 var color = args % 10;
70435
70436 // handle greyscale
70437 if (color === 0 || color === 7) {
70438 if (args > 50) {
70439 color += 3.5;
70440 }
70441
70442 color = color / 10.5 * 255;
70443
70444 return [color, color, color];
70445 }
70446
70447 var mult = (~~(args > 50) + 1) * 0.5;
70448 var r = ((color & 1) * mult) * 255;
70449 var g = (((color >> 1) & 1) * mult) * 255;
70450 var b = (((color >> 2) & 1) * mult) * 255;
70451
70452 return [r, g, b];
70453};
70454
70455convert$1.ansi256.rgb = function (args) {
70456 // handle greyscale
70457 if (args >= 232) {
70458 var c = (args - 232) * 10 + 8;
70459 return [c, c, c];
70460 }
70461
70462 args -= 16;
70463
70464 var rem;
70465 var r = Math.floor(args / 36) / 5 * 255;
70466 var g = Math.floor((rem = args % 36) / 6) / 5 * 255;
70467 var b = (rem % 6) / 5 * 255;
70468
70469 return [r, g, b];
70470};
70471
70472convert$1.rgb.hex = function (args) {
70473 var integer = ((Math.round(args[0]) & 0xFF) << 16)
70474 + ((Math.round(args[1]) & 0xFF) << 8)
70475 + (Math.round(args[2]) & 0xFF);
70476
70477 var string = integer.toString(16).toUpperCase();
70478 return '000000'.substring(string.length) + string;
70479};
70480
70481convert$1.hex.rgb = function (args) {
70482 var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
70483 if (!match) {
70484 return [0, 0, 0];
70485 }
70486
70487 var colorString = match[0];
70488
70489 if (match[0].length === 3) {
70490 colorString = colorString.split('').map(function (char) {
70491 return char + char;
70492 }).join('');
70493 }
70494
70495 var integer = parseInt(colorString, 16);
70496 var r = (integer >> 16) & 0xFF;
70497 var g = (integer >> 8) & 0xFF;
70498 var b = integer & 0xFF;
70499
70500 return [r, g, b];
70501};
70502
70503convert$1.rgb.hcg = function (rgb) {
70504 var r = rgb[0] / 255;
70505 var g = rgb[1] / 255;
70506 var b = rgb[2] / 255;
70507 var max = Math.max(Math.max(r, g), b);
70508 var min = Math.min(Math.min(r, g), b);
70509 var chroma = (max - min);
70510 var grayscale;
70511 var hue;
70512
70513 if (chroma < 1) {
70514 grayscale = min / (1 - chroma);
70515 } else {
70516 grayscale = 0;
70517 }
70518
70519 if (chroma <= 0) {
70520 hue = 0;
70521 } else
70522 if (max === r) {
70523 hue = ((g - b) / chroma) % 6;
70524 } else
70525 if (max === g) {
70526 hue = 2 + (b - r) / chroma;
70527 } else {
70528 hue = 4 + (r - g) / chroma + 4;
70529 }
70530
70531 hue /= 6;
70532 hue %= 1;
70533
70534 return [hue * 360, chroma * 100, grayscale * 100];
70535};
70536
70537convert$1.hsl.hcg = function (hsl) {
70538 var s = hsl[1] / 100;
70539 var l = hsl[2] / 100;
70540 var c = 1;
70541 var f = 0;
70542
70543 if (l < 0.5) {
70544 c = 2.0 * s * l;
70545 } else {
70546 c = 2.0 * s * (1.0 - l);
70547 }
70548
70549 if (c < 1.0) {
70550 f = (l - 0.5 * c) / (1.0 - c);
70551 }
70552
70553 return [hsl[0], c * 100, f * 100];
70554};
70555
70556convert$1.hsv.hcg = function (hsv) {
70557 var s = hsv[1] / 100;
70558 var v = hsv[2] / 100;
70559
70560 var c = s * v;
70561 var f = 0;
70562
70563 if (c < 1.0) {
70564 f = (v - c) / (1 - c);
70565 }
70566
70567 return [hsv[0], c * 100, f * 100];
70568};
70569
70570convert$1.hcg.rgb = function (hcg) {
70571 var h = hcg[0] / 360;
70572 var c = hcg[1] / 100;
70573 var g = hcg[2] / 100;
70574
70575 if (c === 0.0) {
70576 return [g * 255, g * 255, g * 255];
70577 }
70578
70579 var pure = [0, 0, 0];
70580 var hi = (h % 1) * 6;
70581 var v = hi % 1;
70582 var w = 1 - v;
70583 var mg = 0;
70584
70585 switch (Math.floor(hi)) {
70586 case 0:
70587 pure[0] = 1; pure[1] = v; pure[2] = 0; break;
70588 case 1:
70589 pure[0] = w; pure[1] = 1; pure[2] = 0; break;
70590 case 2:
70591 pure[0] = 0; pure[1] = 1; pure[2] = v; break;
70592 case 3:
70593 pure[0] = 0; pure[1] = w; pure[2] = 1; break;
70594 case 4:
70595 pure[0] = v; pure[1] = 0; pure[2] = 1; break;
70596 default:
70597 pure[0] = 1; pure[1] = 0; pure[2] = w;
70598 }
70599
70600 mg = (1.0 - c) * g;
70601
70602 return [
70603 (c * pure[0] + mg) * 255,
70604 (c * pure[1] + mg) * 255,
70605 (c * pure[2] + mg) * 255
70606 ];
70607};
70608
70609convert$1.hcg.hsv = function (hcg) {
70610 var c = hcg[1] / 100;
70611 var g = hcg[2] / 100;
70612
70613 var v = c + g * (1.0 - c);
70614 var f = 0;
70615
70616 if (v > 0.0) {
70617 f = c / v;
70618 }
70619
70620 return [hcg[0], f * 100, v * 100];
70621};
70622
70623convert$1.hcg.hsl = function (hcg) {
70624 var c = hcg[1] / 100;
70625 var g = hcg[2] / 100;
70626
70627 var l = g * (1.0 - c) + 0.5 * c;
70628 var s = 0;
70629
70630 if (l > 0.0 && l < 0.5) {
70631 s = c / (2 * l);
70632 } else
70633 if (l >= 0.5 && l < 1.0) {
70634 s = c / (2 * (1 - l));
70635 }
70636
70637 return [hcg[0], s * 100, l * 100];
70638};
70639
70640convert$1.hcg.hwb = function (hcg) {
70641 var c = hcg[1] / 100;
70642 var g = hcg[2] / 100;
70643 var v = c + g * (1.0 - c);
70644 return [hcg[0], (v - c) * 100, (1 - v) * 100];
70645};
70646
70647convert$1.hwb.hcg = function (hwb) {
70648 var w = hwb[1] / 100;
70649 var b = hwb[2] / 100;
70650 var v = 1 - b;
70651 var c = v - w;
70652 var g = 0;
70653
70654 if (c < 1) {
70655 g = (v - c) / (1 - c);
70656 }
70657
70658 return [hwb[0], c * 100, g * 100];
70659};
70660
70661convert$1.apple.rgb = function (apple) {
70662 return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];
70663};
70664
70665convert$1.rgb.apple = function (rgb) {
70666 return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];
70667};
70668
70669convert$1.gray.rgb = function (args) {
70670 return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
70671};
70672
70673convert$1.gray.hsl = convert$1.gray.hsv = function (args) {
70674 return [0, 0, args[0]];
70675};
70676
70677convert$1.gray.hwb = function (gray) {
70678 return [0, 100, gray[0]];
70679};
70680
70681convert$1.gray.cmyk = function (gray) {
70682 return [0, 0, 0, gray[0]];
70683};
70684
70685convert$1.gray.lab = function (gray) {
70686 return [gray[0], 0, 0];
70687};
70688
70689convert$1.gray.hex = function (gray) {
70690 var val = Math.round(gray[0] / 100 * 255) & 0xFF;
70691 var integer = (val << 16) + (val << 8) + val;
70692
70693 var string = integer.toString(16).toUpperCase();
70694 return '000000'.substring(string.length) + string;
70695};
70696
70697convert$1.rgb.gray = function (rgb) {
70698 var val = (rgb[0] + rgb[1] + rgb[2]) / 3;
70699 return [val / 255 * 100];
70700};
70701
70702var conversions$1 = conversions$2.exports;
70703
70704/*
70705 this function routes a model to all other models.
70706
70707 all functions that are routed have a property `.conversion` attached
70708 to the returned synthetic function. This property is an array
70709 of strings, each with the steps in between the 'from' and 'to'
70710 color models (inclusive).
70711
70712 conversions that are not possible simply are not included.
70713*/
70714
70715function buildGraph() {
70716 var graph = {};
70717 // https://jsperf.com/object-keys-vs-for-in-with-closure/3
70718 var models = Object.keys(conversions$1);
70719
70720 for (var len = models.length, i = 0; i < len; i++) {
70721 graph[models[i]] = {
70722 // http://jsperf.com/1-vs-infinity
70723 // micro-opt, but this is simple.
70724 distance: -1,
70725 parent: null
70726 };
70727 }
70728
70729 return graph;
70730}
70731
70732// https://en.wikipedia.org/wiki/Breadth-first_search
70733function deriveBFS(fromModel) {
70734 var graph = buildGraph();
70735 var queue = [fromModel]; // unshift -> queue -> pop
70736
70737 graph[fromModel].distance = 0;
70738
70739 while (queue.length) {
70740 var current = queue.pop();
70741 var adjacents = Object.keys(conversions$1[current]);
70742
70743 for (var len = adjacents.length, i = 0; i < len; i++) {
70744 var adjacent = adjacents[i];
70745 var node = graph[adjacent];
70746
70747 if (node.distance === -1) {
70748 node.distance = graph[current].distance + 1;
70749 node.parent = current;
70750 queue.unshift(adjacent);
70751 }
70752 }
70753 }
70754
70755 return graph;
70756}
70757
70758function link(from, to) {
70759 return function (args) {
70760 return to(from(args));
70761 };
70762}
70763
70764function wrapConversion(toModel, graph) {
70765 var path = [graph[toModel].parent, toModel];
70766 var fn = conversions$1[graph[toModel].parent][toModel];
70767
70768 var cur = graph[toModel].parent;
70769 while (graph[cur].parent) {
70770 path.unshift(graph[cur].parent);
70771 fn = link(conversions$1[graph[cur].parent][cur], fn);
70772 cur = graph[cur].parent;
70773 }
70774
70775 fn.conversion = path;
70776 return fn;
70777}
70778
70779var route$1 = function (fromModel) {
70780 var graph = deriveBFS(fromModel);
70781 var conversion = {};
70782
70783 var models = Object.keys(graph);
70784 for (var len = models.length, i = 0; i < len; i++) {
70785 var toModel = models[i];
70786 var node = graph[toModel];
70787
70788 if (node.parent === null) {
70789 // no possible conversion, or this node is the source model.
70790 continue;
70791 }
70792
70793 conversion[toModel] = wrapConversion(toModel, graph);
70794 }
70795
70796 return conversion;
70797};
70798
70799var conversions = conversions$2.exports;
70800var route = route$1;
70801
70802var convert = {};
70803
70804var models = Object.keys(conversions);
70805
70806function wrapRaw(fn) {
70807 var wrappedFn = function (args) {
70808 if (args === undefined || args === null) {
70809 return args;
70810 }
70811
70812 if (arguments.length > 1) {
70813 args = Array.prototype.slice.call(arguments);
70814 }
70815
70816 return fn(args);
70817 };
70818
70819 // preserve .conversion property if there is one
70820 if ('conversion' in fn) {
70821 wrappedFn.conversion = fn.conversion;
70822 }
70823
70824 return wrappedFn;
70825}
70826
70827function wrapRounded(fn) {
70828 var wrappedFn = function (args) {
70829 if (args === undefined || args === null) {
70830 return args;
70831 }
70832
70833 if (arguments.length > 1) {
70834 args = Array.prototype.slice.call(arguments);
70835 }
70836
70837 var result = fn(args);
70838
70839 // we're assuming the result is an array here.
70840 // see notice in conversions.js; don't use box types
70841 // in conversion functions.
70842 if (typeof result === 'object') {
70843 for (var len = result.length, i = 0; i < len; i++) {
70844 result[i] = Math.round(result[i]);
70845 }
70846 }
70847
70848 return result;
70849 };
70850
70851 // preserve .conversion property if there is one
70852 if ('conversion' in fn) {
70853 wrappedFn.conversion = fn.conversion;
70854 }
70855
70856 return wrappedFn;
70857}
70858
70859models.forEach(function (fromModel) {
70860 convert[fromModel] = {};
70861
70862 Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});
70863 Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});
70864
70865 var routes = route(fromModel);
70866 var routeModels = Object.keys(routes);
70867
70868 routeModels.forEach(function (toModel) {
70869 var fn = routes[toModel];
70870
70871 convert[fromModel][toModel] = wrapRounded(fn);
70872 convert[fromModel][toModel].raw = wrapRaw(fn);
70873 });
70874});
70875
70876var colorConvert = convert;
70877
70878(function (module) {
70879const colorConvert$1 = colorConvert;
70880
70881const wrapAnsi16 = (fn, offset) => function () {
70882 const code = fn.apply(colorConvert$1, arguments);
70883 return `\u001B[${code + offset}m`;
70884};
70885
70886const wrapAnsi256 = (fn, offset) => function () {
70887 const code = fn.apply(colorConvert$1, arguments);
70888 return `\u001B[${38 + offset};5;${code}m`;
70889};
70890
70891const wrapAnsi16m = (fn, offset) => function () {
70892 const rgb = fn.apply(colorConvert$1, arguments);
70893 return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
70894};
70895
70896function assembleStyles() {
70897 const codes = new Map();
70898 const styles = {
70899 modifier: {
70900 reset: [0, 0],
70901 // 21 isn't widely supported and 22 does the same thing
70902 bold: [1, 22],
70903 dim: [2, 22],
70904 italic: [3, 23],
70905 underline: [4, 24],
70906 inverse: [7, 27],
70907 hidden: [8, 28],
70908 strikethrough: [9, 29]
70909 },
70910 color: {
70911 black: [30, 39],
70912 red: [31, 39],
70913 green: [32, 39],
70914 yellow: [33, 39],
70915 blue: [34, 39],
70916 magenta: [35, 39],
70917 cyan: [36, 39],
70918 white: [37, 39],
70919 gray: [90, 39],
70920
70921 // Bright color
70922 redBright: [91, 39],
70923 greenBright: [92, 39],
70924 yellowBright: [93, 39],
70925 blueBright: [94, 39],
70926 magentaBright: [95, 39],
70927 cyanBright: [96, 39],
70928 whiteBright: [97, 39]
70929 },
70930 bgColor: {
70931 bgBlack: [40, 49],
70932 bgRed: [41, 49],
70933 bgGreen: [42, 49],
70934 bgYellow: [43, 49],
70935 bgBlue: [44, 49],
70936 bgMagenta: [45, 49],
70937 bgCyan: [46, 49],
70938 bgWhite: [47, 49],
70939
70940 // Bright color
70941 bgBlackBright: [100, 49],
70942 bgRedBright: [101, 49],
70943 bgGreenBright: [102, 49],
70944 bgYellowBright: [103, 49],
70945 bgBlueBright: [104, 49],
70946 bgMagentaBright: [105, 49],
70947 bgCyanBright: [106, 49],
70948 bgWhiteBright: [107, 49]
70949 }
70950 };
70951
70952 // Fix humans
70953 styles.color.grey = styles.color.gray;
70954
70955 for (const groupName of Object.keys(styles)) {
70956 const group = styles[groupName];
70957
70958 for (const styleName of Object.keys(group)) {
70959 const style = group[styleName];
70960
70961 styles[styleName] = {
70962 open: `\u001B[${style[0]}m`,
70963 close: `\u001B[${style[1]}m`
70964 };
70965
70966 group[styleName] = styles[styleName];
70967
70968 codes.set(style[0], style[1]);
70969 }
70970
70971 Object.defineProperty(styles, groupName, {
70972 value: group,
70973 enumerable: false
70974 });
70975
70976 Object.defineProperty(styles, 'codes', {
70977 value: codes,
70978 enumerable: false
70979 });
70980 }
70981
70982 const ansi2ansi = n => n;
70983 const rgb2rgb = (r, g, b) => [r, g, b];
70984
70985 styles.color.close = '\u001B[39m';
70986 styles.bgColor.close = '\u001B[49m';
70987
70988 styles.color.ansi = {
70989 ansi: wrapAnsi16(ansi2ansi, 0)
70990 };
70991 styles.color.ansi256 = {
70992 ansi256: wrapAnsi256(ansi2ansi, 0)
70993 };
70994 styles.color.ansi16m = {
70995 rgb: wrapAnsi16m(rgb2rgb, 0)
70996 };
70997
70998 styles.bgColor.ansi = {
70999 ansi: wrapAnsi16(ansi2ansi, 10)
71000 };
71001 styles.bgColor.ansi256 = {
71002 ansi256: wrapAnsi256(ansi2ansi, 10)
71003 };
71004 styles.bgColor.ansi16m = {
71005 rgb: wrapAnsi16m(rgb2rgb, 10)
71006 };
71007
71008 for (let key of Object.keys(colorConvert$1)) {
71009 if (typeof colorConvert$1[key] !== 'object') {
71010 continue;
71011 }
71012
71013 const suite = colorConvert$1[key];
71014
71015 if (key === 'ansi16') {
71016 key = 'ansi';
71017 }
71018
71019 if ('ansi16' in suite) {
71020 styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0);
71021 styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10);
71022 }
71023
71024 if ('ansi256' in suite) {
71025 styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0);
71026 styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10);
71027 }
71028
71029 if ('rgb' in suite) {
71030 styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0);
71031 styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10);
71032 }
71033 }
71034
71035 return styles;
71036}
71037
71038// Make the export immutable
71039Object.defineProperty(module, 'exports', {
71040 enumerable: true,
71041 get: assembleStyles
71042});
71043}(ansiStyles));
71044
71045var hasFlag$1 = (flag, argv) => {
71046 argv = argv || process.argv;
71047 const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');
71048 const pos = argv.indexOf(prefix + flag);
71049 const terminatorPos = argv.indexOf('--');
71050 return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
71051};
71052
71053const os$2 = require$$0__default$1;
71054const hasFlag = hasFlag$1;
71055
71056const env = process.env;
71057
71058let forceColor;
71059if (hasFlag('no-color') ||
71060 hasFlag('no-colors') ||
71061 hasFlag('color=false')) {
71062 forceColor = false;
71063} else if (hasFlag('color') ||
71064 hasFlag('colors') ||
71065 hasFlag('color=true') ||
71066 hasFlag('color=always')) {
71067 forceColor = true;
71068}
71069if ('FORCE_COLOR' in env) {
71070 forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0;
71071}
71072
71073function translateLevel(level) {
71074 if (level === 0) {
71075 return false;
71076 }
71077
71078 return {
71079 level,
71080 hasBasic: true,
71081 has256: level >= 2,
71082 has16m: level >= 3
71083 };
71084}
71085
71086function supportsColor(stream) {
71087 if (forceColor === false) {
71088 return 0;
71089 }
71090
71091 if (hasFlag('color=16m') ||
71092 hasFlag('color=full') ||
71093 hasFlag('color=truecolor')) {
71094 return 3;
71095 }
71096
71097 if (hasFlag('color=256')) {
71098 return 2;
71099 }
71100
71101 if (stream && !stream.isTTY && forceColor !== true) {
71102 return 0;
71103 }
71104
71105 const min = forceColor ? 1 : 0;
71106
71107 if (process.platform === 'win32') {
71108 // Node.js 7.5.0 is the first version of Node.js to include a patch to
71109 // libuv that enables 256 color output on Windows. Anything earlier and it
71110 // won't work. However, here we target Node.js 8 at minimum as it is an LTS
71111 // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows
71112 // release that supports 256 colors. Windows 10 build 14931 is the first release
71113 // that supports 16m/TrueColor.
71114 const osRelease = os$2.release().split('.');
71115 if (
71116 Number(process.versions.node.split('.')[0]) >= 8 &&
71117 Number(osRelease[0]) >= 10 &&
71118 Number(osRelease[2]) >= 10586
71119 ) {
71120 return Number(osRelease[2]) >= 14931 ? 3 : 2;
71121 }
71122
71123 return 1;
71124 }
71125
71126 if ('CI' in env) {
71127 if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') {
71128 return 1;
71129 }
71130
71131 return min;
71132 }
71133
71134 if ('TEAMCITY_VERSION' in env) {
71135 return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
71136 }
71137
71138 if (env.COLORTERM === 'truecolor') {
71139 return 3;
71140 }
71141
71142 if ('TERM_PROGRAM' in env) {
71143 const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
71144
71145 switch (env.TERM_PROGRAM) {
71146 case 'iTerm.app':
71147 return version >= 3 ? 3 : 2;
71148 case 'Apple_Terminal':
71149 return 2;
71150 // No default
71151 }
71152 }
71153
71154 if (/-256(color)?$/i.test(env.TERM)) {
71155 return 2;
71156 }
71157
71158 if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
71159 return 1;
71160 }
71161
71162 if ('COLORTERM' in env) {
71163 return 1;
71164 }
71165
71166 if (env.TERM === 'dumb') {
71167 return min;
71168 }
71169
71170 return min;
71171}
71172
71173function getSupportLevel(stream) {
71174 const level = supportsColor(stream);
71175 return translateLevel(level);
71176}
71177
71178var supportsColor_1 = {
71179 supportsColor: getSupportLevel,
71180 stdout: getSupportLevel(process.stdout),
71181 stderr: getSupportLevel(process.stderr)
71182};
71183
71184const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
71185const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
71186const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
71187const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi;
71188
71189const ESCAPES = new Map([
71190 ['n', '\n'],
71191 ['r', '\r'],
71192 ['t', '\t'],
71193 ['b', '\b'],
71194 ['f', '\f'],
71195 ['v', '\v'],
71196 ['0', '\0'],
71197 ['\\', '\\'],
71198 ['e', '\u001B'],
71199 ['a', '\u0007']
71200]);
71201
71202function unescape$1(c) {
71203 if ((c[0] === 'u' && c.length === 5) || (c[0] === 'x' && c.length === 3)) {
71204 return String.fromCharCode(parseInt(c.slice(1), 16));
71205 }
71206
71207 return ESCAPES.get(c) || c;
71208}
71209
71210function parseArguments(name, args) {
71211 const results = [];
71212 const chunks = args.trim().split(/\s*,\s*/g);
71213 let matches;
71214
71215 for (const chunk of chunks) {
71216 if (!isNaN(chunk)) {
71217 results.push(Number(chunk));
71218 } else if ((matches = chunk.match(STRING_REGEX))) {
71219 results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape$1(escape) : chr));
71220 } else {
71221 throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
71222 }
71223 }
71224
71225 return results;
71226}
71227
71228function parseStyle(style) {
71229 STYLE_REGEX.lastIndex = 0;
71230
71231 const results = [];
71232 let matches;
71233
71234 while ((matches = STYLE_REGEX.exec(style)) !== null) {
71235 const name = matches[1];
71236
71237 if (matches[2]) {
71238 const args = parseArguments(name, matches[2]);
71239 results.push([name].concat(args));
71240 } else {
71241 results.push([name]);
71242 }
71243 }
71244
71245 return results;
71246}
71247
71248function buildStyle(chalk, styles) {
71249 const enabled = {};
71250
71251 for (const layer of styles) {
71252 for (const style of layer.styles) {
71253 enabled[style[0]] = layer.inverse ? null : style.slice(1);
71254 }
71255 }
71256
71257 let current = chalk;
71258 for (const styleName of Object.keys(enabled)) {
71259 if (Array.isArray(enabled[styleName])) {
71260 if (!(styleName in current)) {
71261 throw new Error(`Unknown Chalk style: ${styleName}`);
71262 }
71263
71264 if (enabled[styleName].length > 0) {
71265 current = current[styleName].apply(current, enabled[styleName]);
71266 } else {
71267 current = current[styleName];
71268 }
71269 }
71270 }
71271
71272 return current;
71273}
71274
71275var templates = (chalk, tmp) => {
71276 const styles = [];
71277 const chunks = [];
71278 let chunk = [];
71279
71280 // eslint-disable-next-line max-params
71281 tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => {
71282 if (escapeChar) {
71283 chunk.push(unescape$1(escapeChar));
71284 } else if (style) {
71285 const str = chunk.join('');
71286 chunk = [];
71287 chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str));
71288 styles.push({inverse, styles: parseStyle(style)});
71289 } else if (close) {
71290 if (styles.length === 0) {
71291 throw new Error('Found extraneous } in Chalk template literal');
71292 }
71293
71294 chunks.push(buildStyle(chalk, styles)(chunk.join('')));
71295 chunk = [];
71296 styles.pop();
71297 } else {
71298 chunk.push(chr);
71299 }
71300 });
71301
71302 chunks.push(chunk.join(''));
71303
71304 if (styles.length > 0) {
71305 const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
71306 throw new Error(errMsg);
71307 }
71308
71309 return chunks.join('');
71310};
71311
71312(function (module) {
71313const escapeStringRegexp$1 = escapeStringRegexp;
71314const ansiStyles$1 = ansiStyles.exports;
71315const stdoutColor = supportsColor_1.stdout;
71316
71317const template = templates;
71318
71319const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm');
71320
71321// `supportsColor.level` → `ansiStyles.color[name]` mapping
71322const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m'];
71323
71324// `color-convert` models to exclude from the Chalk API due to conflicts and such
71325const skipModels = new Set(['gray']);
71326
71327const styles = Object.create(null);
71328
71329function applyOptions(obj, options) {
71330 options = options || {};
71331
71332 // Detect level if not set manually
71333 const scLevel = stdoutColor ? stdoutColor.level : 0;
71334 obj.level = options.level === undefined ? scLevel : options.level;
71335 obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0;
71336}
71337
71338function Chalk(options) {
71339 // We check for this.template here since calling `chalk.constructor()`
71340 // by itself will have a `this` of a previously constructed chalk object
71341 if (!this || !(this instanceof Chalk) || this.template) {
71342 const chalk = {};
71343 applyOptions(chalk, options);
71344
71345 chalk.template = function () {
71346 const args = [].slice.call(arguments);
71347 return chalkTag.apply(null, [chalk.template].concat(args));
71348 };
71349
71350 Object.setPrototypeOf(chalk, Chalk.prototype);
71351 Object.setPrototypeOf(chalk.template, chalk);
71352
71353 chalk.template.constructor = Chalk;
71354
71355 return chalk.template;
71356 }
71357
71358 applyOptions(this, options);
71359}
71360
71361// Use bright blue on Windows as the normal blue color is illegible
71362if (isSimpleWindowsTerm) {
71363 ansiStyles$1.blue.open = '\u001B[94m';
71364}
71365
71366for (const key of Object.keys(ansiStyles$1)) {
71367 ansiStyles$1[key].closeRe = new RegExp(escapeStringRegexp$1(ansiStyles$1[key].close), 'g');
71368
71369 styles[key] = {
71370 get() {
71371 const codes = ansiStyles$1[key];
71372 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key);
71373 }
71374 };
71375}
71376
71377styles.visible = {
71378 get() {
71379 return build.call(this, this._styles || [], true, 'visible');
71380 }
71381};
71382
71383ansiStyles$1.color.closeRe = new RegExp(escapeStringRegexp$1(ansiStyles$1.color.close), 'g');
71384for (const model of Object.keys(ansiStyles$1.color.ansi)) {
71385 if (skipModels.has(model)) {
71386 continue;
71387 }
71388
71389 styles[model] = {
71390 get() {
71391 const level = this.level;
71392 return function () {
71393 const open = ansiStyles$1.color[levelMapping[level]][model].apply(null, arguments);
71394 const codes = {
71395 open,
71396 close: ansiStyles$1.color.close,
71397 closeRe: ansiStyles$1.color.closeRe
71398 };
71399 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
71400 };
71401 }
71402 };
71403}
71404
71405ansiStyles$1.bgColor.closeRe = new RegExp(escapeStringRegexp$1(ansiStyles$1.bgColor.close), 'g');
71406for (const model of Object.keys(ansiStyles$1.bgColor.ansi)) {
71407 if (skipModels.has(model)) {
71408 continue;
71409 }
71410
71411 const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
71412 styles[bgModel] = {
71413 get() {
71414 const level = this.level;
71415 return function () {
71416 const open = ansiStyles$1.bgColor[levelMapping[level]][model].apply(null, arguments);
71417 const codes = {
71418 open,
71419 close: ansiStyles$1.bgColor.close,
71420 closeRe: ansiStyles$1.bgColor.closeRe
71421 };
71422 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
71423 };
71424 }
71425 };
71426}
71427
71428const proto = Object.defineProperties(() => {}, styles);
71429
71430function build(_styles, _empty, key) {
71431 const builder = function () {
71432 return applyStyle.apply(builder, arguments);
71433 };
71434
71435 builder._styles = _styles;
71436 builder._empty = _empty;
71437
71438 const self = this;
71439
71440 Object.defineProperty(builder, 'level', {
71441 enumerable: true,
71442 get() {
71443 return self.level;
71444 },
71445 set(level) {
71446 self.level = level;
71447 }
71448 });
71449
71450 Object.defineProperty(builder, 'enabled', {
71451 enumerable: true,
71452 get() {
71453 return self.enabled;
71454 },
71455 set(enabled) {
71456 self.enabled = enabled;
71457 }
71458 });
71459
71460 // See below for fix regarding invisible grey/dim combination on Windows
71461 builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey';
71462
71463 // `__proto__` is used because we must return a function, but there is
71464 // no way to create a function with a different prototype
71465 builder.__proto__ = proto; // eslint-disable-line no-proto
71466
71467 return builder;
71468}
71469
71470function applyStyle() {
71471 // Support varags, but simply cast to string in case there's only one arg
71472 const args = arguments;
71473 const argsLen = args.length;
71474 let str = String(arguments[0]);
71475
71476 if (argsLen === 0) {
71477 return '';
71478 }
71479
71480 if (argsLen > 1) {
71481 // Don't slice `arguments`, it prevents V8 optimizations
71482 for (let a = 1; a < argsLen; a++) {
71483 str += ' ' + args[a];
71484 }
71485 }
71486
71487 if (!this.enabled || this.level <= 0 || !str) {
71488 return this._empty ? '' : str;
71489 }
71490
71491 // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
71492 // see https://github.com/chalk/chalk/issues/58
71493 // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
71494 const originalDim = ansiStyles$1.dim.open;
71495 if (isSimpleWindowsTerm && this.hasGrey) {
71496 ansiStyles$1.dim.open = '';
71497 }
71498
71499 for (const code of this._styles.slice().reverse()) {
71500 // Replace any instances already present with a re-opening code
71501 // otherwise only the part of the string until said closing code
71502 // will be colored, and the rest will simply be 'plain'.
71503 str = code.open + str.replace(code.closeRe, code.open) + code.close;
71504
71505 // Close the styling before a linebreak and reopen
71506 // after next line to fix a bleed issue on macOS
71507 // https://github.com/chalk/chalk/pull/92
71508 str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`);
71509 }
71510
71511 // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue
71512 ansiStyles$1.dim.open = originalDim;
71513
71514 return str;
71515}
71516
71517function chalkTag(chalk, strings) {
71518 if (!Array.isArray(strings)) {
71519 // If chalk() was called by itself or with a string,
71520 // return the string itself as a string.
71521 return [].slice.call(arguments, 1).join(' ');
71522 }
71523
71524 const args = [].slice.call(arguments, 2);
71525 const parts = [strings.raw[0]];
71526
71527 for (let i = 1; i < strings.length; i++) {
71528 parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&'));
71529 parts.push(String(strings.raw[i]));
71530 }
71531
71532 return template(chalk, parts.join(''));
71533}
71534
71535Object.defineProperties(Chalk.prototype, styles);
71536
71537module.exports = Chalk(); // eslint-disable-line new-cap
71538module.exports.supportsColor = stdoutColor;
71539module.exports.default = module.exports; // For TypeScript
71540}(chalk$1));
71541
71542var shellQuote$1 = {};
71543
71544shellQuote$1.quote = function (xs) {
71545 return xs.map(function (s) {
71546 if (s && typeof s === 'object') {
71547 return s.op.replace(/(.)/g, '\\$1');
71548 }
71549 else if (/["\s]/.test(s) && !/'/.test(s)) {
71550 return "'" + s.replace(/(['\\])/g, '\\$1') + "'";
71551 }
71552 else if (/["'\s]/.test(s)) {
71553 return '"' + s.replace(/(["\\$`!])/g, '\\$1') + '"';
71554 }
71555 else {
71556 return String(s).replace(/([A-z]:)?([#!"$&'()*,:;<=>?@\[\\\]^`{|}])/g, '$1\\$2');
71557 }
71558 }).join(' ');
71559};
71560
71561// '<(' is process substitution operator and
71562// can be parsed the same as control operator
71563var CONTROL = '(?:' + [
71564 '\\|\\|', '\\&\\&', ';;', '\\|\\&', '\\<\\(', '>>', '>\\&', '[&;()|<>]'
71565].join('|') + ')';
71566var META = '|&;()<> \\t';
71567var BAREWORD = '(\\\\[\'"' + META + ']|[^\\s\'"' + META + '])+';
71568var SINGLE_QUOTE = '"((\\\\"|[^"])*?)"';
71569var DOUBLE_QUOTE = '\'((\\\\\'|[^\'])*?)\'';
71570
71571var TOKEN = '';
71572for (var i = 0; i < 4; i++) {
71573 TOKEN += (Math.pow(16,8)*Math.random()).toString(16);
71574}
71575
71576shellQuote$1.parse = function (s, env, opts) {
71577 var mapped = parse$1(s, env, opts);
71578 if (typeof env !== 'function') return mapped;
71579 return mapped.reduce(function (acc, s) {
71580 if (typeof s === 'object') return acc.concat(s);
71581 var xs = s.split(RegExp('(' + TOKEN + '.*?' + TOKEN + ')', 'g'));
71582 if (xs.length === 1) return acc.concat(xs[0]);
71583 return acc.concat(xs.filter(Boolean).map(function (x) {
71584 if (RegExp('^' + TOKEN).test(x)) {
71585 return JSON.parse(x.split(TOKEN)[1]);
71586 }
71587 else return x;
71588 }));
71589 }, []);
71590};
71591
71592function parse$1 (s, env, opts) {
71593 var chunker = new RegExp([
71594 '(' + CONTROL + ')', // control chars
71595 '(' + BAREWORD + '|' + SINGLE_QUOTE + '|' + DOUBLE_QUOTE + ')*'
71596 ].join('|'), 'g');
71597 var match = s.match(chunker).filter(Boolean);
71598 var commented = false;
71599
71600 if (!match) return [];
71601 if (!env) env = {};
71602 if (!opts) opts = {};
71603 return match.map(function (s, j) {
71604 if (commented) {
71605 return;
71606 }
71607 if (RegExp('^' + CONTROL + '$').test(s)) {
71608 return { op: s };
71609 }
71610
71611 // Hand-written scanner/parser for Bash quoting rules:
71612 //
71613 // 1. inside single quotes, all characters are printed literally.
71614 // 2. inside double quotes, all characters are printed literally
71615 // except variables prefixed by '$' and backslashes followed by
71616 // either a double quote or another backslash.
71617 // 3. outside of any quotes, backslashes are treated as escape
71618 // characters and not printed (unless they are themselves escaped)
71619 // 4. quote context can switch mid-token if there is no whitespace
71620 // between the two quote contexts (e.g. all'one'"token" parses as
71621 // "allonetoken")
71622 var SQ = "'";
71623 var DQ = '"';
71624 var DS = '$';
71625 var BS = opts.escape || '\\';
71626 var quote = false;
71627 var esc = false;
71628 var out = '';
71629 var isGlob = false;
71630
71631 for (var i = 0, len = s.length; i < len; i++) {
71632 var c = s.charAt(i);
71633 isGlob = isGlob || (!quote && (c === '*' || c === '?'));
71634 if (esc) {
71635 out += c;
71636 esc = false;
71637 }
71638 else if (quote) {
71639 if (c === quote) {
71640 quote = false;
71641 }
71642 else if (quote == SQ) {
71643 out += c;
71644 }
71645 else { // Double quote
71646 if (c === BS) {
71647 i += 1;
71648 c = s.charAt(i);
71649 if (c === DQ || c === BS || c === DS) {
71650 out += c;
71651 } else {
71652 out += BS + c;
71653 }
71654 }
71655 else if (c === DS) {
71656 out += parseEnvVar();
71657 }
71658 else {
71659 out += c;
71660 }
71661 }
71662 }
71663 else if (c === DQ || c === SQ) {
71664 quote = c;
71665 }
71666 else if (RegExp('^' + CONTROL + '$').test(c)) {
71667 return { op: s };
71668 }
71669 else if (RegExp('^#$').test(c)) {
71670 commented = true;
71671 if (out.length){
71672 return [out, { comment: s.slice(i+1) + match.slice(j+1).join(' ') }];
71673 }
71674 return [{ comment: s.slice(i+1) + match.slice(j+1).join(' ') }];
71675 }
71676 else if (c === BS) {
71677 esc = true;
71678 }
71679 else if (c === DS) {
71680 out += parseEnvVar();
71681 }
71682 else out += c;
71683 }
71684
71685 if (isGlob) return {op: 'glob', pattern: out};
71686
71687 return out;
71688
71689 function parseEnvVar() {
71690 i += 1;
71691 var varend, varname;
71692 //debugger
71693 if (s.charAt(i) === '{') {
71694 i += 1;
71695 if (s.charAt(i) === '}') {
71696 throw new Error("Bad substitution: " + s.substr(i - 2, 3));
71697 }
71698 varend = s.indexOf('}', i);
71699 if (varend < 0) {
71700 throw new Error("Bad substitution: " + s.substr(i));
71701 }
71702 varname = s.substr(i, varend - i);
71703 i = varend;
71704 }
71705 else if (/[*@#?$!_\-]/.test(s.charAt(i))) {
71706 varname = s.charAt(i);
71707 i += 1;
71708 }
71709 else {
71710 varend = s.substr(i).match(/[^\w\d_]/);
71711 if (!varend) {
71712 varname = s.substr(i);
71713 i = s.length;
71714 } else {
71715 varname = s.substr(i, varend.index);
71716 i += varend.index - 1;
71717 }
71718 }
71719 return getVar(null, '', varname);
71720 }
71721 })
71722 // finalize parsed aruments
71723 .reduce(function(prev, arg){
71724 if (arg === undefined){
71725 return prev;
71726 }
71727 return prev.concat(arg);
71728 },[]);
71729
71730 function getVar (_, pre, key) {
71731 var r = typeof env === 'function' ? env(key) : env[key];
71732 if (r === undefined && key != '')
71733 r = '';
71734 else if (r === undefined)
71735 r = '$';
71736
71737 if (typeof r === 'object') {
71738 return pre + TOKEN + JSON.stringify(r) + TOKEN;
71739 }
71740 else return pre + r;
71741 }
71742}
71743
71744var osx = {
71745 '/Applications/Atom.app/Contents/MacOS/Atom': 'atom',
71746 '/Applications/Atom Beta.app/Contents/MacOS/Atom Beta':
71747 '/Applications/Atom Beta.app/Contents/MacOS/Atom Beta',
71748 '/Applications/Brackets.app/Contents/MacOS/Brackets': 'brackets',
71749 '/Applications/Sublime Text.app/Contents/MacOS/Sublime Text':
71750 '/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl',
71751 '/Applications/Sublime Text 2.app/Contents/MacOS/Sublime Text 2':
71752 '/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl',
71753 '/Applications/Sublime Text Dev.app/Contents/MacOS/Sublime Text':
71754 '/Applications/Sublime Text Dev.app/Contents/SharedSupport/bin/subl',
71755 '/Applications/Visual Studio Code.app/Contents/MacOS/Electron': 'code',
71756 '/Applications/Visual Studio Code - Insiders.app/Contents/MacOS/Electron':
71757 'code-insiders',
71758 '/Applications/AppCode.app/Contents/MacOS/appcode':
71759 '/Applications/AppCode.app/Contents/MacOS/appcode',
71760 '/Applications/CLion.app/Contents/MacOS/clion':
71761 '/Applications/CLion.app/Contents/MacOS/clion',
71762 '/Applications/IntelliJ IDEA.app/Contents/MacOS/idea':
71763 '/Applications/IntelliJ IDEA.app/Contents/MacOS/idea',
71764 '/Applications/PhpStorm.app/Contents/MacOS/phpstorm':
71765 '/Applications/PhpStorm.app/Contents/MacOS/phpstorm',
71766 '/Applications/PyCharm.app/Contents/MacOS/pycharm':
71767 '/Applications/PyCharm.app/Contents/MacOS/pycharm',
71768 '/Applications/PyCharm CE.app/Contents/MacOS/pycharm':
71769 '/Applications/PyCharm CE.app/Contents/MacOS/pycharm',
71770 '/Applications/RubyMine.app/Contents/MacOS/rubymine':
71771 '/Applications/RubyMine.app/Contents/MacOS/rubymine',
71772 '/Applications/WebStorm.app/Contents/MacOS/webstorm':
71773 '/Applications/WebStorm.app/Contents/MacOS/webstorm'
71774};
71775
71776var linux = {
71777 atom: 'atom',
71778 Brackets: 'brackets',
71779 code: 'code',
71780 emacs: 'emacs',
71781 'idea.sh': 'idea',
71782 'phpstorm.sh': 'phpstorm',
71783 'pycharm.sh': 'pycharm',
71784 'rubymine.sh': 'rubymine',
71785 sublime_text: 'subl',
71786 vim: 'vim',
71787 'webstorm.sh': 'webstorm'
71788};
71789
71790var windows = [
71791 'Brackets.exe',
71792 'Code.exe',
71793 'atom.exe',
71794 'sublime_text.exe',
71795 'notepad++.exe',
71796 'clion.exe',
71797 'clion64.exe',
71798 'idea.exe',
71799 'idea64.exe',
71800 'phpstorm.exe',
71801 'phpstorm64.exe',
71802 'pycharm.exe',
71803 'pycharm64.exe',
71804 'rubymine.exe',
71805 'rubymine64.exe',
71806 'webstorm.exe',
71807 'webstorm64.exe'
71808];
71809
71810const path$4 = path__default;
71811const shellQuote = shellQuote$1;
71812const childProcess$1 = require$$1__default$3;
71813
71814// Map from full process name to binary that starts the process
71815// We can't just re-use full process name, because it will spawn a new instance
71816// of the app every time
71817const COMMON_EDITORS_OSX = osx;
71818const COMMON_EDITORS_LINUX = linux;
71819const COMMON_EDITORS_WIN = windows;
71820
71821var guess = function guessEditor (specifiedEditor) {
71822 if (specifiedEditor) {
71823 return shellQuote.parse(specifiedEditor)
71824 }
71825 // We can find out which editor is currently running by:
71826 // `ps x` on macOS and Linux
71827 // `Get-Process` on Windows
71828 try {
71829 if (process.platform === 'darwin') {
71830 const output = childProcess$1.execSync('ps x').toString();
71831 const processNames = Object.keys(COMMON_EDITORS_OSX);
71832 for (let i = 0; i < processNames.length; i++) {
71833 const processName = processNames[i];
71834 if (output.indexOf(processName) !== -1) {
71835 return [COMMON_EDITORS_OSX[processName]]
71836 }
71837 }
71838 } else if (process.platform === 'win32') {
71839 const output = childProcess$1
71840 .execSync('powershell -Command "Get-Process | Select-Object Path"', {
71841 stdio: ['pipe', 'pipe', 'ignore']
71842 })
71843 .toString();
71844 const runningProcesses = output.split('\r\n');
71845 for (let i = 0; i < runningProcesses.length; i++) {
71846 // `Get-Process` sometimes returns empty lines
71847 if (!runningProcesses[i]) {
71848 continue
71849 }
71850
71851 const fullProcessPath = runningProcesses[i].trim();
71852 const shortProcessName = path$4.basename(fullProcessPath);
71853
71854 if (COMMON_EDITORS_WIN.indexOf(shortProcessName) !== -1) {
71855 return [fullProcessPath]
71856 }
71857 }
71858 } else if (process.platform === 'linux') {
71859 // --no-heading No header line
71860 // x List all processes owned by you
71861 // -o comm Need only names column
71862 const output = childProcess$1
71863 .execSync('ps x --no-heading -o comm --sort=comm')
71864 .toString();
71865 const processNames = Object.keys(COMMON_EDITORS_LINUX);
71866 for (let i = 0; i < processNames.length; i++) {
71867 const processName = processNames[i];
71868 if (output.indexOf(processName) !== -1) {
71869 return [COMMON_EDITORS_LINUX[processName]]
71870 }
71871 }
71872 }
71873 } catch (error) {
71874 // Ignore...
71875 }
71876
71877 // Last resort, use old skool env vars
71878 if (process.env.VISUAL) {
71879 return [process.env.VISUAL]
71880 } else if (process.env.EDITOR) {
71881 return [process.env.EDITOR]
71882 }
71883
71884 return [null]
71885};
71886
71887const path$3 = path__default;
71888
71889// normalize file/line numbers into command line args for specific editors
71890var getArgs = function getArgumentsForPosition (
71891 editor,
71892 fileName,
71893 lineNumber,
71894 columnNumber = 1
71895) {
71896 const editorBasename = path$3.basename(editor).replace(/\.(exe|cmd|bat)$/i, '');
71897 switch (editorBasename) {
71898 case 'atom':
71899 case 'Atom':
71900 case 'Atom Beta':
71901 case 'subl':
71902 case 'sublime':
71903 case 'sublime_text':
71904 case 'wstorm':
71905 case 'charm':
71906 return [`${fileName}:${lineNumber}:${columnNumber}`]
71907 case 'notepad++':
71908 return ['-n' + lineNumber, fileName]
71909 case 'vim':
71910 case 'mvim':
71911 return [`+call cursor(${lineNumber}, ${columnNumber})`, fileName]
71912 case 'joe':
71913 return ['+' + `${lineNumber}`, fileName]
71914 case 'emacs':
71915 case 'emacsclient':
71916 return [`+${lineNumber}:${columnNumber}`, fileName]
71917 case 'rmate':
71918 case 'mate':
71919 case 'mine':
71920 return ['--line', lineNumber, fileName]
71921 case 'code':
71922 case 'code-insiders':
71923 case 'Code':
71924 return ['-r', '-g', `${fileName}:${lineNumber}:${columnNumber}`]
71925 case 'appcode':
71926 case 'clion':
71927 case 'clion64':
71928 case 'idea':
71929 case 'idea64':
71930 case 'phpstorm':
71931 case 'phpstorm64':
71932 case 'pycharm':
71933 case 'pycharm64':
71934 case 'rubymine':
71935 case 'rubymine64':
71936 case 'webstorm':
71937 case 'webstorm64':
71938 return ['--line', lineNumber, fileName]
71939 }
71940
71941 // For all others, drop the lineNumber until we have
71942 // a mapping above, since providing the lineNumber incorrectly
71943 // can result in errors or confusing behavior.
71944 return [fileName]
71945};
71946
71947/**
71948 * Copyright (c) 2015-present, Facebook, Inc.
71949 *
71950 * This source code is licensed under the MIT license found in the
71951 * LICENSE file at
71952 * https://github.com/facebookincubator/create-react-app/blob/master/LICENSE
71953 *
71954 * Modified by Yuxi Evan You
71955 */
71956
71957const fs$1 = fs__default;
71958const os$1 = require$$0__default$1;
71959const path$2 = path__default;
71960const chalk = chalk$1.exports;
71961const childProcess = require$$1__default$3;
71962
71963const guessEditor = guess;
71964const getArgumentsForPosition = getArgs;
71965
71966function wrapErrorCallback (cb) {
71967 return (fileName, errorMessage) => {
71968 console.log();
71969 console.log(
71970 chalk.red('Could not open ' + path$2.basename(fileName) + ' in the editor.')
71971 );
71972 if (errorMessage) {
71973 if (errorMessage[errorMessage.length - 1] !== '.') {
71974 errorMessage += '.';
71975 }
71976 console.log(
71977 chalk.red('The editor process exited with an error: ' + errorMessage)
71978 );
71979 }
71980 console.log();
71981 if (cb) cb(fileName, errorMessage);
71982 }
71983}
71984
71985function isTerminalEditor (editor) {
71986 switch (editor) {
71987 case 'vim':
71988 case 'emacs':
71989 case 'nano':
71990 return true
71991 }
71992 return false
71993}
71994
71995const positionRE = /:(\d+)(:(\d+))?$/;
71996function parseFile (file) {
71997 const fileName = file.replace(positionRE, '');
71998 const match = file.match(positionRE);
71999 const lineNumber = match && match[1];
72000 const columnNumber = match && match[3];
72001 return {
72002 fileName,
72003 lineNumber,
72004 columnNumber
72005 }
72006}
72007
72008let _childProcess = null;
72009
72010function launchEditor (file, specifiedEditor, onErrorCallback) {
72011 const parsed = parseFile(file);
72012 let { fileName } = parsed;
72013 const { lineNumber, columnNumber } = parsed;
72014
72015 if (!fs$1.existsSync(fileName)) {
72016 return
72017 }
72018
72019 if (typeof specifiedEditor === 'function') {
72020 onErrorCallback = specifiedEditor;
72021 specifiedEditor = undefined;
72022 }
72023
72024 onErrorCallback = wrapErrorCallback(onErrorCallback);
72025
72026 const [editor, ...args] = guessEditor(specifiedEditor);
72027 if (!editor) {
72028 onErrorCallback(fileName, null);
72029 return
72030 }
72031
72032 if (
72033 process.platform === 'linux' &&
72034 fileName.startsWith('/mnt/') &&
72035 /Microsoft/i.test(os$1.release())
72036 ) {
72037 // Assume WSL / "Bash on Ubuntu on Windows" is being used, and
72038 // that the file exists on the Windows file system.
72039 // `os.release()` is "4.4.0-43-Microsoft" in the current release
72040 // build of WSL, see: https://github.com/Microsoft/BashOnWindows/issues/423#issuecomment-221627364
72041 // When a Windows editor is specified, interop functionality can
72042 // handle the path translation, but only if a relative path is used.
72043 fileName = path$2.relative('', fileName);
72044 }
72045
72046 if (lineNumber) {
72047 const extraArgs = getArgumentsForPosition(editor, fileName, lineNumber, columnNumber);
72048 args.push.apply(args, extraArgs);
72049 } else {
72050 args.push(fileName);
72051 }
72052
72053 if (_childProcess && isTerminalEditor(editor)) {
72054 // There's an existing editor process already and it's attached
72055 // to the terminal, so go kill it. Otherwise two separate editor
72056 // instances attach to the stdin/stdout which gets confusing.
72057 _childProcess.kill('SIGKILL');
72058 }
72059
72060 if (process.platform === 'win32') {
72061 // On Windows, launch the editor in a shell because spawn can only
72062 // launch .exe files.
72063 _childProcess = childProcess.spawn(
72064 'cmd.exe',
72065 ['/C', editor].concat(args),
72066 { stdio: 'inherit' }
72067 );
72068 } else {
72069 _childProcess = childProcess.spawn(editor, args, { stdio: 'inherit' });
72070 }
72071 _childProcess.on('exit', function (errorCode) {
72072 _childProcess = null;
72073
72074 if (errorCode) {
72075 onErrorCallback(fileName, '(code ' + errorCode + ')');
72076 }
72077 });
72078
72079 _childProcess.on('error', function (error) {
72080 onErrorCallback(fileName, error.message);
72081 });
72082}
72083
72084var launchEditor_1 = launchEditor;
72085
72086const url = require$$0__default$7;
72087const path$1 = path__default;
72088const launch = launchEditor_1;
72089
72090var launchEditorMiddleware = (specifiedEditor, srcRoot, onErrorCallback) => {
72091 if (typeof specifiedEditor === 'function') {
72092 onErrorCallback = specifiedEditor;
72093 specifiedEditor = undefined;
72094 }
72095
72096 if (typeof srcRoot === 'function') {
72097 onErrorCallback = srcRoot;
72098 srcRoot = undefined;
72099 }
72100
72101 srcRoot = srcRoot || process.cwd();
72102
72103 return function launchEditorMiddleware (req, res, next) {
72104 const { file } = url.parse(req.url, true).query || {};
72105 if (!file) {
72106 res.statusCode = 500;
72107 res.end(`launch-editor-middleware: required query param "file" is missing.`);
72108 } else {
72109 launch(path$1.resolve(srcRoot, file), specifiedEditor, onErrorCallback);
72110 res.end();
72111 }
72112 }
72113};
72114
72115const externalTypes = [
72116 'css',
72117 // supported pre-processor types
72118 'less',
72119 'sass',
72120 'scss',
72121 'styl',
72122 'stylus',
72123 'pcss',
72124 'postcss',
72125 // known SFC types
72126 'vue',
72127 'svelte',
72128 'marko',
72129 // JSX/TSX may be configured to be compiled differently from how esbuild
72130 // handles it by default, so exclude them as well
72131 'jsx',
72132 'tsx',
72133 ...KNOWN_ASSET_TYPES
72134];
72135function esbuildDepPlugin(qualified, exportsData, config, ssr) {
72136 // default resolver which prefers ESM
72137 const _resolve = config.createResolver({ asSrc: false });
72138 // cjs resolver that prefers Node
72139 const _resolveRequire = config.createResolver({
72140 asSrc: false,
72141 isRequire: true
72142 });
72143 const resolve = (id, importer, kind, resolveDir) => {
72144 let _importer;
72145 // explicit resolveDir - this is passed only during yarn pnp resolve for
72146 // entries
72147 if (resolveDir) {
72148 _importer = normalizePath$4(path__default.join(resolveDir, '*'));
72149 }
72150 else {
72151 // map importer ids to file paths for correct resolution
72152 _importer = importer in qualified ? qualified[importer] : importer;
72153 }
72154 const resolver = kind.startsWith('require') ? _resolveRequire : _resolve;
72155 return resolver(id, _importer, undefined, ssr);
72156 };
72157 return {
72158 name: 'vite:dep-pre-bundle',
72159 setup(build) {
72160 // externalize assets and commonly known non-js file types
72161 build.onResolve({
72162 filter: new RegExp(`\\.(` + externalTypes.join('|') + `)(\\?.*)?$`)
72163 }, async ({ path: id, importer, kind }) => {
72164 const resolved = await resolve(id, importer, kind);
72165 if (resolved) {
72166 return {
72167 path: resolved,
72168 external: true
72169 };
72170 }
72171 });
72172 function resolveEntry(id, isEntry, resolveDir) {
72173 const flatId = flattenId(id);
72174 if (flatId in qualified) {
72175 return isEntry
72176 ? {
72177 path: flatId,
72178 namespace: 'dep'
72179 }
72180 : {
72181 path: require.resolve(qualified[flatId], {
72182 paths: [resolveDir]
72183 })
72184 };
72185 }
72186 }
72187 build.onResolve({ filter: /^[\w@][^:]/ }, async ({ path: id, importer, kind, resolveDir }) => {
72188 const isEntry = !importer;
72189 // ensure esbuild uses our resolved entries
72190 let entry;
72191 // if this is an entry, return entry namespace resolve result
72192 if ((entry = resolveEntry(id, isEntry, resolveDir)))
72193 return entry;
72194 // check if this is aliased to an entry - also return entry namespace
72195 const aliased = await _resolve(id, undefined, true);
72196 if (aliased && (entry = resolveEntry(aliased, isEntry, resolveDir))) {
72197 return entry;
72198 }
72199 // use vite's own resolver
72200 const resolved = await resolve(id, importer, kind);
72201 if (resolved) {
72202 if (resolved.startsWith(browserExternalId)) {
72203 return {
72204 path: id,
72205 namespace: 'browser-external'
72206 };
72207 }
72208 if (isExternalUrl(resolved)) {
72209 return {
72210 path: resolved,
72211 external: true
72212 };
72213 }
72214 return {
72215 path: path__default.resolve(resolved)
72216 };
72217 }
72218 });
72219 // For entry files, we'll read it ourselves and construct a proxy module
72220 // to retain the entry's raw id instead of file path so that esbuild
72221 // outputs desired output file structure.
72222 // It is necessary to do the re-exporting to separate the virtual proxy
72223 // module from the actual module since the actual module may get
72224 // referenced via relative imports - if we don't separate the proxy and
72225 // the actual module, esbuild will create duplicated copies of the same
72226 // module!
72227 const root = path__default.resolve(config.root);
72228 build.onLoad({ filter: /.*/, namespace: 'dep' }, ({ path: id }) => {
72229 const entryFile = qualified[id];
72230 let relativePath = normalizePath$4(path__default.relative(root, entryFile));
72231 if (!relativePath.startsWith('.')) {
72232 relativePath = `./${relativePath}`;
72233 }
72234 let contents = '';
72235 const data = exportsData[id];
72236 const [imports, exports] = data;
72237 if (!imports.length && !exports.length) {
72238 // cjs
72239 contents += `export default require("${relativePath}");`;
72240 }
72241 else {
72242 if (exports.includes('default')) {
72243 contents += `import d from "${relativePath}";export default d;`;
72244 }
72245 if (data.hasReExports ||
72246 exports.length > 1 ||
72247 exports[0] !== 'default') {
72248 contents += `\nexport * from "${relativePath}"`;
72249 }
72250 }
72251 let ext = path__default.extname(entryFile).slice(1);
72252 if (ext === 'mjs')
72253 ext = 'js';
72254 return {
72255 loader: ext,
72256 contents,
72257 resolveDir: root
72258 };
72259 });
72260 build.onLoad({ filter: /.*/, namespace: 'browser-external' }, ({ path: id }) => {
72261 return {
72262 contents: `export default new Proxy({}, {
72263 get() {
72264 throw new Error('Module "${id}" has been externalized for ` +
72265 `browser compatibility and cannot be accessed in client code.')
72266 }
72267})`
72268 };
72269 });
72270 // yarn 2 pnp compat
72271 if (isRunningWithYarnPnp) {
72272 build.onResolve({ filter: /.*/ }, async ({ path, importer, kind, resolveDir }) => ({
72273 // pass along resolveDir for entries
72274 path: await resolve(path, importer, kind, resolveDir)
72275 }));
72276 build.onLoad({ filter: /.*/ }, async (args) => ({
72277 contents: await require('fs').promises.readFile(args.path),
72278 loader: 'default'
72279 }));
72280 }
72281 }
72282 };
72283}
72284
72285const debug$1 = createDebugger('vite:deps');
72286async function optimizeDeps(config, force = config.server.force, asCommand = false, newDeps, // missing imports encountered after server has started
72287ssr) {
72288 var _a, _b, _c, _d;
72289 config = {
72290 ...config,
72291 command: 'build'
72292 };
72293 const { root, logger, cacheDir } = config;
72294 const log = asCommand ? logger.info : debug$1;
72295 if (!cacheDir) {
72296 log(`No cache directory. Skipping.`);
72297 return null;
72298 }
72299 const dataPath = path__default.join(cacheDir, '_metadata.json');
72300 const mainHash = getDepHash(root, config);
72301 const data = {
72302 hash: mainHash,
72303 browserHash: mainHash,
72304 optimized: {}
72305 };
72306 if (!force) {
72307 let prevData;
72308 try {
72309 prevData = JSON.parse(fs__default.readFileSync(dataPath, 'utf-8'));
72310 }
72311 catch (e) { }
72312 // hash is consistent, no need to re-bundle
72313 if (prevData && prevData.hash === data.hash) {
72314 log('Hash is consistent. Skipping. Use --force to override.');
72315 return prevData;
72316 }
72317 }
72318 if (fs__default.existsSync(cacheDir)) {
72319 emptyDir(cacheDir);
72320 }
72321 else {
72322 fs__default.mkdirSync(cacheDir, { recursive: true });
72323 }
72324 // a hint for Node.js
72325 // all files in the cache directory should be recognized as ES modules
72326 writeFile(path__default.resolve(cacheDir, 'package.json'), JSON.stringify({ type: 'module' }));
72327 let deps, missing;
72328 if (!newDeps) {
72329 ({ deps, missing } = await scanImports(config));
72330 }
72331 else {
72332 deps = newDeps;
72333 missing = {};
72334 }
72335 // update browser hash
72336 data.browserHash = require$$1$2.createHash('sha256')
72337 .update(data.hash + JSON.stringify(deps))
72338 .digest('hex')
72339 .substr(0, 8);
72340 const missingIds = Object.keys(missing);
72341 if (missingIds.length) {
72342 throw new Error(`The following dependencies are imported but could not be resolved:\n\n ${missingIds
72343 .map((id) => `${source.cyan(id)} ${source.white.dim(`(imported by ${missing[id]})`)}`)
72344 .join(`\n `)}\n\nAre they installed?`);
72345 }
72346 const include = (_a = config.optimizeDeps) === null || _a === void 0 ? void 0 : _a.include;
72347 if (include) {
72348 const resolve = config.createResolver({ asSrc: false });
72349 for (const id of include) {
72350 if (!deps[id]) {
72351 const entry = await resolve(id);
72352 if (entry) {
72353 deps[id] = entry;
72354 }
72355 else {
72356 throw new Error(`Failed to resolve force included dependency: ${source.cyan(id)}`);
72357 }
72358 }
72359 }
72360 }
72361 const qualifiedIds = Object.keys(deps);
72362 if (!qualifiedIds.length) {
72363 writeFile(dataPath, JSON.stringify(data, null, 2));
72364 log(`No dependencies to bundle. Skipping.\n\n\n`);
72365 return data;
72366 }
72367 const total = qualifiedIds.length;
72368 const maxListed = 5;
72369 const listed = Math.min(total, maxListed);
72370 const extra = Math.max(0, total - maxListed);
72371 const depsString = source.yellow(qualifiedIds.slice(0, listed).join(`\n `) +
72372 (extra > 0 ? `\n (...and ${extra} more)` : ``));
72373 if (!asCommand) {
72374 if (!newDeps) {
72375 // This is auto run on server start - let the user know that we are
72376 // pre-optimizing deps
72377 logger.info(source.greenBright(`Pre-bundling dependencies:\n ${depsString}`));
72378 logger.info(`(this will be run only when your dependencies or config have changed)`);
72379 }
72380 }
72381 else {
72382 logger.info(source.greenBright(`Optimizing dependencies:\n ${depsString}`));
72383 }
72384 // esbuild generates nested directory output with lowest common ancestor base
72385 // this is unpredictable and makes it difficult to analyze entry / output
72386 // mapping. So what we do here is:
72387 // 1. flatten all ids to eliminate slash
72388 // 2. in the plugin, read the entry ourselves as virtual files to retain the
72389 // path.
72390 const flatIdDeps = {};
72391 const idToExports = {};
72392 const flatIdToExports = {};
72393 await init;
72394 for (const id in deps) {
72395 const flatId = flattenId(id);
72396 flatIdDeps[flatId] = deps[id];
72397 const entryContent = fs__default.readFileSync(deps[id], 'utf-8');
72398 const exportsData = parse$e(entryContent);
72399 for (const { ss, se } of exportsData[0]) {
72400 const exp = entryContent.slice(ss, se);
72401 if (/export\s+\*\s+from/.test(exp)) {
72402 exportsData.hasReExports = true;
72403 }
72404 }
72405 idToExports[id] = exportsData;
72406 flatIdToExports[flatId] = exportsData;
72407 }
72408 const define = {
72409 'process.env.NODE_ENV': JSON.stringify(config.mode)
72410 };
72411 for (const key in config.define) {
72412 const value = config.define[key];
72413 define[key] = typeof value === 'string' ? value : JSON.stringify(value);
72414 }
72415 const start = Date.now();
72416 const { plugins = [], ...esbuildOptions } = (_c = (_b = config.optimizeDeps) === null || _b === void 0 ? void 0 : _b.esbuildOptions) !== null && _c !== void 0 ? _c : {};
72417 const result = await esbuild.build({
72418 absWorkingDir: process.cwd(),
72419 entryPoints: Object.keys(flatIdDeps),
72420 bundle: true,
72421 format: 'esm',
72422 external: (_d = config.optimizeDeps) === null || _d === void 0 ? void 0 : _d.exclude,
72423 logLevel: 'error',
72424 splitting: true,
72425 sourcemap: true,
72426 outdir: cacheDir,
72427 treeShaking: 'ignore-annotations',
72428 metafile: true,
72429 define,
72430 plugins: [
72431 ...plugins,
72432 esbuildDepPlugin(flatIdDeps, flatIdToExports, config, ssr)
72433 ],
72434 ...esbuildOptions
72435 });
72436 const meta = result.metafile;
72437 // the paths in `meta.outputs` are relative to `process.cwd()`
72438 const cacheDirOutputPath = path__default.relative(process.cwd(), cacheDir);
72439 for (const id in deps) {
72440 const entry = deps[id];
72441 data.optimized[id] = {
72442 file: normalizePath$4(path__default.resolve(cacheDir, flattenId(id) + '.js')),
72443 src: entry,
72444 needsInterop: needsInterop(id, idToExports[id], meta.outputs, cacheDirOutputPath)
72445 };
72446 }
72447 writeFile(dataPath, JSON.stringify(data, null, 2));
72448 debug$1(`deps bundled in ${Date.now() - start}ms`);
72449 return data;
72450}
72451// https://github.com/vitejs/vite/issues/1724#issuecomment-767619642
72452// a list of modules that pretends to be ESM but still uses `require`.
72453// this causes esbuild to wrap them as CJS even when its entry appears to be ESM.
72454const KNOWN_INTEROP_IDS = new Set(['moment']);
72455function needsInterop(id, exportsData, outputs, cacheDirOutputPath) {
72456 if (KNOWN_INTEROP_IDS.has(id)) {
72457 return true;
72458 }
72459 const [imports, exports] = exportsData;
72460 // entry has no ESM syntax - likely CJS or UMD
72461 if (!exports.length && !imports.length) {
72462 return true;
72463 }
72464 // if a peer dependency used require() on a ESM dependency, esbuild turns the
72465 // ESM dependency's entry chunk into a single default export... detect
72466 // such cases by checking exports mismatch, and force interop.
72467 const flatId = flattenId(id) + '.js';
72468 let generatedExports;
72469 for (const output in outputs) {
72470 if (normalizePath$4(output) ===
72471 normalizePath$4(path__default.join(cacheDirOutputPath, flatId))) {
72472 generatedExports = outputs[output].exports;
72473 break;
72474 }
72475 }
72476 if (!generatedExports ||
72477 (isSingleDefaultExport(generatedExports) && !isSingleDefaultExport(exports))) {
72478 return true;
72479 }
72480 return false;
72481}
72482function isSingleDefaultExport(exports) {
72483 return exports.length === 1 && exports[0] === 'default';
72484}
72485const lockfileFormats = ['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml'];
72486function getDepHash(root, config) {
72487 var _a, _b;
72488 let content = lookupFile(root, lockfileFormats) || '';
72489 // also take config into account
72490 // only a subset of config options that can affect dep optimization
72491 content += JSON.stringify({
72492 mode: config.mode,
72493 root: config.root,
72494 resolve: config.resolve,
72495 assetsInclude: config.assetsInclude,
72496 plugins: config.plugins.map((p) => p.name),
72497 optimizeDeps: {
72498 include: (_a = config.optimizeDeps) === null || _a === void 0 ? void 0 : _a.include,
72499 exclude: (_b = config.optimizeDeps) === null || _b === void 0 ? void 0 : _b.exclude
72500 }
72501 }, (_, value) => {
72502 if (typeof value === 'function' || value instanceof RegExp) {
72503 return value.toString();
72504 }
72505 return value;
72506 });
72507 return require$$1$2.createHash('sha256').update(content).digest('hex').substr(0, 8);
72508}
72509
72510var index$1 = {
72511 __proto__: null,
72512 optimizeDeps: optimizeDeps
72513};
72514
72515let offset;
72516try {
72517 new Function('throw new Error(1)')();
72518}
72519catch (e) {
72520 // in Node 12, stack traces account for the function wrapper.
72521 // in Node 13 and later, the function wrapper adds two lines,
72522 // which must be subtracted to generate a valid mapping
72523 const match = /:(\d+):\d+\)$/.exec(e.stack.split('\n')[1]);
72524 offset = match ? +match[1] - 1 : 0;
72525}
72526function ssrRewriteStacktrace(stack, moduleGraph) {
72527 return stack
72528 .split('\n')
72529 .map((line) => {
72530 return line.replace(/^ {4}at (?:(.+?)\s+\()?(?:(.+?):(\d+)(?::(\d+))?)\)?/, (input, varName, url, line, column) => {
72531 var _a;
72532 if (!url)
72533 return input;
72534 const mod = moduleGraph.urlToModuleMap.get(url);
72535 const rawSourceMap = (_a = mod === null || mod === void 0 ? void 0 : mod.ssrTransformResult) === null || _a === void 0 ? void 0 : _a.map;
72536 if (!rawSourceMap) {
72537 return input;
72538 }
72539 const consumer = new SourceMapConsumer(rawSourceMap);
72540 const pos = consumer.originalPositionFor({
72541 line: Number(line) - offset,
72542 column: Number(column),
72543 bias: SourceMapConsumer.LEAST_UPPER_BOUND
72544 });
72545 if (!pos.source) {
72546 return input;
72547 }
72548 const source = `${pos.source}:${pos.line || 0}:${pos.column || 0}`;
72549 if (!varName || varName === 'eval') {
72550 return ` at ${source}`;
72551 }
72552 else {
72553 return ` at ${varName} (${source})`;
72554 }
72555 });
72556 })
72557 .join('\n');
72558}
72559
72560const pendingModules = new Map();
72561async function ssrLoadModule(url, server, context = { global }, urlStack = []) {
72562 url = unwrapId$1(url);
72563 if (urlStack.includes(url)) {
72564 server.config.logger.warn(`Circular dependency: ${urlStack.join(' -> ')} -> ${url}`);
72565 return {};
72566 }
72567 // when we instantiate multiple dependency modules in parallel, they may
72568 // point to shared modules. We need to avoid duplicate instantiation attempts
72569 // by register every module as pending synchronously so that all subsequent
72570 // request to that module are simply waiting on the same promise.
72571 const pending = pendingModules.get(url);
72572 if (pending) {
72573 return pending;
72574 }
72575 const modulePromise = instantiateModule(url, server, context, urlStack);
72576 pendingModules.set(url, modulePromise);
72577 modulePromise.catch(() => { }).then(() => pendingModules.delete(url));
72578 return modulePromise;
72579}
72580async function instantiateModule(url, server, context = { global }, urlStack = []) {
72581 const { moduleGraph } = server;
72582 const mod = await moduleGraph.ensureEntryFromUrl(url);
72583 if (mod.ssrModule) {
72584 return mod.ssrModule;
72585 }
72586 const result = mod.ssrTransformResult ||
72587 (await transformRequest(url, server, { ssr: true }));
72588 if (!result) {
72589 // TODO more info? is this even necessary?
72590 throw new Error(`failed to load module for ssr: ${url}`);
72591 }
72592 const ssrModule = {
72593 [Symbol.toStringTag]: 'Module'
72594 };
72595 Object.defineProperty(ssrModule, '__esModule', { value: true });
72596 const isExternal = (dep) => dep[0] !== '.' && dep[0] !== '/';
72597 await Promise.all(result.deps.map((dep) => {
72598 if (!isExternal(dep)) {
72599 return ssrLoadModule(dep, server, context, urlStack.concat(url));
72600 }
72601 }));
72602 const ssrImportMeta = { url };
72603 const ssrImport = (dep) => {
72604 var _a;
72605 if (isExternal(dep)) {
72606 return nodeRequire(dep, mod.file, server.config.root);
72607 }
72608 else {
72609 return (_a = moduleGraph.urlToModuleMap.get(unwrapId$1(dep))) === null || _a === void 0 ? void 0 : _a.ssrModule;
72610 }
72611 };
72612 const ssrDynamicImport = (dep) => {
72613 if (isExternal(dep)) {
72614 return Promise.resolve(nodeRequire(dep, mod.file, server.config.root));
72615 }
72616 else {
72617 // #3087 dynamic import vars is ignored at rewrite import path,
72618 // so here need process relative path
72619 if (dep.startsWith('.')) {
72620 dep = path__default.posix.resolve(path__default.dirname(url), dep);
72621 }
72622 return ssrLoadModule(dep, server, context, urlStack.concat(url));
72623 }
72624 };
72625 function ssrExportAll(sourceModule) {
72626 for (const key in sourceModule) {
72627 if (key !== 'default') {
72628 Object.defineProperty(ssrModule, key, {
72629 enumerable: true,
72630 configurable: true,
72631 get() {
72632 return sourceModule[key];
72633 }
72634 });
72635 }
72636 }
72637 }
72638 try {
72639 new Function(`global`, ssrModuleExportsKey, ssrImportMetaKey, ssrImportKey, ssrDynamicImportKey, ssrExportAllKey, result.code + `\n//# sourceURL=${mod.url}`)(context.global, ssrModule, ssrImportMeta, ssrImport, ssrDynamicImport, ssrExportAll);
72640 }
72641 catch (e) {
72642 e.stack = ssrRewriteStacktrace(e.stack, moduleGraph);
72643 server.config.logger.error(`Error when evaluating SSR module ${url}:\n${e.stack}`, {
72644 timestamp: true,
72645 clear: server.config.clearScreen
72646 });
72647 throw e;
72648 }
72649 mod.ssrModule = Object.freeze(ssrModule);
72650 return ssrModule;
72651}
72652function nodeRequire(id, importer, root) {
72653 const mod = require(resolve(id, importer, root));
72654 const defaultExport = mod.__esModule ? mod.default : mod;
72655 // rollup-style default import interop for cjs
72656 return new Proxy(mod, {
72657 get(mod, prop) {
72658 if (prop === 'default')
72659 return defaultExport;
72660 return mod[prop];
72661 }
72662 });
72663}
72664const resolveCache = new Map();
72665function resolve(id, importer, root) {
72666 const key = id + importer + root;
72667 const cached = resolveCache.get(key);
72668 if (cached) {
72669 return cached;
72670 }
72671 const resolveDir = importer && fs__default.existsSync(cleanUrl(importer))
72672 ? path__default.dirname(importer)
72673 : root;
72674 const resolved = resolveFrom$3(id, resolveDir, true);
72675 resolveCache.set(key, resolved);
72676 return resolved;
72677}
72678
72679/**
72680 * The amount to wait for requests to register newly found dependencies before triggering
72681 * a re-bundle + page reload
72682 */
72683const debounceMs = 100;
72684function createMissingImporterRegisterFn(server) {
72685 const { logger } = server.config;
72686 let knownOptimized = server._optimizeDepsMetadata.optimized;
72687 let currentMissing = {};
72688 let handle;
72689 let pendingResolve = null;
72690 async function rerun(ssr) {
72691 const newDeps = currentMissing;
72692 currentMissing = {};
72693 logger.info(source.yellow(`new dependencies found: ${Object.keys(newDeps).join(', ')}, updating...`), {
72694 timestamp: true
72695 });
72696 for (const id in knownOptimized) {
72697 newDeps[id] = knownOptimized[id].src;
72698 }
72699 try {
72700 // Nullify previous metadata so that the resolver won't
72701 // resolve to optimized files during the optimizer re-run
72702 server._isRunningOptimizer = true;
72703 server._optimizeDepsMetadata = null;
72704 const newData = (server._optimizeDepsMetadata = await optimizeDeps(server.config, true, false, newDeps, ssr));
72705 knownOptimized = newData.optimized;
72706 // update ssr externals
72707 server._ssrExternals = resolveSSRExternal(server.config, Object.keys(knownOptimized));
72708 logger.info(source.greenBright(`✨ dependencies updated, reloading page...`), { timestamp: true });
72709 }
72710 catch (e) {
72711 logger.error(source.red(`error while updating dependencies:\n${e.stack}`), { timestamp: true });
72712 }
72713 finally {
72714 server._isRunningOptimizer = false;
72715 pendingResolve && pendingResolve();
72716 server._pendingReload = pendingResolve = null;
72717 }
72718 // Cached transform results have stale imports (resolved to
72719 // old locations) so they need to be invalidated before the page is
72720 // reloaded.
72721 server.moduleGraph.invalidateAll();
72722 server.ws.send({
72723 type: 'full-reload',
72724 path: '*'
72725 });
72726 }
72727 return function registerMissingImport(id, resolved, ssr) {
72728 if (!knownOptimized[id]) {
72729 currentMissing[id] = resolved;
72730 if (handle)
72731 clearTimeout(handle);
72732 handle = setTimeout(() => rerun(ssr), debounceMs);
72733 server._pendingReload = new Promise((r) => {
72734 pendingResolve = r;
72735 });
72736 }
72737 };
72738}
72739
72740// https://github.com/vitejs/vite/issues/2820#issuecomment-812495079
72741const ROOT_FILES = [
72742 // '.git',
72743 // https://pnpm.js.org/workspaces/
72744 'pnpm-workspace.yaml'
72745 // https://rushjs.io/pages/advanced/config_files/
72746 // 'rush.json',
72747 // https://nx.dev/latest/react/getting-started/nx-setup
72748 // 'workspace.json',
72749 // 'nx.json'
72750];
72751// npm: https://docs.npmjs.com/cli/v7/using-npm/workspaces#installing-workspaces
72752// yarn: https://classic.yarnpkg.com/en/docs/workspaces/#toc-how-to-use-it
72753function hasWorkspacePackageJSON(root) {
72754 const path = path$A.join(root, 'package.json');
72755 try {
72756 fs__default.accessSync(path, fs__default.constants.R_OK);
72757 }
72758 catch {
72759 return false;
72760 }
72761 const content = JSON.parse(fs__default.readFileSync(path, 'utf-8')) || {};
72762 return !!content.workspaces;
72763}
72764function hasRootFile(root) {
72765 return ROOT_FILES.some((file) => fs__default.existsSync(path$A.join(root, file)));
72766}
72767function hasPackageJSON(root) {
72768 const path = path$A.join(root, 'package.json');
72769 return fs__default.existsSync(path);
72770}
72771/**
72772 * Search up for the nearest `package.json`
72773 */
72774function searchForPackageRoot(current, root = current) {
72775 if (hasPackageJSON(current))
72776 return current;
72777 const dir = path$A.dirname(current);
72778 // reach the fs root
72779 if (!dir || dir === current)
72780 return root;
72781 return searchForPackageRoot(dir, root);
72782}
72783/**
72784 * Search up for the nearest workspace root
72785 */
72786function searchForWorkspaceRoot(current, root = searchForPackageRoot(current)) {
72787 if (hasRootFile(current))
72788 return current;
72789 if (hasWorkspacePackageJSON(current))
72790 return current;
72791 const dir = path$A.dirname(current);
72792 // reach the fs root
72793 if (!dir || dir === current)
72794 return root;
72795 return searchForWorkspaceRoot(dir, root);
72796}
72797
72798async function createServer(inlineConfig = {}) {
72799 const config = await resolveConfig(inlineConfig, 'serve', 'development');
72800 const root = config.root;
72801 const serverConfig = config.server;
72802 const httpsOptions = await resolveHttpsConfig(config);
72803 let { middlewareMode } = serverConfig;
72804 if (middlewareMode === true) {
72805 middlewareMode = 'ssr';
72806 }
72807 const middlewares = connect();
72808 const httpServer = middlewareMode
72809 ? null
72810 : await resolveHttpServer(serverConfig, middlewares, httpsOptions);
72811 const ws = createWebSocketServer(httpServer, config, httpsOptions);
72812 const { ignored = [], ...watchOptions } = serverConfig.watch || {};
72813 const watcher = chokidar.watch(path__default.resolve(root), {
72814 ignored: ['**/node_modules/**', '**/.git/**', ...ignored],
72815 ignoreInitial: true,
72816 ignorePermissionErrors: true,
72817 disableGlobbing: true,
72818 ...watchOptions
72819 });
72820 const plugins = config.plugins;
72821 const container = await createPluginContainer(config, watcher);
72822 const moduleGraph = new ModuleGraph(container);
72823 const closeHttpServer = createServerCloseFn(httpServer);
72824 // eslint-disable-next-line prefer-const
72825 let exitProcess;
72826 const server = {
72827 config: config,
72828 middlewares,
72829 get app() {
72830 config.logger.warn(`ViteDevServer.app is deprecated. Use ViteDevServer.middlewares instead.`);
72831 return middlewares;
72832 },
72833 httpServer,
72834 watcher,
72835 pluginContainer: container,
72836 ws,
72837 moduleGraph,
72838 transformWithEsbuild,
72839 transformRequest(url, options) {
72840 return transformRequest(url, server, options);
72841 },
72842 transformIndexHtml: null,
72843 ssrLoadModule(url) {
72844 if (!server._ssrExternals) {
72845 server._ssrExternals = resolveSSRExternal(config, server._optimizeDepsMetadata
72846 ? Object.keys(server._optimizeDepsMetadata.optimized)
72847 : []);
72848 }
72849 return ssrLoadModule(url, server);
72850 },
72851 ssrFixStacktrace(e) {
72852 if (e.stack) {
72853 e.stack = ssrRewriteStacktrace(e.stack, moduleGraph);
72854 }
72855 },
72856 listen(port, isRestart) {
72857 return startServer(server, port, isRestart);
72858 },
72859 async close() {
72860 process.off('SIGTERM', exitProcess);
72861 if (!process.stdin.isTTY) {
72862 process.stdin.off('end', exitProcess);
72863 }
72864 await Promise.all([
72865 watcher.close(),
72866 ws.close(),
72867 container.close(),
72868 closeHttpServer()
72869 ]);
72870 },
72871 _optimizeDepsMetadata: null,
72872 _ssrExternals: null,
72873 _globImporters: {},
72874 _isRunningOptimizer: false,
72875 _registerMissingImport: null,
72876 _pendingReload: null
72877 };
72878 server.transformIndexHtml = createDevHtmlTransformFn(server);
72879 exitProcess = async () => {
72880 try {
72881 await server.close();
72882 }
72883 finally {
72884 process.exit(0);
72885 }
72886 };
72887 process.once('SIGTERM', exitProcess);
72888 if (process.env.CI !== 'true') {
72889 process.stdin.on('end', exitProcess);
72890 process.stdin.resume();
72891 }
72892 watcher.on('change', async (file) => {
72893 file = normalizePath$4(file);
72894 // invalidate module graph cache on file change
72895 moduleGraph.onFileChange(file);
72896 if (serverConfig.hmr !== false) {
72897 try {
72898 await handleHMRUpdate(file, server);
72899 }
72900 catch (err) {
72901 ws.send({
72902 type: 'error',
72903 err: prepareError(err)
72904 });
72905 }
72906 }
72907 });
72908 watcher.on('add', (file) => {
72909 handleFileAddUnlink(normalizePath$4(file), server);
72910 });
72911 watcher.on('unlink', (file) => {
72912 handleFileAddUnlink(normalizePath$4(file), server, true);
72913 });
72914 // apply server configuration hooks from plugins
72915 const postHooks = [];
72916 for (const plugin of plugins) {
72917 if (plugin.configureServer) {
72918 postHooks.push(await plugin.configureServer(server));
72919 }
72920 }
72921 // Internal middlewares ------------------------------------------------------
72922 // request timer
72923 if (process.env.DEBUG) {
72924 middlewares.use(timeMiddleware(root));
72925 }
72926 // cors (enabled by default)
72927 const { cors } = serverConfig;
72928 if (cors !== false) {
72929 middlewares.use(corsMiddleware(typeof cors === 'boolean' ? {} : cors));
72930 }
72931 // proxy
72932 const { proxy } = serverConfig;
72933 if (proxy) {
72934 middlewares.use(proxyMiddleware(httpServer, config));
72935 }
72936 // base
72937 if (config.base !== '/') {
72938 middlewares.use(baseMiddleware(server));
72939 }
72940 // open in editor support
72941 middlewares.use('/__open-in-editor', launchEditorMiddleware());
72942 // hmr reconnect ping
72943 // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
72944 middlewares.use('/__vite_ping', function viteHMRPingMiddleware(_, res) {
72945 res.end('pong');
72946 });
72947 //decode request url
72948 middlewares.use(decodeURIMiddleware());
72949 // serve static files under /public
72950 // this applies before the transform middleware so that these files are served
72951 // as-is without transforms.
72952 if (config.publicDir) {
72953 middlewares.use(servePublicMiddleware(config.publicDir));
72954 }
72955 // main transform middleware
72956 middlewares.use(transformMiddleware(server));
72957 // serve static files
72958 middlewares.use(serveRawFsMiddleware(server));
72959 middlewares.use(serveStaticMiddleware(root, config));
72960 // spa fallback
72961 if (!middlewareMode || middlewareMode === 'html') {
72962 middlewares.use(history({
72963 logger: createDebugger('vite:spa-fallback'),
72964 // support /dir/ without explicit index.html
72965 rewrites: [
72966 {
72967 from: /\/$/,
72968 to({ parsedUrl }) {
72969 const rewritten = parsedUrl.pathname + 'index.html';
72970 if (fs__default.existsSync(path__default.join(root, rewritten))) {
72971 return rewritten;
72972 }
72973 else {
72974 return `/index.html`;
72975 }
72976 }
72977 }
72978 ]
72979 }));
72980 }
72981 // run post config hooks
72982 // This is applied before the html middleware so that user middleware can
72983 // serve custom content instead of index.html.
72984 postHooks.forEach((fn) => fn && fn());
72985 if (!middlewareMode || middlewareMode === 'html') {
72986 // transform index.html
72987 middlewares.use(indexHtmlMiddleware(server));
72988 // handle 404s
72989 // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
72990 middlewares.use(function vite404Middleware(_, res) {
72991 res.statusCode = 404;
72992 res.end();
72993 });
72994 }
72995 // error handler
72996 middlewares.use(errorMiddleware(server, !!middlewareMode));
72997 const runOptimize = async () => {
72998 if (config.cacheDir) {
72999 server._isRunningOptimizer = true;
73000 try {
73001 server._optimizeDepsMetadata = await optimizeDeps(config);
73002 }
73003 finally {
73004 server._isRunningOptimizer = false;
73005 }
73006 server._registerMissingImport = createMissingImporterRegisterFn(server);
73007 }
73008 };
73009 if (!middlewareMode && httpServer) {
73010 // overwrite listen to run optimizer before server start
73011 const listen = httpServer.listen.bind(httpServer);
73012 httpServer.listen = (async (port, ...args) => {
73013 try {
73014 await container.buildStart({});
73015 await runOptimize();
73016 }
73017 catch (e) {
73018 httpServer.emit('error', e);
73019 return;
73020 }
73021 return listen(port, ...args);
73022 });
73023 httpServer.once('listening', () => {
73024 // update actual port since this may be different from initial value
73025 serverConfig.port = httpServer.address().port;
73026 });
73027 }
73028 else {
73029 await container.buildStart({});
73030 await runOptimize();
73031 }
73032 return server;
73033}
73034async function startServer(server, inlinePort, isRestart = false) {
73035 const httpServer = server.httpServer;
73036 if (!httpServer) {
73037 throw new Error('Cannot call server.listen in middleware mode.');
73038 }
73039 const options = server.config.server;
73040 let port = inlinePort || options.port || 3000;
73041 const hostname = resolveHostname(options.host);
73042 const protocol = options.https ? 'https' : 'http';
73043 const info = server.config.logger.info;
73044 const base = server.config.base;
73045 return new Promise((resolve, reject) => {
73046 const onError = (e) => {
73047 if (e.code === 'EADDRINUSE') {
73048 if (options.strictPort) {
73049 httpServer.removeListener('error', onError);
73050 reject(new Error(`Port ${port} is already in use`));
73051 }
73052 else {
73053 info(`Port ${port} is in use, trying another one...`);
73054 httpServer.listen(++port, hostname.host);
73055 }
73056 }
73057 else {
73058 httpServer.removeListener('error', onError);
73059 reject(e);
73060 }
73061 };
73062 httpServer.on('error', onError);
73063 httpServer.listen(port, hostname.host, () => {
73064 httpServer.removeListener('error', onError);
73065 info(source.cyan(`\n vite v${require('vite/package.json').version}`) +
73066 source.green(` dev server running at:\n`), {
73067 clear: !server.config.logger.hasWarned
73068 });
73069 printServerUrls(hostname, protocol, port, base, info);
73070 // @ts-ignore
73071 if (global.__vite_start_time) {
73072 info(source.cyan(
73073 // @ts-ignore
73074 `\n ready in ${Date.now() - global.__vite_start_time}ms.\n`));
73075 }
73076 // @ts-ignore
73077 const profileSession = global.__vite_profile_session;
73078 if (profileSession) {
73079 profileSession.post('Profiler.stop', (err, { profile }) => {
73080 // Write profile to disk, upload, etc.
73081 if (!err) {
73082 const outPath = path__default.resolve('./vite-profile.cpuprofile');
73083 fs__default.writeFileSync(outPath, JSON.stringify(profile));
73084 info(source.yellow(` CPU profile written to ${source.white.dim(outPath)}\n`));
73085 }
73086 else {
73087 throw err;
73088 }
73089 });
73090 }
73091 if (options.open && !isRestart) {
73092 const path = typeof options.open === 'string' ? options.open : base;
73093 openBrowser(`${protocol}://${hostname.name}:${port}${path}`, true, server.config.logger);
73094 }
73095 resolve(server);
73096 });
73097 });
73098}
73099function createServerCloseFn(server) {
73100 if (!server) {
73101 return () => { };
73102 }
73103 let hasListened = false;
73104 const openSockets = new Set();
73105 server.on('connection', (socket) => {
73106 openSockets.add(socket);
73107 socket.on('close', () => {
73108 openSockets.delete(socket);
73109 });
73110 });
73111 server.once('listening', () => {
73112 hasListened = true;
73113 });
73114 return () => new Promise((resolve, reject) => {
73115 openSockets.forEach((s) => s.destroy());
73116 if (hasListened) {
73117 server.close((err) => {
73118 if (err) {
73119 reject(err);
73120 }
73121 else {
73122 resolve();
73123 }
73124 });
73125 }
73126 else {
73127 resolve();
73128 }
73129 });
73130}
73131function resolvedAllowDir(root, dir) {
73132 return ensureLeadingSlash(normalizePath$4(path__default.resolve(root, dir)));
73133}
73134function resolveServerOptions(root, raw) {
73135 var _a, _b;
73136 const server = raw || {};
73137 let allowDirs = (_a = server.fs) === null || _a === void 0 ? void 0 : _a.allow;
73138 if (!allowDirs) {
73139 allowDirs = [searchForWorkspaceRoot(root)];
73140 }
73141 allowDirs = allowDirs.map((i) => resolvedAllowDir(root, i));
73142 // only push client dir when vite itself is outside-of-root
73143 const resolvedClientDir = resolvedAllowDir(root, CLIENT_DIR);
73144 if (!allowDirs.some((i) => resolvedClientDir.startsWith(i))) {
73145 allowDirs.push(resolvedClientDir);
73146 }
73147 server.fs = {
73148 // TODO: make strict by default
73149 strict: (_b = server.fs) === null || _b === void 0 ? void 0 : _b.strict,
73150 allow: allowDirs
73151 };
73152 return server;
73153}
73154
73155var index = {
73156 __proto__: null,
73157 createServer: createServer,
73158 resolveServerOptions: resolveServerOptions
73159};
73160
73161const VOLUME = /^([A-Z]:)/i;
73162const IS_WINDOWS = require$$0$6.platform() === 'win32';
73163const noop = () => null;
73164function matches(pattern, importee) {
73165 if (pattern instanceof RegExp) {
73166 return pattern.test(importee);
73167 }
73168 if (importee.length < pattern.length) {
73169 return false;
73170 }
73171 if (importee === pattern) {
73172 return true;
73173 }
73174 const importeeStartsWithKey = importee.indexOf(pattern) === 0;
73175 const importeeHasSlashAfterKey = importee.substring(pattern.length)[0] === '/';
73176 return importeeStartsWithKey && importeeHasSlashAfterKey;
73177}
73178function normalizeId(id) {
73179 if (typeof id === 'string' && (IS_WINDOWS || VOLUME.test(id))) {
73180 return slash$1(id.replace(VOLUME, ''));
73181 }
73182 return id;
73183}
73184function getEntries({ entries }) {
73185 if (!entries) {
73186 return [];
73187 }
73188 if (Array.isArray(entries)) {
73189 return entries;
73190 }
73191 return Object.entries(entries).map(([key, value]) => {
73192 return { find: key, replacement: value };
73193 });
73194}
73195function getCustomResolver({ customResolver }, options) {
73196 if (typeof customResolver === 'function') {
73197 return customResolver;
73198 }
73199 if (customResolver && typeof customResolver.resolveId === 'function') {
73200 return customResolver.resolveId;
73201 }
73202 if (typeof options.customResolver === 'function') {
73203 return options.customResolver;
73204 }
73205 if (options.customResolver && typeof options.customResolver.resolveId === 'function') {
73206 return options.customResolver.resolveId;
73207 }
73208 return null;
73209}
73210function alias(options = {}) {
73211 const entries = getEntries(options);
73212 if (entries.length === 0) {
73213 return {
73214 name: 'alias',
73215 resolveId: noop
73216 };
73217 }
73218 return {
73219 name: 'alias',
73220 buildStart(inputOptions) {
73221 return Promise.all([...entries, options].map(({ customResolver }) => customResolver &&
73222 typeof customResolver === 'object' &&
73223 typeof customResolver.buildStart === 'function' &&
73224 customResolver.buildStart.call(this, inputOptions))).then(() => {
73225 // enforce void return value
73226 });
73227 },
73228 resolveId(importee, importer) {
73229 const importeeId = normalizeId(importee);
73230 const importerId = normalizeId(importer);
73231 // First match is supposed to be the correct one
73232 const matchedEntry = entries.find((entry) => matches(entry.find, importeeId));
73233 if (!matchedEntry || !importerId) {
73234 return null;
73235 }
73236 const updatedId = normalizeId(importeeId.replace(matchedEntry.find, matchedEntry.replacement));
73237 const customResolver = getCustomResolver(matchedEntry, options);
73238 if (customResolver) {
73239 return customResolver.call(this, updatedId, importerId, {});
73240 }
73241 return this.resolve(updatedId, importer, { skipSelf: true }).then((resolved) => {
73242 let finalResult = resolved;
73243 if (!finalResult) {
73244 finalResult = { id: updatedId };
73245 }
73246 return finalResult;
73247 });
73248 }
73249 };
73250}
73251
73252/**
73253 * https://github.com/rollup/plugins/blob/master/packages/json/src/index.js
73254 *
73255 * This source code is licensed under the MIT license found in the
73256 * LICENSE file at
73257 * https://github.com/rollup/plugins/blob/master/LICENSE
73258 */
73259// Custom json filter for vite
73260const jsonExtRE = /\.json($|\?)(?!commonjs-proxy)/;
73261function jsonPlugin(options = {}, isBuild) {
73262 return {
73263 name: 'vite:json',
73264 transform(json, id) {
73265 if (!jsonExtRE.test(id))
73266 return null;
73267 if (SPECIAL_QUERY_RE.test(id))
73268 return null;
73269 try {
73270 if (options.stringify) {
73271 if (isBuild) {
73272 return {
73273 // during build, parse then double-stringify to remove all
73274 // unnecessary whitespaces to reduce bundle size.
73275 code: `export default JSON.parse(${JSON.stringify(JSON.stringify(JSON.parse(json)))})`,
73276 map: { mappings: '' }
73277 };
73278 }
73279 else {
73280 return `export default JSON.parse(${JSON.stringify(json)})`;
73281 }
73282 }
73283 const parsed = JSON.parse(json);
73284 return {
73285 code: dataToEsm(parsed, {
73286 preferConst: true,
73287 namedExports: options.namedExports
73288 }),
73289 map: { mappings: '' }
73290 };
73291 }
73292 catch (e) {
73293 const errorMessageList = /[\d]+/.exec(e.message);
73294 const position = errorMessageList && parseInt(errorMessageList[0], 10);
73295 const msg = position
73296 ? `, invalid JSON syntax found at line ${position}`
73297 : `.`;
73298 this.error(`Failed to parse JSON file` + msg, e.idx);
73299 }
73300 }
73301 };
73302}
73303
73304const isDebug = !!process.env.DEBUG;
73305const debugRewrite = createDebugger('vite:rewrite');
73306const clientDir = normalizePath$4(CLIENT_DIR);
73307const skipRE = /\.(map|json)$/;
73308const canSkip = (id) => skipRE.test(id) || isDirectCSSRequest(id);
73309function isExplicitImportRequired(url) {
73310 return !isJSRequest(cleanUrl(url)) && !isCSSRequest(url);
73311}
73312function markExplicitImport(url) {
73313 if (isExplicitImportRequired(url)) {
73314 return injectQuery(url, 'import');
73315 }
73316 return url;
73317}
73318/**
73319 * Server-only plugin that lexes, resolves, rewrites and analyzes url imports.
73320 *
73321 * - Imports are resolved to ensure they exist on disk
73322 *
73323 * - Lexes HMR accept calls and updates import relationships in the module graph
73324 *
73325 * - Bare module imports are resolved (by @rollup-plugin/node-resolve) to
73326 * absolute file paths, e.g.
73327 *
73328 * ```js
73329 * import 'foo'
73330 * ```
73331 * is rewritten to
73332 * ```js
73333 * import '/@fs//project/node_modules/foo/dist/foo.js'
73334 * ```
73335 *
73336 * - CSS imports are appended with `.js` since both the js module and the actual
73337 * css (referenced via <link>) may go through the transform pipeline:
73338 *
73339 * ```js
73340 * import './style.css'
73341 * ```
73342 * is rewritten to
73343 * ```js
73344 * import './style.css.js'
73345 * ```
73346 */
73347function importAnalysisPlugin(config) {
73348 const { root, base } = config;
73349 const clientPublicPath = path__default.posix.join(base, CLIENT_PUBLIC_PATH);
73350 let server;
73351 return {
73352 name: 'vite:import-analysis',
73353 configureServer(_server) {
73354 server = _server;
73355 },
73356 async transform(source$1, importer, ssr) {
73357 const prettyImporter = prettifyUrl(importer, root);
73358 if (canSkip(importer)) {
73359 isDebug && debugRewrite(source.dim(`[skipped] ${prettyImporter}`));
73360 return null;
73361 }
73362 const rewriteStart = Date.now();
73363 await init;
73364 let imports = [];
73365 // strip UTF-8 BOM
73366 if (source$1.charCodeAt(0) === 0xfeff) {
73367 source$1 = source$1.slice(1);
73368 }
73369 try {
73370 imports = parse$e(source$1)[0];
73371 }
73372 catch (e) {
73373 const isVue = importer.endsWith('.vue');
73374 const maybeJSX = !isVue && isJSRequest(importer);
73375 const msg = isVue
73376 ? `Install @vitejs/plugin-vue to handle .vue files.`
73377 : maybeJSX
73378 ? `If you are using JSX, make sure to name the file with the .jsx or .tsx extension.`
73379 : `You may need to install appropriate plugins to handle the ${path__default.extname(importer)} file format.`;
73380 this.error(`Failed to parse source for import analysis because the content ` +
73381 `contains invalid JS syntax. ` +
73382 msg, e.idx);
73383 }
73384 if (!imports.length) {
73385 isDebug &&
73386 debugRewrite(`${timeFrom(rewriteStart)} ${source.dim(`[no imports] ${prettyImporter}`)}`);
73387 return source$1;
73388 }
73389 let hasHMR = false;
73390 let isSelfAccepting = false;
73391 let hasEnv = false;
73392 let needQueryInjectHelper = false;
73393 let s;
73394 const str = () => s || (s = new MagicString(source$1));
73395 // vite-only server context
73396 const { moduleGraph } = server;
73397 // since we are already in the transform phase of the importer, it must
73398 // have been loaded so its entry is guaranteed in the module graph.
73399 const importerModule = moduleGraph.getModuleById(importer);
73400 const importedUrls = new Set();
73401 const acceptedUrls = new Set();
73402 const toAbsoluteUrl = (url) => path__default.posix.resolve(path__default.posix.dirname(importerModule.url), url);
73403 const normalizeUrl = async (url, pos) => {
73404 if (base !== '/' && url.startsWith(base)) {
73405 url = url.replace(base, '/');
73406 }
73407 const resolved = await this.resolve(url, importer);
73408 if (!resolved) {
73409 this.error(`Failed to resolve import "${url}" from "${path__default.relative(process.cwd(), importer)}". Does the file exist?`, pos);
73410 }
73411 const isRelative = url.startsWith('.');
73412 // normalize all imports into resolved URLs
73413 // e.g. `import 'foo'` -> `import '/@fs/.../node_modules/foo/index.js`
73414 if (resolved.id.startsWith(root + '/')) {
73415 // in root: infer short absolute path from root
73416 url = resolved.id.slice(root.length);
73417 }
73418 else if (fs__default.existsSync(cleanUrl(resolved.id))) {
73419 // exists but out of root: rewrite to absolute /@fs/ paths
73420 url = path__default.posix.join(FS_PREFIX + resolved.id);
73421 }
73422 else {
73423 url = resolved.id;
73424 }
73425 if (isExternalUrl(url)) {
73426 return [url, url];
73427 }
73428 // if the resolved id is not a valid browser import specifier,
73429 // prefix it to make it valid. We will strip this before feeding it
73430 // back into the transform pipeline
73431 if (!url.startsWith('.') && !url.startsWith('/')) {
73432 url =
73433 VALID_ID_PREFIX + resolved.id.replace('\0', NULL_BYTE_PLACEHOLDER);
73434 }
73435 // make the URL browser-valid if not SSR
73436 if (!ssr) {
73437 // mark non-js/css imports with `?import`
73438 url = markExplicitImport(url);
73439 // for relative js/css imports, inherit importer's version query
73440 // do not do this for unknown type imports, otherwise the appended
73441 // query can break 3rd party plugin's extension checks.
73442 if (isRelative && !/[\?&]import=?\b/.test(url)) {
73443 const versionMatch = importer.match(DEP_VERSION_RE);
73444 if (versionMatch) {
73445 url = injectQuery(url, versionMatch[1]);
73446 }
73447 }
73448 // check if the dep has been hmr updated. If yes, we need to attach
73449 // its last updated timestamp to force the browser to fetch the most
73450 // up-to-date version of this module.
73451 try {
73452 const depModule = await moduleGraph.ensureEntryFromUrl(url);
73453 if (depModule.lastHMRTimestamp > 0) {
73454 url = injectQuery(url, `t=${depModule.lastHMRTimestamp}`);
73455 }
73456 }
73457 catch (e) {
73458 // it's possible that the dep fails to resolve (non-existent import)
73459 // attach location to the missing import
73460 e.pos = pos;
73461 throw e;
73462 }
73463 // prepend base (dev base is guaranteed to have ending slash)
73464 url = base + url.replace(/^\//, '');
73465 }
73466 return [url, resolved.id];
73467 };
73468 for (let index = 0; index < imports.length; index++) {
73469 const { s: start, e: end, ss: expStart, se: expEnd, d: dynamicIndex,
73470 // #2083 User may use escape path,
73471 // so use imports[index].n to get the unescaped string
73472 // @ts-ignore
73473 n: specifier } = imports[index];
73474 const rawUrl = source$1.slice(start, end);
73475 // check import.meta usage
73476 if (rawUrl === 'import.meta') {
73477 const prop = source$1.slice(end, end + 4);
73478 if (prop === '.hot') {
73479 hasHMR = true;
73480 if (source$1.slice(end + 4, end + 11) === '.accept') {
73481 // further analyze accepted modules
73482 if (lexAcceptedHmrDeps(source$1, source$1.indexOf('(', end + 11) + 1, acceptedUrls)) {
73483 isSelfAccepting = true;
73484 }
73485 }
73486 }
73487 else if (prop === '.env') {
73488 hasEnv = true;
73489 }
73490 else if (prop === '.glo' && source$1[end + 4] === 'b') {
73491 // transform import.meta.glob()
73492 // e.g. `import.meta.glob('glob:./dir/*.js')`
73493 const { imports, importsString, exp, endIndex, base, pattern } = await transformImportGlob(source$1, start, importer, index, root, normalizeUrl);
73494 str().prepend(importsString);
73495 str().overwrite(expStart, endIndex, exp);
73496 imports.forEach((url) => importedUrls.add(url.replace(base, '/')));
73497 if (!(importerModule.file in server._globImporters)) {
73498 server._globImporters[importerModule.file] = {
73499 module: importerModule,
73500 importGlobs: []
73501 };
73502 }
73503 server._globImporters[importerModule.file].importGlobs.push({
73504 base,
73505 pattern
73506 });
73507 }
73508 continue;
73509 }
73510 const isDynamicImport = dynamicIndex >= 0;
73511 // static import or valid string in dynamic import
73512 // If resolvable, let's resolve it
73513 if (specifier) {
73514 // skip external / data uri
73515 if (isExternalUrl(specifier) || isDataUrl(specifier)) {
73516 continue;
73517 }
73518 // skip ssr external
73519 if (ssr) {
73520 if (server._ssrExternals &&
73521 shouldExternalizeForSSR(specifier, server._ssrExternals)) {
73522 continue;
73523 }
73524 if (isBuiltin(specifier)) {
73525 continue;
73526 }
73527 }
73528 // skip client
73529 if (specifier === clientPublicPath) {
73530 continue;
73531 }
73532 // warn imports to non-asset /public files
73533 if (specifier.startsWith('/') &&
73534 !config.assetsInclude(cleanUrl(specifier)) &&
73535 !specifier.endsWith('.json') &&
73536 checkPublicFile(specifier, config)) {
73537 throw new Error(`Cannot import non-asset file ${specifier} which is inside /public.` +
73538 `JS/CSS files inside /public are copied as-is on build and ` +
73539 `can only be referenced via <script src> or <link href> in html.`);
73540 }
73541 // normalize
73542 const [normalizedUrl, resolvedId] = await normalizeUrl(specifier, start);
73543 let url = normalizedUrl;
73544 // record as safe modules
73545 server === null || server === void 0 ? void 0 : server.moduleGraph.safeModulesPath.add(cleanUrl(url).slice(4 /* '/@fs'.length */));
73546 // rewrite
73547 if (url !== specifier) {
73548 // for optimized cjs deps, support named imports by rewriting named
73549 // imports to const assignments.
73550 if (resolvedId.endsWith(`&es-interop`)) {
73551 url = url.slice(0, -11);
73552 if (isDynamicImport) {
73553 // rewrite `import('package')` to expose the default directly
73554 str().overwrite(dynamicIndex, end + 1, `import('${url}').then(m => ({ ...m.default, default: m.default }))`);
73555 }
73556 else {
73557 const exp = source$1.slice(expStart, expEnd);
73558 const rewritten = transformCjsImport(exp, url, rawUrl, index);
73559 if (rewritten) {
73560 str().overwrite(expStart, expEnd, rewritten);
73561 }
73562 else {
73563 // #1439 export * from '...'
73564 str().overwrite(start, end, url);
73565 }
73566 }
73567 }
73568 else {
73569 str().overwrite(start, end, isDynamicImport ? `'${url}'` : url);
73570 }
73571 }
73572 // record for HMR import chain analysis
73573 // make sure to normalize away base
73574 importedUrls.add(url.replace(base, '/'));
73575 }
73576 else if (!importer.startsWith(clientDir) && !ssr) {
73577 // check @vite-ignore which suppresses dynamic import warning
73578 const hasViteIgnore = /\/\*\s*@vite-ignore\s*\*\//.test(rawUrl);
73579 const url = rawUrl
73580 .replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm, '')
73581 .trim();
73582 if (!hasViteIgnore && !isSupportedDynamicImport(url)) {
73583 this.warn(`\n` +
73584 source.cyan(importerModule.file) +
73585 `\n` +
73586 generateCodeFrame(source$1, start) +
73587 `\nThe above dynamic import cannot be analyzed by vite.\n` +
73588 `See ${source.blue(`https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations`)} ` +
73589 `for supported dynamic import formats. ` +
73590 `If this is intended to be left as-is, you can use the ` +
73591 `/* @vite-ignore */ comment inside the import() call to suppress this warning.\n`);
73592 }
73593 if (!/^('.*'|".*"|`.*`)$/.test(url) ||
73594 isExplicitImportRequired(url.slice(1, -1))) {
73595 needQueryInjectHelper = true;
73596 str().overwrite(start, end, `__vite__injectQuery(${url}, 'import')`);
73597 }
73598 }
73599 }
73600 if (hasEnv) {
73601 // inject import.meta.env
73602 let env = `import.meta.env = ${JSON.stringify({
73603 ...config.env,
73604 SSR: !!ssr
73605 })};`;
73606 // account for user env defines
73607 for (const key in config.define) {
73608 if (key.startsWith(`import.meta.env.`)) {
73609 const val = config.define[key];
73610 env += `${key} = ${typeof val === 'string' ? val : JSON.stringify(val)};`;
73611 }
73612 }
73613 str().prepend(env);
73614 }
73615 if (hasHMR && !ssr) {
73616 debugHmr(`${isSelfAccepting
73617 ? `[self-accepts]`
73618 : acceptedUrls.size
73619 ? `[accepts-deps]`
73620 : `[detected api usage]`} ${prettyImporter}`);
73621 // inject hot context
73622 str().prepend(`import { createHotContext as __vite__createHotContext } from "${clientPublicPath}";` +
73623 `import.meta.hot = __vite__createHotContext(${JSON.stringify(importerModule.url)});`);
73624 }
73625 if (needQueryInjectHelper) {
73626 str().prepend(`import { injectQuery as __vite__injectQuery } from "${clientPublicPath}";`);
73627 }
73628 // normalize and rewrite accepted urls
73629 const normalizedAcceptedUrls = new Set();
73630 for (const { url, start, end } of acceptedUrls) {
73631 const [normalized] = await moduleGraph.resolveUrl(toAbsoluteUrl(markExplicitImport(url)));
73632 normalizedAcceptedUrls.add(normalized);
73633 str().overwrite(start, end, JSON.stringify(normalized));
73634 }
73635 // update the module graph for HMR analysis.
73636 // node CSS imports does its own graph update in the css plugin so we
73637 // only handle js graph updates here.
73638 if (!isCSSRequest(importer)) {
73639 const prunedImports = await moduleGraph.updateModuleInfo(importerModule, importedUrls, normalizedAcceptedUrls, isSelfAccepting);
73640 if (hasHMR && prunedImports) {
73641 handlePrunedModules(prunedImports, server);
73642 }
73643 }
73644 if (s) {
73645 return s.toString();
73646 }
73647 else {
73648 return source$1;
73649 }
73650 }
73651 };
73652}
73653/**
73654 * https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations
73655 * This is probably less accurate but is much cheaper than a full AST parse.
73656 */
73657function isSupportedDynamicImport(url) {
73658 url = url.trim().slice(1, -1);
73659 // must be relative
73660 if (!url.startsWith('./') && !url.startsWith('../')) {
73661 return false;
73662 }
73663 // must have extension
73664 if (!path__default.extname(url)) {
73665 return false;
73666 }
73667 // must be more specific if importing from same dir
73668 if (url.startsWith('./${') && url.indexOf('/') === url.lastIndexOf('/')) {
73669 return false;
73670 }
73671 return true;
73672}
73673/**
73674 * Detect import statements to a known optimized CJS dependency and provide
73675 * ES named imports interop. We do this by rewriting named imports to a variable
73676 * assignment to the corresponding property on the `module.exports` of the cjs
73677 * module. Note this doesn't support dynamic re-assignments from within the cjs
73678 * module.
73679 *
73680 * Note that es-module-lexer treats `export * from '...'` as an import as well,
73681 * so, we may encounter ExportAllDeclaration here, in which case `undefined`
73682 * will be returned.
73683 *
73684 * Credits \@csr632 via #837
73685 */
73686function transformCjsImport(importExp, url, rawUrl, importIndex) {
73687 const node = parse$c(importExp, {
73688 ecmaVersion: 2020,
73689 sourceType: 'module'
73690 }).body[0];
73691 if (node.type === 'ImportDeclaration') {
73692 if (!node.specifiers.length) {
73693 return `import "${url}"`;
73694 }
73695 const importNames = [];
73696 for (const spec of node.specifiers) {
73697 if (spec.type === 'ImportSpecifier' &&
73698 spec.imported.type === 'Identifier') {
73699 const importedName = spec.imported.name;
73700 const localName = spec.local.name;
73701 importNames.push({ importedName, localName });
73702 }
73703 else if (spec.type === 'ImportDefaultSpecifier') {
73704 importNames.push({
73705 importedName: 'default',
73706 localName: spec.local.name
73707 });
73708 }
73709 else if (spec.type === 'ImportNamespaceSpecifier') {
73710 importNames.push({ importedName: '*', localName: spec.local.name });
73711 }
73712 }
73713 // If there is multiple import for same id in one file,
73714 // importIndex will prevent the cjsModuleName to be duplicate
73715 const cjsModuleName = makeLegalIdentifier$1(`__vite__cjsImport${importIndex}_${rawUrl}`);
73716 const lines = [`import ${cjsModuleName} from "${url}"`];
73717 importNames.forEach(({ importedName, localName }) => {
73718 if (importedName === '*') {
73719 lines.push(`const ${localName} = ${cjsModuleName}`);
73720 }
73721 else if (importedName === 'default') {
73722 lines.push(`const ${localName} = ${cjsModuleName}.__esModule ? ${cjsModuleName}.default : ${cjsModuleName}`);
73723 }
73724 else {
73725 lines.push(`const ${localName} = ${cjsModuleName}["${importedName}"]`);
73726 }
73727 });
73728 return lines.join('; ');
73729 }
73730}
73731
73732// ids in transform are normalized to unix style
73733const normalizedClientEntry = normalizePath$4(CLIENT_ENTRY);
73734const normalizedEnvEntry = normalizePath$4(ENV_ENTRY);
73735/**
73736 * some values used by the client needs to be dynamically injected by the server
73737 * @server-only
73738 */
73739function clientInjectionsPlugin(config) {
73740 return {
73741 name: 'vite:client-inject',
73742 transform(code, id) {
73743 if (id === normalizedClientEntry || id === normalizedEnvEntry) {
73744 let options = config.server.hmr;
73745 options = options && typeof options !== 'boolean' ? options : {};
73746 const host = options.host || null;
73747 const protocol = options.protocol || null;
73748 const timeout = options.timeout || 30000;
73749 const overlay = options.overlay !== false;
73750 let port;
73751 if (config.server.middlewareMode) {
73752 if (typeof config.server.hmr === 'object') {
73753 port = config.server.hmr.clientPort || config.server.hmr.port;
73754 }
73755 port = String(port || 24678);
73756 }
73757 else {
73758 port = String(options.port || config.server.port);
73759 }
73760 let hmrBase = config.base;
73761 if (options.path) {
73762 hmrBase = path__default.posix.join(hmrBase, options.path);
73763 }
73764 if (hmrBase !== '/') {
73765 port = path__default.posix.normalize(`${port}${hmrBase}`);
73766 }
73767 return code
73768 .replace(`__MODE__`, JSON.stringify(config.mode))
73769 .replace(`__BASE__`, JSON.stringify(config.base))
73770 .replace(`__ROOT__`, JSON.stringify(config.root))
73771 .replace(`__DEFINES__`, serializeDefine(config.define || {}))
73772 .replace(`__HMR_PROTOCOL__`, JSON.stringify(protocol))
73773 .replace(`__HMR_HOSTNAME__`, JSON.stringify(host))
73774 .replace(`__HMR_PORT__`, JSON.stringify(port))
73775 .replace(`__HMR_TIMEOUT__`, JSON.stringify(timeout))
73776 .replace(`__HMR_ENABLE_OVERLAY__`, JSON.stringify(overlay));
73777 }
73778 else if (code.includes('process.env.NODE_ENV')) {
73779 // replace process.env.NODE_ENV
73780 return code.replace(/\bprocess\.env\.NODE_ENV\b/g, JSON.stringify(config.mode));
73781 }
73782 }
73783 };
73784}
73785function serializeDefine(define) {
73786 let res = `{`;
73787 for (const key in define) {
73788 const val = define[key];
73789 res += `${JSON.stringify(key)}: ${typeof val === 'string' ? `(${val})` : JSON.stringify(val)}, `;
73790 }
73791 return res + `}`;
73792}
73793
73794const wasmHelperId = '/__vite-wasm-helper';
73795const wasmHelper = async (opts = {}, url) => {
73796 let result;
73797 if (url.startsWith('data:')) {
73798 // @ts-ignore
73799 const binaryString = atob(url.replace(/^data:.*?base64,/, ''));
73800 const bytes = new Uint8Array(binaryString.length);
73801 for (let i = 0; i < binaryString.length; i++) {
73802 bytes[i] = binaryString.charCodeAt(i);
73803 }
73804 // @ts-ignore
73805 result = await WebAssembly.instantiate(bytes, opts);
73806 }
73807 else {
73808 // https://github.com/mdn/webassembly-examples/issues/5
73809 // WebAssembly.instantiateStreaming requires the server to provide the
73810 // correct MIME type for .wasm files, which unfortunately doesn't work for
73811 // a lot of static file servers, so we just work around it by getting the
73812 // raw buffer.
73813 // @ts-ignore
73814 const response = await fetch(url);
73815 const contentType = response.headers.get('Content-Type') || '';
73816 if (
73817 // @ts-ignore
73818 'instantiateStreaming' in WebAssembly &&
73819 contentType.startsWith('application/wasm')) {
73820 // @ts-ignore
73821 result = await WebAssembly.instantiateStreaming(response, opts);
73822 }
73823 else {
73824 const buffer = await response.arrayBuffer();
73825 // @ts-ignore
73826 result = await WebAssembly.instantiate(buffer, opts);
73827 }
73828 }
73829 return result.instance.exports;
73830};
73831const wasmHelperCode = wasmHelper.toString();
73832const wasmPlugin = (config) => {
73833 return {
73834 name: 'vite:wasm',
73835 resolveId(id) {
73836 if (id === wasmHelperId) {
73837 return id;
73838 }
73839 },
73840 async load(id) {
73841 if (id === wasmHelperId) {
73842 return `export default ${wasmHelperCode}`;
73843 }
73844 if (!id.endsWith('.wasm')) {
73845 return;
73846 }
73847 const url = await fileToUrl(id, config, this);
73848 return `
73849import initWasm from "${wasmHelperId}"
73850export default opts => initWasm(opts, ${JSON.stringify(url)})
73851`;
73852 }
73853 };
73854};
73855
73856function parseWorkerRequest(id) {
73857 const { search } = require$$0$b.parse(id);
73858 if (!search) {
73859 return null;
73860 }
73861 return qs__default.parse(search.slice(1));
73862}
73863const WorkerFileId = 'worker_file';
73864function webWorkerPlugin(config) {
73865 const isBuild = config.command === 'build';
73866 return {
73867 name: 'vite:worker',
73868 load(id) {
73869 var _a;
73870 if (isBuild) {
73871 const parsedQuery = parseWorkerRequest(id);
73872 if (parsedQuery &&
73873 ((_a = parsedQuery.worker) !== null && _a !== void 0 ? _a : parsedQuery.sharedworker) != null) {
73874 return '';
73875 }
73876 }
73877 },
73878 async transform(_, id) {
73879 var _a;
73880 const query = parseWorkerRequest(id);
73881 if (query && query[WorkerFileId] != null) {
73882 return {
73883 code: `import '${ENV_PUBLIC_PATH}'\n` + _
73884 };
73885 }
73886 if (query == null ||
73887 (query && ((_a = query.worker) !== null && _a !== void 0 ? _a : query.sharedworker) == null)) {
73888 return;
73889 }
73890 let url;
73891 if (isBuild) {
73892 // bundle the file as entry to support imports
73893 const rollup = require('rollup');
73894 const bundle = await rollup.rollup({
73895 input: cleanUrl(id),
73896 plugins: await resolvePlugins({ ...config }, [], [], [])
73897 });
73898 let code;
73899 try {
73900 const { output } = await bundle.generate({
73901 format: 'iife',
73902 sourcemap: config.build.sourcemap
73903 });
73904 code = output[0].code;
73905 }
73906 finally {
73907 await bundle.close();
73908 }
73909 const content = Buffer.from(code);
73910 if (query.inline != null) {
73911 // inline as blob data url
73912 return `const blob = new Blob([atob(\"${content.toString('base64')}\")], { type: 'text/javascript;charset=utf-8' });
73913 export default function WorkerWrapper() {
73914 const objURL = (window.URL || window.webkitURL).createObjectURL(blob);
73915 try {
73916 return new Worker(objURL);
73917 } finally {
73918 (window.URL || window.webkitURL).revokeObjectURL(objURL);
73919 }
73920 }`;
73921 }
73922 else {
73923 const basename = path__default.parse(cleanUrl(id)).name;
73924 const contentHash = getAssetHash(content);
73925 const fileName = path__default.posix.join(config.build.assetsDir, `${basename}.${contentHash}.js`);
73926 url = `__VITE_ASSET__${this.emitFile({
73927 fileName,
73928 type: 'asset',
73929 source: code
73930 })}__`;
73931 }
73932 }
73933 else {
73934 url = await fileToUrl(cleanUrl(id), config, this);
73935 url = injectQuery(url, WorkerFileId);
73936 }
73937 const workerConstructor = query.sharedworker != null ? 'SharedWorker' : 'Worker';
73938 const workerOptions = { type: 'module' };
73939 return `export default function WorkerWrapper() {
73940 return new ${workerConstructor}(${JSON.stringify(url)}, ${JSON.stringify(workerOptions, null, 2)})
73941 }`;
73942 }
73943 };
73944}
73945
73946/**
73947 * A plugin to avoid an aliased AND optimized dep from being aliased in src
73948 */
73949function preAliasPlugin() {
73950 let server;
73951 return {
73952 name: 'vite:pre-alias',
73953 configureServer(_server) {
73954 server = _server;
73955 },
73956 resolveId(id, _, __, ssr) {
73957 if (!ssr && bareImportRE.test(id)) {
73958 return tryOptimizedResolve(id, server);
73959 }
73960 }
73961 };
73962}
73963
73964function definePlugin(config) {
73965 const isBuild = config.command === 'build';
73966 const userDefine = {};
73967 for (const key in config.define) {
73968 const val = config.define[key];
73969 userDefine[key] = typeof val === 'string' ? val : JSON.stringify(val);
73970 }
73971 // during dev, import.meta properties are handled by importAnalysis plugin
73972 const importMetaKeys = {};
73973 if (isBuild) {
73974 const env = {
73975 ...config.env,
73976 SSR: !!config.build.ssr
73977 };
73978 for (const key in env) {
73979 importMetaKeys[`import.meta.env.${key}`] = JSON.stringify(env[key]);
73980 }
73981 Object.assign(importMetaKeys, {
73982 'import.meta.env.': `({}).`,
73983 'import.meta.env': JSON.stringify(config.env),
73984 'import.meta.hot': `false`
73985 });
73986 }
73987 const replacements = {
73988 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || config.mode),
73989 'global.process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || config.mode),
73990 'globalThis.process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || config.mode),
73991 ...userDefine,
73992 ...importMetaKeys,
73993 'process.env.': `({}).`,
73994 'global.process.env.': `({}).`,
73995 'globalThis.process.env.': `({}).`
73996 };
73997 const pattern = new RegExp('(?<!\\.)\\b(' +
73998 Object.keys(replacements)
73999 .map((str) => {
74000 return str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
74001 })
74002 .join('|') +
74003 ')\\b', 'g');
74004 return {
74005 name: 'vite:define',
74006 transform(code, id, ssr) {
74007 if (!ssr && !isBuild) {
74008 // for dev we inject actual global defines in the vite client to
74009 // avoid the transform cost.
74010 return;
74011 }
74012 if (
74013 // exclude css and static assets for performance
74014 isCSSRequest(id) ||
74015 config.assetsInclude(id)) {
74016 return;
74017 }
74018 if (ssr && !isBuild) {
74019 // ssr + dev, simple replace
74020 return code.replace(pattern, (_, match) => {
74021 return '' + replacements[match];
74022 });
74023 }
74024 const s = new MagicString(code);
74025 let hasReplaced = false;
74026 let match;
74027 while ((match = pattern.exec(code))) {
74028 hasReplaced = true;
74029 const start = match.index;
74030 const end = start + match[0].length;
74031 const replacement = '' + replacements[match[1]];
74032 s.overwrite(start, end, replacement);
74033 }
74034 if (!hasReplaced) {
74035 return null;
74036 }
74037 const result = { code: s.toString() };
74038 if (config.build.sourcemap) {
74039 result.map = s.generateMap({ hires: true });
74040 }
74041 return result;
74042 }
74043 };
74044}
74045
74046async function resolvePlugins(config, prePlugins, normalPlugins, postPlugins) {
74047 var _a;
74048 const isBuild = config.command === 'build';
74049 const buildPlugins = isBuild
74050 ? (await Promise.resolve().then(function () { return build$1; })).resolveBuildPlugins(config)
74051 : { pre: [], post: [] };
74052 return [
74053 isBuild ? null : preAliasPlugin(),
74054 alias({ entries: config.resolve.alias }),
74055 ...prePlugins,
74056 dynamicImportPolyfillPlugin(config),
74057 resolvePlugin({
74058 ...config.resolve,
74059 root: config.root,
74060 isProduction: config.isProduction,
74061 isBuild,
74062 ssrTarget: (_a = config.ssr) === null || _a === void 0 ? void 0 : _a.target,
74063 asSrc: true
74064 }),
74065 htmlInlineScriptProxyPlugin(),
74066 cssPlugin(config),
74067 config.esbuild !== false ? esbuildPlugin(config.esbuild) : null,
74068 jsonPlugin({
74069 namedExports: true,
74070 ...config.json
74071 }, isBuild),
74072 wasmPlugin(config),
74073 webWorkerPlugin(config),
74074 assetPlugin(config),
74075 ...normalPlugins,
74076 definePlugin(config),
74077 cssPostPlugin(config),
74078 ...buildPlugins.pre,
74079 ...postPlugins,
74080 ...buildPlugins.post,
74081 // internal server-only plugins are always applied after everything else
74082 ...(isBuild
74083 ? []
74084 : [clientInjectionsPlugin(config), importAnalysisPlugin(config)])
74085 ].filter(Boolean);
74086}
74087
74088var main$1 = {};
74089
74090/* @flow */
74091
74092/*::
74093
74094type DotenvParseOptions = {
74095 debug?: boolean
74096}
74097
74098// keys and values from src
74099type DotenvParseOutput = { [string]: string }
74100
74101type DotenvConfigOptions = {
74102 path?: string, // path to .env file
74103 encoding?: string, // encoding of .env file
74104 debug?: string // turn on logging for debugging purposes
74105}
74106
74107type DotenvConfigOutput = {
74108 parsed?: DotenvParseOutput,
74109 error?: Error
74110}
74111
74112*/
74113
74114const fs = fs__default;
74115const path = path__default;
74116const os = require$$0__default$1;
74117
74118function log (message /*: string */) {
74119 console.log(`[dotenv][DEBUG] ${message}`);
74120}
74121
74122const NEWLINE = '\n';
74123const RE_INI_KEY_VAL = /^\s*([\w.-]+)\s*=\s*(.*)?\s*$/;
74124const RE_NEWLINES = /\\n/g;
74125const NEWLINES_MATCH = /\r\n|\n|\r/;
74126
74127// Parses src into an Object
74128function parse (src /*: string | Buffer */, options /*: ?DotenvParseOptions */) /*: DotenvParseOutput */ {
74129 const debug = Boolean(options && options.debug);
74130 const obj = {};
74131
74132 // convert Buffers before splitting into lines and processing
74133 src.toString().split(NEWLINES_MATCH).forEach(function (line, idx) {
74134 // matching "KEY' and 'VAL' in 'KEY=VAL'
74135 const keyValueArr = line.match(RE_INI_KEY_VAL);
74136 // matched?
74137 if (keyValueArr != null) {
74138 const key = keyValueArr[1];
74139 // default undefined or missing values to empty string
74140 let val = (keyValueArr[2] || '');
74141 const end = val.length - 1;
74142 const isDoubleQuoted = val[0] === '"' && val[end] === '"';
74143 const isSingleQuoted = val[0] === "'" && val[end] === "'";
74144
74145 // if single or double quoted, remove quotes
74146 if (isSingleQuoted || isDoubleQuoted) {
74147 val = val.substring(1, end);
74148
74149 // if double quoted, expand newlines
74150 if (isDoubleQuoted) {
74151 val = val.replace(RE_NEWLINES, NEWLINE);
74152 }
74153 } else {
74154 // remove surrounding whitespace
74155 val = val.trim();
74156 }
74157
74158 obj[key] = val;
74159 } else if (debug) {
74160 log(`did not match key and value when parsing line ${idx + 1}: ${line}`);
74161 }
74162 });
74163
74164 return obj
74165}
74166
74167function resolveHome (envPath) {
74168 return envPath[0] === '~' ? path.join(os.homedir(), envPath.slice(1)) : envPath
74169}
74170
74171// Populates process.env from .env file
74172function config (options /*: ?DotenvConfigOptions */) /*: DotenvConfigOutput */ {
74173 let dotenvPath = path.resolve(process.cwd(), '.env');
74174 let encoding /*: string */ = 'utf8';
74175 let debug = false;
74176
74177 if (options) {
74178 if (options.path != null) {
74179 dotenvPath = resolveHome(options.path);
74180 }
74181 if (options.encoding != null) {
74182 encoding = options.encoding;
74183 }
74184 if (options.debug != null) {
74185 debug = true;
74186 }
74187 }
74188
74189 try {
74190 // specifying an encoding returns a string instead of a buffer
74191 const parsed = parse(fs.readFileSync(dotenvPath, { encoding }), { debug });
74192
74193 Object.keys(parsed).forEach(function (key) {
74194 if (!Object.prototype.hasOwnProperty.call(process.env, key)) {
74195 process.env[key] = parsed[key];
74196 } else if (debug) {
74197 log(`"${key}" is already defined in \`process.env\` and will not be overwritten`);
74198 }
74199 });
74200
74201 return { parsed }
74202 } catch (e) {
74203 return { error: e }
74204 }
74205}
74206
74207main$1.config = config;
74208main$1.parse = parse;
74209
74210var dotenvExpand = function (config) {
74211 // if ignoring process.env, use a blank object
74212 var environment = config.ignoreProcessEnv ? {} : process.env;
74213
74214 var interpolate = function (envValue) {
74215 var matches = envValue.match(/(.?\${?(?:[a-zA-Z0-9_]+)?}?)/g) || [];
74216
74217 return matches.reduce(function (newEnv, match) {
74218 var parts = /(.?)\${?([a-zA-Z0-9_]+)?}?/g.exec(match);
74219 var prefix = parts[1];
74220
74221 var value, replacePart;
74222
74223 if (prefix === '\\') {
74224 replacePart = parts[0];
74225 value = replacePart.replace('\\$', '$');
74226 } else {
74227 var key = parts[2];
74228 replacePart = parts[0].substring(prefix.length);
74229 // process.env value 'wins' over .env file's value
74230 value = environment.hasOwnProperty(key) ? environment[key] : (config.parsed[key] || '');
74231
74232 // Resolve recursive interpolations
74233 value = interpolate(value);
74234 }
74235
74236 return newEnv.replace(replacePart, value)
74237 }, envValue)
74238 };
74239
74240 for (var configKey in config.parsed) {
74241 var value = environment.hasOwnProperty(configKey) ? environment[configKey] : config.parsed[configKey];
74242
74243 config.parsed[configKey] = interpolate(value);
74244 }
74245
74246 for (var processKey in config.parsed) {
74247 environment[processKey] = config.parsed[processKey];
74248 }
74249
74250 return config
74251};
74252
74253var main = dotenvExpand;
74254
74255const debug = createDebugger('vite:config');
74256/**
74257 * Type helper to make it easier to use vite.config.ts
74258 * accepts a direct {@link UserConfig} object, or a function that returns it.
74259 * The function receives a {@link ConfigEnv} object that exposes two properties:
74260 * `command` (either `'build'` or `'serve'`), and `mode`.
74261 */
74262function defineConfig(config) {
74263 return config;
74264}
74265async function resolveConfig(inlineConfig, command, defaultMode = 'development') {
74266 var _a, _b, _c, _d, _e;
74267 let config = inlineConfig;
74268 let configFileDependencies = [];
74269 let mode = inlineConfig.mode || defaultMode;
74270 // some dependencies e.g. @vue/compiler-* relies on NODE_ENV for getting
74271 // production-specific behavior, so set it here even though we haven't
74272 // resolve the final mode yet
74273 if (mode === 'production') {
74274 process.env.NODE_ENV = 'production';
74275 }
74276 const configEnv = {
74277 mode,
74278 command
74279 };
74280 let { configFile } = config;
74281 if (configFile !== false) {
74282 const loadResult = await loadConfigFromFile(configEnv, configFile, config.root, config.logLevel);
74283 if (loadResult) {
74284 config = mergeConfig(loadResult.config, config);
74285 configFile = loadResult.path;
74286 configFileDependencies = loadResult.dependencies;
74287 }
74288 }
74289 // Define logger
74290 const logger = createLogger(config.logLevel, {
74291 allowClearScreen: config.clearScreen
74292 });
74293 // user config may provide an alternative mode
74294 mode = config.mode || mode;
74295 // resolve plugins
74296 const rawUserPlugins = (config.plugins || []).flat().filter((p) => {
74297 return p && (!p.apply || p.apply === command);
74298 });
74299 const [prePlugins, normalPlugins, postPlugins] = sortUserPlugins(rawUserPlugins);
74300 // run config hooks
74301 const userPlugins = [...prePlugins, ...normalPlugins, ...postPlugins];
74302 for (const p of userPlugins) {
74303 if (p.config) {
74304 const res = await p.config(config, configEnv);
74305 if (res) {
74306 config = mergeConfig(config, res);
74307 }
74308 }
74309 }
74310 // resolve root
74311 const resolvedRoot = normalizePath$4(config.root ? path__default.resolve(config.root) : process.cwd());
74312 // resolve alias with internal client alias
74313 const resolvedAlias = mergeAlias(
74314 // #1732 the CLIENT_DIR may contain $$ which cannot be used as direct
74315 // replacement string.
74316 // @ts-ignore because @rollup/plugin-alias' type doesn't allow function
74317 // replacement, but its implementation does work with function values.
74318 [{ find: /^\/@vite\//, replacement: () => CLIENT_DIR + '/' }], ((_a = config.resolve) === null || _a === void 0 ? void 0 : _a.alias) || config.alias || []);
74319 const resolveOptions = {
74320 dedupe: config.dedupe,
74321 ...config.resolve,
74322 alias: resolvedAlias
74323 };
74324 // load .env files
74325 const envDir = config.envDir
74326 ? normalizePath$4(path__default.resolve(resolvedRoot, config.envDir))
74327 : resolvedRoot;
74328 const userEnv = inlineConfig.envFile !== false && loadEnv(mode, envDir);
74329 // Note it is possible for user to have a custom mode, e.g. `staging` where
74330 // production-like behavior is expected. This is indicated by NODE_ENV=production
74331 // loaded from `.staging.env` and set by us as VITE_USER_NODE_ENV
74332 const isProduction = (process.env.VITE_USER_NODE_ENV || mode) === 'production';
74333 if (isProduction) {
74334 // in case default mode was not production and is overwritten
74335 process.env.NODE_ENV = 'production';
74336 }
74337 // resolve public base url
74338 const BASE_URL = resolveBaseUrl(config.base, command === 'build', logger);
74339 const resolvedBuildOptions = resolveBuildOptions(config.build);
74340 // resolve cache directory
74341 const pkgPath = lookupFile(resolvedRoot, [`package.json`], true /* pathOnly */);
74342 const cacheDir = config.cacheDir
74343 ? path__default.resolve(resolvedRoot, config.cacheDir)
74344 : pkgPath && path__default.join(path__default.dirname(pkgPath), `node_modules/.vite`);
74345 const assetsFilter = config.assetsInclude
74346 ? createFilter$1(config.assetsInclude)
74347 : () => false;
74348 // create an internal resolver to be used in special scenarios, e.g.
74349 // optimizer & handling css @imports
74350 const createResolver = (options) => {
74351 let aliasContainer;
74352 let resolverContainer;
74353 return async (id, importer, aliasOnly, ssr) => {
74354 var _a, _b;
74355 let container;
74356 if (aliasOnly) {
74357 container =
74358 aliasContainer ||
74359 (aliasContainer = await createPluginContainer({
74360 ...resolved,
74361 plugins: [alias({ entries: resolved.resolve.alias })]
74362 }));
74363 }
74364 else {
74365 container =
74366 resolverContainer ||
74367 (resolverContainer = await createPluginContainer({
74368 ...resolved,
74369 plugins: [
74370 alias({ entries: resolved.resolve.alias }),
74371 resolvePlugin({
74372 ...resolved.resolve,
74373 root: resolvedRoot,
74374 isProduction,
74375 isBuild: command === 'build',
74376 ssrTarget: (_a = resolved.ssr) === null || _a === void 0 ? void 0 : _a.target,
74377 asSrc: true,
74378 preferRelative: false,
74379 tryIndex: true,
74380 ...options
74381 })
74382 ]
74383 }));
74384 }
74385 return (_b = (await container.resolveId(id, importer, undefined, ssr))) === null || _b === void 0 ? void 0 : _b.id;
74386 };
74387 };
74388 const { publicDir } = config;
74389 const resolvedPublicDir = publicDir !== false && publicDir !== ''
74390 ? path__default.resolve(resolvedRoot, typeof publicDir === 'string' ? publicDir : 'public')
74391 : '';
74392 const resolved = {
74393 ...config,
74394 configFile: configFile ? normalizePath$4(configFile) : undefined,
74395 configFileDependencies,
74396 inlineConfig,
74397 root: resolvedRoot,
74398 base: BASE_URL,
74399 resolve: resolveOptions,
74400 publicDir: resolvedPublicDir,
74401 cacheDir,
74402 command,
74403 mode,
74404 isProduction,
74405 plugins: userPlugins,
74406 server: resolveServerOptions(resolvedRoot, config.server),
74407 build: resolvedBuildOptions,
74408 env: {
74409 ...userEnv,
74410 BASE_URL,
74411 MODE: mode,
74412 DEV: !isProduction,
74413 PROD: isProduction
74414 },
74415 assetsInclude(file) {
74416 return DEFAULT_ASSETS_RE.test(file) || assetsFilter(file);
74417 },
74418 logger,
74419 createResolver,
74420 optimizeDeps: {
74421 ...config.optimizeDeps,
74422 esbuildOptions: {
74423 keepNames: (_b = config.optimizeDeps) === null || _b === void 0 ? void 0 : _b.keepNames,
74424 ...(_c = config.optimizeDeps) === null || _c === void 0 ? void 0 : _c.esbuildOptions
74425 }
74426 }
74427 };
74428 resolved.plugins = await resolvePlugins(resolved, prePlugins, normalPlugins, postPlugins);
74429 // call configResolved hooks
74430 await Promise.all(userPlugins.map((p) => { var _a; return (_a = p.configResolved) === null || _a === void 0 ? void 0 : _a.call(p, resolved); }));
74431 if (process.env.DEBUG) {
74432 debug(`using resolved config: %O`, {
74433 ...resolved,
74434 plugins: resolved.plugins.map((p) => p.name)
74435 });
74436 }
74437 // TODO Deprecation warnings - remove when out of beta
74438 const logDeprecationWarning = (deprecatedOption, hint, error) => {
74439 logger.warn(source.yellow.bold(`(!) "${deprecatedOption}" option is deprecated. ${hint}${error ? `\n${error.stack}` : ''}`));
74440 };
74441 if ((_d = config.build) === null || _d === void 0 ? void 0 : _d.base) {
74442 logDeprecationWarning('build.base', '"base" is now a root-level config option.');
74443 config.base = config.build.base;
74444 }
74445 Object.defineProperty(resolvedBuildOptions, 'base', {
74446 enumerable: false,
74447 get() {
74448 logDeprecationWarning('build.base', '"base" is now a root-level config option.', new Error());
74449 return resolved.base;
74450 }
74451 });
74452 if (config.alias) {
74453 logDeprecationWarning('alias', 'Use "resolve.alias" instead.');
74454 }
74455 Object.defineProperty(resolved, 'alias', {
74456 enumerable: false,
74457 get() {
74458 logDeprecationWarning('alias', 'Use "resolve.alias" instead.', new Error());
74459 return resolved.resolve.alias;
74460 }
74461 });
74462 if (config.dedupe) {
74463 logDeprecationWarning('dedupe', 'Use "resolve.dedupe" instead.');
74464 }
74465 Object.defineProperty(resolved, 'dedupe', {
74466 enumerable: false,
74467 get() {
74468 logDeprecationWarning('dedupe', 'Use "resolve.dedupe" instead.', new Error());
74469 return resolved.resolve.dedupe;
74470 }
74471 });
74472 if ((_e = config.optimizeDeps) === null || _e === void 0 ? void 0 : _e.keepNames) {
74473 logDeprecationWarning('optimizeDeps.keepNames', 'Use "optimizeDeps.esbuildOptions.keepNames" instead.');
74474 }
74475 Object.defineProperty(resolved.optimizeDeps, 'keepNames', {
74476 enumerable: false,
74477 get() {
74478 var _a;
74479 logDeprecationWarning('optimizeDeps.keepNames', 'Use "optimizeDeps.esbuildOptions.keepNames" instead.', new Error());
74480 return (_a = resolved.optimizeDeps.esbuildOptions) === null || _a === void 0 ? void 0 : _a.keepNames;
74481 }
74482 });
74483 return resolved;
74484}
74485/**
74486 * Resolve base. Note that some users use Vite to build for non-web targets like
74487 * electron or expects to deploy
74488 */
74489function resolveBaseUrl(base = '/', isBuild, logger) {
74490 // #1669 special treatment for empty for same dir relative base
74491 if (base === '' || base === './') {
74492 return isBuild ? base : '/';
74493 }
74494 if (base.startsWith('.')) {
74495 logger.warn(source.yellow.bold(`(!) invalid "base" option: ${base}. The value can only be an absolute ` +
74496 `URL, ./, or an empty string.`));
74497 base = '/';
74498 }
74499 // external URL
74500 if (isExternalUrl(base)) {
74501 if (!isBuild) {
74502 // get base from full url during dev
74503 const parsed = require$$0$b.parse(base);
74504 base = parsed.pathname || '/';
74505 }
74506 }
74507 else {
74508 // ensure leading slash
74509 if (!base.startsWith('/')) {
74510 logger.warn(source.yellow.bold(`(!) "base" option should start with a slash.`));
74511 base = '/' + base;
74512 }
74513 }
74514 // ensure ending slash
74515 if (!base.endsWith('/')) {
74516 logger.warn(source.yellow.bold(`(!) "base" option should end with a slash.`));
74517 base += '/';
74518 }
74519 return base;
74520}
74521function mergeConfigRecursively(a, b, rootPath) {
74522 const merged = { ...a };
74523 for (const key in b) {
74524 const value = b[key];
74525 if (value == null) {
74526 continue;
74527 }
74528 const existing = merged[key];
74529 if (Array.isArray(existing) && Array.isArray(value)) {
74530 merged[key] = [...existing, ...value];
74531 continue;
74532 }
74533 if (isObject$3(existing) && isObject$3(value)) {
74534 merged[key] = mergeConfigRecursively(existing, value, rootPath ? `${rootPath}.${key}` : key);
74535 continue;
74536 }
74537 // fields that require special handling
74538 if (existing != null) {
74539 if (key === 'alias' && (rootPath === 'resolve' || rootPath === '')) {
74540 merged[key] = mergeAlias(existing, value);
74541 continue;
74542 }
74543 else if (key === 'assetsInclude' && rootPath === '') {
74544 merged[key] = [].concat(existing, value);
74545 continue;
74546 }
74547 }
74548 merged[key] = value;
74549 }
74550 return merged;
74551}
74552function mergeConfig(a, b, isRoot = true) {
74553 return mergeConfigRecursively(a, b, isRoot ? '' : '.');
74554}
74555function mergeAlias(a = [], b = []) {
74556 return [...normalizeAlias(a), ...normalizeAlias(b)];
74557}
74558function normalizeAlias(o) {
74559 return Array.isArray(o)
74560 ? o.map(normalizeSingleAlias)
74561 : Object.keys(o).map((find) => normalizeSingleAlias({
74562 find,
74563 replacement: o[find]
74564 }));
74565}
74566// https://github.com/vitejs/vite/issues/1363
74567// work around https://github.com/rollup/plugins/issues/759
74568function normalizeSingleAlias({ find, replacement }) {
74569 if (typeof find === 'string' &&
74570 find.endsWith('/') &&
74571 replacement.endsWith('/')) {
74572 find = find.slice(0, find.length - 1);
74573 replacement = replacement.slice(0, replacement.length - 1);
74574 }
74575 return { find, replacement };
74576}
74577function sortUserPlugins(plugins) {
74578 const prePlugins = [];
74579 const postPlugins = [];
74580 const normalPlugins = [];
74581 if (plugins) {
74582 plugins.flat().forEach((p) => {
74583 if (p.enforce === 'pre')
74584 prePlugins.push(p);
74585 else if (p.enforce === 'post')
74586 postPlugins.push(p);
74587 else
74588 normalPlugins.push(p);
74589 });
74590 }
74591 return [prePlugins, normalPlugins, postPlugins];
74592}
74593async function loadConfigFromFile(configEnv, configFile, configRoot = process.cwd(), logLevel) {
74594 const start = Date.now();
74595 let resolvedPath;
74596 let isTS = false;
74597 let isMjs = false;
74598 let dependencies = [];
74599 // check package.json for type: "module" and set `isMjs` to true
74600 try {
74601 const pkg = lookupFile(configRoot, ['package.json']);
74602 if (pkg && JSON.parse(pkg).type === 'module') {
74603 isMjs = true;
74604 }
74605 }
74606 catch (e) { }
74607 if (configFile) {
74608 // explicit config path is always resolved from cwd
74609 resolvedPath = path__default.resolve(configFile);
74610 isTS = configFile.endsWith('.ts');
74611 }
74612 else {
74613 // implicit config file loaded from inline root (if present)
74614 // otherwise from cwd
74615 const jsconfigFile = path__default.resolve(configRoot, 'vite.config.js');
74616 if (fs__default.existsSync(jsconfigFile)) {
74617 resolvedPath = jsconfigFile;
74618 }
74619 if (!resolvedPath) {
74620 const mjsconfigFile = path__default.resolve(configRoot, 'vite.config.mjs');
74621 if (fs__default.existsSync(mjsconfigFile)) {
74622 resolvedPath = mjsconfigFile;
74623 isMjs = true;
74624 }
74625 }
74626 if (!resolvedPath) {
74627 const tsconfigFile = path__default.resolve(configRoot, 'vite.config.ts');
74628 if (fs__default.existsSync(tsconfigFile)) {
74629 resolvedPath = tsconfigFile;
74630 isTS = true;
74631 }
74632 }
74633 }
74634 if (!resolvedPath) {
74635 debug('no config file found.');
74636 return null;
74637 }
74638 try {
74639 let userConfig;
74640 if (isMjs) {
74641 const fileUrl = require('url').pathToFileURL(resolvedPath);
74642 if (isTS) {
74643 // before we can register loaders without requiring users to run node
74644 // with --experimental-loader themselves, we have to do a hack here:
74645 // bundle the config file w/ ts transforms first, write it to disk,
74646 // load it with native Node ESM, then delete the file.
74647 const bundled = await bundleConfigFile(resolvedPath, true);
74648 dependencies = bundled.dependencies;
74649 fs__default.writeFileSync(resolvedPath + '.js', bundled.code);
74650 userConfig = (await eval(`import(fileUrl + '.js?t=${Date.now()}')`))
74651 .default;
74652 fs__default.unlinkSync(resolvedPath + '.js');
74653 debug(`TS + native esm config loaded in ${Date.now() - start}ms`, fileUrl);
74654 }
74655 else {
74656 // using eval to avoid this from being compiled away by TS/Rollup
74657 // append a query so that we force reload fresh config in case of
74658 // server restart
74659 userConfig = (await eval(`import(fileUrl + '?t=${Date.now()}')`))
74660 .default;
74661 debug(`native esm config loaded in ${Date.now() - start}ms`, fileUrl);
74662 }
74663 }
74664 if (!userConfig && !isTS && !isMjs) {
74665 // 1. try to directly require the module (assuming commonjs)
74666 try {
74667 // clear cache in case of server restart
74668 delete require.cache[require.resolve(resolvedPath)];
74669 userConfig = require(resolvedPath);
74670 debug(`cjs config loaded in ${Date.now() - start}ms`);
74671 }
74672 catch (e) {
74673 const ignored = new RegExp([
74674 `Cannot use import statement`,
74675 `Must use import to load ES Module`,
74676 // #1635, #2050 some Node 12.x versions don't have esm detection
74677 // so it throws normal syntax errors when encountering esm syntax
74678 `Unexpected token`,
74679 `Unexpected identifier`
74680 ].join('|'));
74681 if (!ignored.test(e.message)) {
74682 throw e;
74683 }
74684 }
74685 }
74686 if (!userConfig) {
74687 // 2. if we reach here, the file is ts or using es import syntax, or
74688 // the user has type: "module" in their package.json (#917)
74689 // transpile es import syntax to require syntax using rollup.
74690 // lazy require rollup (it's actually in dependencies)
74691 const bundled = await bundleConfigFile(resolvedPath);
74692 dependencies = bundled.dependencies;
74693 userConfig = await loadConfigFromBundledFile(resolvedPath, bundled.code);
74694 debug(`bundled config file loaded in ${Date.now() - start}ms`);
74695 }
74696 const config = await (typeof userConfig === 'function'
74697 ? userConfig(configEnv)
74698 : userConfig);
74699 if (!isObject$3(config)) {
74700 throw new Error(`config must export or return an object.`);
74701 }
74702 return {
74703 path: normalizePath$4(resolvedPath),
74704 config,
74705 dependencies
74706 };
74707 }
74708 catch (e) {
74709 createLogger(logLevel).error(source.red(`failed to load config from ${resolvedPath}`));
74710 throw e;
74711 }
74712}
74713async function bundleConfigFile(fileName, mjs = false) {
74714 const result = await esbuild.build({
74715 absWorkingDir: process.cwd(),
74716 entryPoints: [fileName],
74717 outfile: 'out.js',
74718 write: false,
74719 platform: 'node',
74720 bundle: true,
74721 format: mjs ? 'esm' : 'cjs',
74722 sourcemap: 'inline',
74723 metafile: true,
74724 plugins: [
74725 {
74726 name: 'externalize-deps',
74727 setup(build) {
74728 build.onResolve({ filter: /.*/ }, (args) => {
74729 const id = args.path;
74730 if (id[0] !== '.' && !path__default.isAbsolute(id)) {
74731 return {
74732 external: true
74733 };
74734 }
74735 });
74736 }
74737 },
74738 {
74739 name: 'replace-import-meta',
74740 setup(build) {
74741 build.onLoad({ filter: /\.[jt]s$/ }, async (args) => {
74742 const contents = await fs__default.promises.readFile(args.path, 'utf8');
74743 return {
74744 loader: args.path.endsWith('.ts') ? 'ts' : 'js',
74745 contents: contents
74746 .replace(/\bimport\.meta\.url\b/g, JSON.stringify(`file://${args.path}`))
74747 .replace(/\b__dirname\b/g, JSON.stringify(path__default.dirname(args.path)))
74748 .replace(/\b__filename\b/g, JSON.stringify(args.path))
74749 };
74750 });
74751 }
74752 }
74753 ]
74754 });
74755 const { text } = result.outputFiles[0];
74756 return {
74757 code: text,
74758 dependencies: result.metafile ? Object.keys(result.metafile.inputs) : []
74759 };
74760}
74761async function loadConfigFromBundledFile(fileName, bundledCode) {
74762 const extension = path__default.extname(fileName);
74763 const defaultLoader = require.extensions[extension];
74764 require.extensions[extension] = (module, filename) => {
74765 if (filename === fileName) {
74766 module._compile(bundledCode, filename);
74767 }
74768 else {
74769 defaultLoader(module, filename);
74770 }
74771 };
74772 // clear cache in case of server restart
74773 delete require.cache[require.resolve(fileName)];
74774 const raw = require(fileName);
74775 const config = raw.__esModule ? raw.default : raw;
74776 require.extensions[extension] = defaultLoader;
74777 return config;
74778}
74779function loadEnv(mode, envDir, prefix = 'VITE_') {
74780 if (mode === 'local') {
74781 throw new Error(`"local" cannot be used as a mode name because it conflicts with ` +
74782 `the .local postfix for .env files.`);
74783 }
74784 const env = {};
74785 const envFiles = [
74786 /** mode local file */ `.env.${mode}.local`,
74787 /** mode file */ `.env.${mode}`,
74788 /** local file */ `.env.local`,
74789 /** default file */ `.env`
74790 ];
74791 // check if there are actual env variables starting with VITE_*
74792 // these are typically provided inline and should be prioritized
74793 for (const key in process.env) {
74794 if (key.startsWith(prefix) && env[key] === undefined) {
74795 env[key] = process.env[key];
74796 }
74797 }
74798 for (const file of envFiles) {
74799 const path = lookupFile(envDir, [file], true);
74800 if (path) {
74801 const parsed = main$1.parse(fs__default.readFileSync(path), {
74802 debug: !!process.env.DEBUG || undefined
74803 });
74804 // let environment variables use each other
74805 main({
74806 parsed,
74807 // prevent process.env mutation
74808 ignoreProcessEnv: true
74809 });
74810 // only keys that start with prefix are exposed to client
74811 for (const [key, value] of Object.entries(parsed)) {
74812 if (key.startsWith(prefix) && env[key] === undefined) {
74813 env[key] = value;
74814 }
74815 else if (key === 'NODE_ENV') {
74816 // NODE_ENV override in .env file
74817 process.env.VITE_USER_NODE_ENV = value;
74818 }
74819 }
74820 }
74821 }
74822 return env;
74823}
74824
74825exports.build = build;
74826exports.build$1 = build$1;
74827exports.commonjsGlobal = commonjsGlobal;
74828exports.connect = connect;
74829exports.corsMiddleware = corsMiddleware;
74830exports.createLogger = createLogger;
74831exports.createServer = createServer;
74832exports.defineConfig = defineConfig;
74833exports.getAugmentedNamespace = getAugmentedNamespace;
74834exports.getDefaultExportFromCjs = getDefaultExportFromCjs;
74835exports.index = index$1;
74836exports.index$1 = index;
74837exports.loadConfigFromFile = loadConfigFromFile;
74838exports.loadEnv = loadEnv;
74839exports.mergeConfig = mergeConfig;
74840exports.ms = ms$1;
74841exports.normalizePath = normalizePath$4;
74842exports.openBrowser = openBrowser;
74843exports.optimizeDeps = optimizeDeps;
74844exports.printServerUrls = printServerUrls;
74845exports.proxyMiddleware = proxyMiddleware;
74846exports.resolveConfig = resolveConfig;
74847exports.resolveHostname = resolveHostname;
74848exports.resolveHttpServer = resolveHttpServer;
74849exports.resolveHttpsConfig = resolveHttpsConfig;
74850exports.resolvePackageData = resolvePackageData;
74851exports.resolvePackageEntry = resolvePackageEntry;
74852exports.safeBuffer = safeBuffer;
74853exports.send = send$1;
74854exports.sirv = sirv;
74855exports.sortUserPlugins = sortUserPlugins;
74856exports.source = source;
74857exports.sourceMap = sourceMap;
74858exports.vary = vary$1;
74859//# sourceMappingURL=dep-cc49d7be.js.map